chore: 初始化仓库,导入项目基线代码
Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、 Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。 今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
commit
7ec21f35b0
5767 files changed
+1436788
No files matched your search
@@ -0,0 +1,117 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type agentGrantRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewAgentGrantRepository creates a repository backed by GORM.
|
||||
func NewAgentGrantRepository(db *gorm.DB) interfaces.AgentGrantRepository {
|
||||
return &agentGrantRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *agentGrantRepository) FindGrant(
|
||||
ctx context.Context, tenantID uint64, userID string, scope types.GrantScope, key string,
|
||||
) (*types.AgentGrant, error) {
|
||||
var grant types.AgentGrant
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND user_id = ? AND scope = ? AND scope_id = ? AND grant_key = ?",
|
||||
tenantID, userID, scope.Scope, scope.ScopeID, key).
|
||||
First(&grant).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("find agent grant: %w", err)
|
||||
}
|
||||
return &grant, nil
|
||||
}
|
||||
|
||||
func (r *agentGrantRepository) SaveGrant(ctx context.Context, grant *types.AgentGrant) error {
|
||||
if grant == nil || grant.TenantID == 0 || grant.UserID == "" || grant.Scope == "" ||
|
||||
grant.ScopeID == "" || grant.GrantKey == "" {
|
||||
return errors.New("agent grant identity is required")
|
||||
}
|
||||
if grant.Risk == "" {
|
||||
grant.Risk = "write"
|
||||
}
|
||||
now := time.Now()
|
||||
if grant.CreatedAt.IsZero() {
|
||||
grant.CreatedAt = now
|
||||
}
|
||||
grant.UpdatedAt = now
|
||||
err := r.db.WithContext(ctx).Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{
|
||||
{Name: "tenant_id"}, {Name: "user_id"}, {Name: "scope"}, {Name: "scope_id"}, {Name: "grant_key"},
|
||||
},
|
||||
DoUpdates: clause.Assignments(map[string]interface{}{
|
||||
"label": grant.Label,
|
||||
"binding_hash": grant.BindingHash,
|
||||
"risk": grant.Risk,
|
||||
"prompt_id": grant.PromptID,
|
||||
"created_at": grant.CreatedAt,
|
||||
"updated_at": now,
|
||||
"last_used_at": nil,
|
||||
"expires_at": grant.ExpiresAt,
|
||||
"revoked_at": nil,
|
||||
}),
|
||||
}).Create(grant).Error
|
||||
if err != nil {
|
||||
return fmt.Errorf("save agent grant: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *agentGrantRepository) TouchGrant(ctx context.Context, id string, at time.Time) error {
|
||||
return r.db.WithContext(ctx).Model(&types.AgentGrant{}).Where("id = ?", id).
|
||||
UpdateColumn("last_used_at", at).Error
|
||||
}
|
||||
|
||||
func (r *agentGrantRepository) ListGrants(
|
||||
ctx context.Context, tenantID uint64, userID, scope, scopeID string,
|
||||
) ([]*types.AgentGrant, error) {
|
||||
var grants []*types.AgentGrant
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND user_id = ? AND scope = ? AND scope_id = ? AND revoked_at IS NULL",
|
||||
tenantID, userID, scope, scopeID).
|
||||
Order("created_at DESC").
|
||||
Find(&grants).Error
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list agent grants: %w", err)
|
||||
}
|
||||
return grants, nil
|
||||
}
|
||||
|
||||
func (r *agentGrantRepository) RevokeGrant(
|
||||
ctx context.Context, tenantID uint64, userID, id string, at time.Time,
|
||||
) (bool, error) {
|
||||
res := r.db.WithContext(ctx).Model(&types.AgentGrant{}).
|
||||
Where("id = ? AND tenant_id = ? AND user_id = ? AND revoked_at IS NULL", id, tenantID, userID).
|
||||
Updates(map[string]interface{}{"revoked_at": at, "updated_at": at})
|
||||
if res.Error != nil {
|
||||
return false, fmt.Errorf("revoke agent grant: %w", res.Error)
|
||||
}
|
||||
return res.RowsAffected > 0, nil
|
||||
}
|
||||
|
||||
func (r *agentGrantRepository) DeleteScopes(
|
||||
ctx context.Context, tenantID uint64, scope string, scopeIDs []string,
|
||||
) error {
|
||||
if len(scopeIDs) == 0 {
|
||||
return nil
|
||||
}
|
||||
return r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND scope = ? AND scope_id IN ?", tenantID, scope, scopeIDs).
|
||||
Delete(&types.AgentGrant{}).Error
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestAgentGrantRepositoryLifecycle(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
sqlDB, err := db.DB()
|
||||
require.NoError(t, err)
|
||||
sqlDB.SetMaxOpenConns(1)
|
||||
t.Cleanup(func() { require.NoError(t, sqlDB.Close()) })
|
||||
require.NoError(t, db.AutoMigrate(&types.AgentGrant{}))
|
||||
|
||||
ctx := context.Background()
|
||||
repo := NewAgentGrantRepository(db)
|
||||
scope := types.GrantScope{Scope: types.AgentGrantScopeSession, ScopeID: "root"}
|
||||
save := func(user, label string) {
|
||||
require.NoError(t, repo.SaveGrant(ctx, &types.AgentGrant{
|
||||
TenantID: 7, UserID: user, Scope: scope.Scope, ScopeID: scope.ScopeID,
|
||||
GrantKey: "mcp:svc/write#abc", Label: label,
|
||||
}))
|
||||
}
|
||||
save("u1", "first")
|
||||
save("u2", "other user")
|
||||
|
||||
found, err := repo.FindGrant(ctx, 7, "u1", scope, "mcp:svc/write#abc")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, found)
|
||||
missing, err := repo.FindGrant(ctx, 8, "u1", scope, "mcp:svc/write#abc")
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, missing, "grants do not cross tenants")
|
||||
|
||||
used := time.Now()
|
||||
require.NoError(t, repo.TouchGrant(ctx, found.ID, used))
|
||||
listed, err := repo.ListGrants(ctx, 7, "u1", scope.Scope, scope.ScopeID)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, listed, 1)
|
||||
require.NotNil(t, listed[0].LastUsedAt)
|
||||
|
||||
revoked, err := repo.RevokeGrant(ctx, 7, "u2", found.ID, time.Now())
|
||||
require.NoError(t, err)
|
||||
assert.False(t, revoked, "only the owner revokes a grant")
|
||||
revoked, err = repo.RevokeGrant(ctx, 7, "u1", found.ID, time.Now())
|
||||
require.NoError(t, err)
|
||||
assert.True(t, revoked)
|
||||
listed, err = repo.ListGrants(ctx, 7, "u1", scope.Scope, scope.ScopeID)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, listed)
|
||||
|
||||
save("u1", "again")
|
||||
again, err := repo.FindGrant(ctx, 7, "u1", scope, "mcp:svc/write#abc")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, again)
|
||||
assert.Equal(t, found.ID, again.ID, "approving again revives the same row")
|
||||
assert.Nil(t, again.RevokedAt)
|
||||
assert.Nil(t, again.LastUsedAt)
|
||||
assert.Equal(t, "again", again.Label)
|
||||
|
||||
require.NoError(t, repo.DeleteScopes(ctx, 7, scope.Scope, []string{"root"}))
|
||||
gone, err := repo.FindGrant(ctx, 7, "u1", scope, "mcp:svc/write#abc")
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, gone)
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
// AgentPromptRepository implements interfaces.AgentPromptRepository.
|
||||
type AgentPromptRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewAgentPromptRepository creates a repository backed by GORM.
|
||||
func NewAgentPromptRepository(db *gorm.DB) interfaces.AgentPromptRepository {
|
||||
return &AgentPromptRepository{db: db}
|
||||
}
|
||||
|
||||
// Create inserts a new prompt row.
|
||||
func (r *AgentPromptRepository) Create(ctx context.Context, row *types.AgentPrompt) error {
|
||||
if row == nil {
|
||||
return errors.New("agent prompt row is nil")
|
||||
}
|
||||
if err := r.db.WithContext(ctx).Create(row).Error; err != nil {
|
||||
return fmt.Errorf("create agent prompt: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get returns the row, or nil when it does not exist.
|
||||
func (r *AgentPromptRepository) Get(ctx context.Context, id string) (*types.AgentPrompt, error) {
|
||||
var row types.AgentPrompt
|
||||
err := r.db.WithContext(ctx).Where("id = ?", id).First(&row).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get agent prompt: %w", err)
|
||||
}
|
||||
return &row, nil
|
||||
}
|
||||
|
||||
// Transition applies a compare-and-set state change.
|
||||
func (r *AgentPromptRepository) Transition(
|
||||
ctx context.Context, id string, t types.AgentPromptTransition,
|
||||
) (bool, error) {
|
||||
if len(t.From) == 0 || t.To == "" {
|
||||
return false, errors.New("transition requires from and to states")
|
||||
}
|
||||
// A map keeps empty values that a struct update would skip.
|
||||
updates := map[string]interface{}{
|
||||
"status": t.To,
|
||||
"updated_at": time.Now(),
|
||||
}
|
||||
if len(t.Response) > 0 {
|
||||
updates["response"] = t.Response
|
||||
}
|
||||
if t.CloseReason != nil {
|
||||
updates["close_reason"] = *t.CloseReason
|
||||
}
|
||||
if t.ResolvedBy != nil {
|
||||
updates["resolved_by"] = *t.ResolvedBy
|
||||
}
|
||||
if t.ResolvedAt != nil {
|
||||
updates["resolved_at"] = *t.ResolvedAt
|
||||
}
|
||||
if t.ExpiresAt != nil {
|
||||
updates["expires_at"] = *t.ExpiresAt
|
||||
}
|
||||
if t.Owner != nil {
|
||||
updates["owner_instance"] = *t.Owner
|
||||
}
|
||||
if t.LeaseUntil != nil {
|
||||
updates["lease_until"] = *t.LeaseUntil
|
||||
}
|
||||
q := r.db.WithContext(ctx).Model(&types.AgentPrompt{}).
|
||||
Where("id = ? AND status IN ?", id, t.From)
|
||||
if t.UnexpiredAt != nil {
|
||||
q = q.Where("expires_at IS NULL OR expires_at > ?", *t.UnexpiredAt)
|
||||
}
|
||||
if t.ExpectedOwner != nil {
|
||||
q = q.Where("owner_instance = ?", *t.ExpectedOwner)
|
||||
}
|
||||
if t.LeaseBefore != nil {
|
||||
q = q.Where("lease_until < ?", *t.LeaseBefore)
|
||||
}
|
||||
res := q.Updates(updates)
|
||||
if res.Error != nil {
|
||||
return false, fmt.Errorf("transition agent prompt: %w", res.Error)
|
||||
}
|
||||
return res.RowsAffected == 1, nil
|
||||
}
|
||||
|
||||
// leasedStatuses are the states whose row is held by an owner replica.
|
||||
var leasedStatuses = []string{types.AgentPromptPending, types.AgentPromptAnswered, types.AgentPromptExecuting}
|
||||
|
||||
// RenewLease extends the lease of a leased row still held by owner.
|
||||
func (r *AgentPromptRepository) RenewLease(
|
||||
ctx context.Context, id, owner string, until time.Time,
|
||||
) (bool, error) {
|
||||
res := r.db.WithContext(ctx).Model(&types.AgentPrompt{}).
|
||||
Where("id = ? AND status IN ? AND owner_instance = ?", id, leasedStatuses, owner).
|
||||
Updates(map[string]interface{}{"lease_until": until, "updated_at": time.Now()})
|
||||
if res.Error != nil {
|
||||
return false, fmt.Errorf("renew agent prompt lease: %w", res.Error)
|
||||
}
|
||||
return res.RowsAffected == 1, nil
|
||||
}
|
||||
|
||||
// ListStaleLeases returns rows in statuses whose owner stopped renewing.
|
||||
func (r *AgentPromptRepository) ListStaleLeases(
|
||||
ctx context.Context, statuses []string, before time.Time, limit int,
|
||||
) ([]*types.AgentPrompt, error) {
|
||||
var rows []*types.AgentPrompt
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("status IN ? AND lease_until < ?", statuses, before).
|
||||
Order("lease_until").
|
||||
Limit(limit).
|
||||
Find(&rows).Error
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list stale agent prompts: %w", err)
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// ListExpired returns suspended rows past their expiry.
|
||||
func (r *AgentPromptRepository) ListExpired(
|
||||
ctx context.Context, before time.Time, limit int,
|
||||
) ([]*types.AgentPrompt, error) {
|
||||
var rows []*types.AgentPrompt
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("status = ? AND expires_at < ?", types.AgentPromptSuspended, before).
|
||||
Order("expires_at").
|
||||
Limit(limit).
|
||||
Find(&rows).Error
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list expired agent prompts: %w", err)
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// ListBySession returns the session's rows in statuses.
|
||||
func (r *AgentPromptRepository) ListBySession(
|
||||
ctx context.Context, sessionID string, statuses []string,
|
||||
) ([]*types.AgentPrompt, error) {
|
||||
var rows []*types.AgentPrompt
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("session_id = ? AND status IN ?", sessionID, statuses).
|
||||
Order("created_at").
|
||||
Find(&rows).Error
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list session agent prompts: %w", err)
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// ListByMessages returns the session's rows in one of statuses raised by one
|
||||
// of the assistant messages.
|
||||
func (r *AgentPromptRepository) ListByMessages(
|
||||
ctx context.Context, sessionID string, messageIDs, statuses []string,
|
||||
) ([]*types.AgentPrompt, error) {
|
||||
var rows []*types.AgentPrompt
|
||||
if len(messageIDs) == 0 {
|
||||
return rows, nil
|
||||
}
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("session_id = ? AND assistant_message_id IN ? AND status IN ?", sessionID, messageIDs, statuses).
|
||||
Order("created_at").
|
||||
Find(&rows).Error
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list message agent prompts: %w", err)
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// AgentRunSuspensionRepository implements interfaces.AgentRunSuspensionRepository.
|
||||
type AgentRunSuspensionRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewAgentRunSuspensionRepository creates a repository backed by GORM.
|
||||
func NewAgentRunSuspensionRepository(db *gorm.DB) interfaces.AgentRunSuspensionRepository {
|
||||
return &AgentRunSuspensionRepository{db: db}
|
||||
}
|
||||
|
||||
// Save inserts or replaces the run state of a message.
|
||||
func (r *AgentRunSuspensionRepository) Save(ctx context.Context, row *types.AgentRunSuspension) error {
|
||||
if row == nil || row.AssistantMessageID == "" {
|
||||
return errors.New("agent run suspension requires an assistant message id")
|
||||
}
|
||||
now := time.Now()
|
||||
if row.CreatedAt.IsZero() {
|
||||
row.CreatedAt = now
|
||||
}
|
||||
row.UpdatedAt = now
|
||||
err := r.db.WithContext(ctx).Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "assistant_message_id"}},
|
||||
DoUpdates: clause.AssignmentColumns([]string{
|
||||
"tenant_id", "session_id", "prompt_id", "snapshot_version", "snapshot", "updated_at",
|
||||
}),
|
||||
}).Create(row).Error
|
||||
if err != nil {
|
||||
return fmt.Errorf("save agent run suspension: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get returns the run state of a message, or nil when there is none.
|
||||
func (r *AgentRunSuspensionRepository) Get(
|
||||
ctx context.Context, assistantMessageID string,
|
||||
) (*types.AgentRunSuspension, error) {
|
||||
var row types.AgentRunSuspension
|
||||
err := r.db.WithContext(ctx).Where("assistant_message_id = ?", assistantMessageID).First(&row).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get agent run suspension: %w", err)
|
||||
}
|
||||
return &row, nil
|
||||
}
|
||||
|
||||
// Delete removes the run state while it still belongs to promptID.
|
||||
func (r *AgentRunSuspensionRepository) Delete(ctx context.Context, assistantMessageID, promptID string) error {
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("assistant_message_id = ? AND prompt_id = ?", assistantMessageID, promptID).
|
||||
Delete(&types.AgentRunSuspension{}).Error
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete agent run suspension: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func newAgentPromptTestRepo(t *testing.T) *AgentPromptRepository {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
sqlDB, err := db.DB()
|
||||
require.NoError(t, err)
|
||||
sqlDB.SetMaxOpenConns(1)
|
||||
t.Cleanup(func() { require.NoError(t, sqlDB.Close()) })
|
||||
require.NoError(t, db.AutoMigrate(&types.AgentPrompt{}))
|
||||
return NewAgentPromptRepository(db).(*AgentPromptRepository)
|
||||
}
|
||||
|
||||
func TestAgentPromptRepositoryTransitionIsCompareAndSet(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := newAgentPromptTestRepo(t)
|
||||
lease := time.Now().Add(time.Minute)
|
||||
require.NoError(t, repo.Create(ctx, &types.AgentPrompt{
|
||||
ID: "p1", TenantID: 7, UserID: "alice", SessionID: "s1",
|
||||
Kind: types.AgentPromptKindToolApproval, Status: types.AgentPromptPending,
|
||||
Request: types.JSON(`{"args":{"a":1}}`), OwnerInstance: "owner", LeaseUntil: &lease,
|
||||
}))
|
||||
|
||||
resolvedBy := "alice"
|
||||
ok, err := repo.Transition(ctx, "p1", types.AgentPromptTransition{
|
||||
From: []string{types.AgentPromptPending}, To: types.AgentPromptAnswered,
|
||||
Response: types.JSON(`{"approved":true}`), ResolvedBy: &resolvedBy,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.True(t, ok)
|
||||
|
||||
ok, err = repo.Transition(ctx, "p1", types.AgentPromptTransition{
|
||||
From: []string{types.AgentPromptPending}, To: types.AgentPromptAnswered,
|
||||
Response: types.JSON(`{"approved":false}`),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.False(t, ok, "a second answer must lose")
|
||||
|
||||
row, err := repo.Get(ctx, "p1")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, types.AgentPromptAnswered, row.Status)
|
||||
require.JSONEq(t, `{"approved":true}`, string(row.Response))
|
||||
require.JSONEq(t, `{"args":{"a":1}}`, string(row.Request))
|
||||
require.Equal(t, "alice", row.ResolvedBy)
|
||||
|
||||
missing, err := repo.Get(ctx, "nope")
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, missing)
|
||||
}
|
||||
|
||||
func TestAgentPromptRepositoryRenewLeaseRequiresPendingOwner(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := newAgentPromptTestRepo(t)
|
||||
require.NoError(t, repo.Create(ctx, &types.AgentPrompt{
|
||||
ID: "p1", TenantID: 7, SessionID: "s1",
|
||||
Kind: types.AgentPromptKindToolApproval, Status: types.AgentPromptPending,
|
||||
OwnerInstance: "owner",
|
||||
}))
|
||||
|
||||
until := time.Now().Add(time.Minute)
|
||||
ok, err := repo.RenewLease(ctx, "p1", "intruder", until)
|
||||
require.NoError(t, err)
|
||||
require.False(t, ok)
|
||||
|
||||
ok, err = repo.RenewLease(ctx, "p1", "owner", until)
|
||||
require.NoError(t, err)
|
||||
require.True(t, ok)
|
||||
|
||||
_, err = repo.Transition(ctx, "p1", types.AgentPromptTransition{
|
||||
From: []string{types.AgentPromptPending}, To: types.AgentPromptExpired,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
ok, err = repo.RenewLease(ctx, "p1", "owner", until)
|
||||
require.NoError(t, err)
|
||||
require.False(t, ok, "a closed row has no lease to renew")
|
||||
}
|
||||
|
||||
func TestAgentPromptRepositoryListStaleLeasesOnlyPendingAndLapsed(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := newAgentPromptTestRepo(t)
|
||||
now := time.Now()
|
||||
lease := func(d time.Duration) *time.Time { at := now.Add(d); return &at }
|
||||
for _, row := range []*types.AgentPrompt{
|
||||
{ID: "older", Status: types.AgentPromptPending, LeaseUntil: lease(-2 * time.Minute)},
|
||||
{ID: "old", Status: types.AgentPromptPending, LeaseUntil: lease(-time.Minute)},
|
||||
{ID: "alive", Status: types.AgentPromptPending, LeaseUntil: lease(time.Minute)},
|
||||
{ID: "closed", Status: types.AgentPromptSuspended, LeaseUntil: lease(-time.Minute)},
|
||||
} {
|
||||
row.TenantID, row.SessionID, row.Kind = 7, "s1", types.AgentPromptKindToolApproval
|
||||
require.NoError(t, repo.Create(ctx, row))
|
||||
}
|
||||
|
||||
rows, err := repo.ListStaleLeases(ctx, []string{types.AgentPromptPending}, now, 10)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, rows, 2)
|
||||
require.Equal(t, "older", rows[0].ID)
|
||||
require.Equal(t, "old", rows[1].ID)
|
||||
|
||||
rows, err = repo.ListStaleLeases(ctx, []string{types.AgentPromptPending}, now, 1)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, rows, 1)
|
||||
}
|
||||
|
||||
func TestAgentRunSuspensionRepositorySaveReplacesAndDeleteIsConditional(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
sqlDB, err := db.DB()
|
||||
require.NoError(t, err)
|
||||
sqlDB.SetMaxOpenConns(1)
|
||||
t.Cleanup(func() { require.NoError(t, sqlDB.Close()) })
|
||||
require.NoError(t, db.AutoMigrate(&types.AgentRunSuspension{}))
|
||||
repo := NewAgentRunSuspensionRepository(db)
|
||||
|
||||
missing, err := repo.Get(ctx, "m1")
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, missing)
|
||||
|
||||
require.NoError(t, repo.Save(ctx, &types.AgentRunSuspension{
|
||||
AssistantMessageID: "m1", TenantID: 7, SessionID: "s1", PromptID: "p1",
|
||||
SnapshotVersion: 1, Snapshot: types.JSON(`{"round":1}`),
|
||||
}))
|
||||
require.NoError(t, repo.Save(ctx, &types.AgentRunSuspension{
|
||||
AssistantMessageID: "m1", TenantID: 7, SessionID: "s1", PromptID: "p2",
|
||||
SnapshotVersion: 1, Snapshot: types.JSON(`{"round":2}`),
|
||||
}))
|
||||
row, err := repo.Get(ctx, "m1")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "p2", row.PromptID)
|
||||
require.JSONEq(t, `{"round":2}`, string(row.Snapshot))
|
||||
|
||||
require.NoError(t, repo.Delete(ctx, "m1", "p1"))
|
||||
row, err = repo.Get(ctx, "m1")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, row, "an older prompt must not drop a newer prompt's state")
|
||||
|
||||
require.NoError(t, repo.Delete(ctx, "m1", "p2"))
|
||||
row, err = repo.Get(ctx, "m1")
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, row)
|
||||
|
||||
require.Error(t, repo.Save(ctx, &types.AgentRunSuspension{}))
|
||||
}
|
||||
|
||||
func TestAgentPromptRepositoryExpiryAndSessionQueries(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := newAgentPromptTestRepo(t)
|
||||
now := time.Now()
|
||||
at := func(d time.Duration) *time.Time { v := now.Add(d); return &v }
|
||||
for _, row := range []*types.AgentPrompt{
|
||||
{ID: "expired", SessionID: "s1", Status: types.AgentPromptSuspended, ExpiresAt: at(-time.Minute)},
|
||||
{ID: "open", SessionID: "s1", Status: types.AgentPromptSuspended, ExpiresAt: at(time.Hour)},
|
||||
{ID: "forever", SessionID: "s2", Status: types.AgentPromptSuspended},
|
||||
{ID: "done", SessionID: "s1", Status: types.AgentPromptDone, ExpiresAt: at(-time.Minute)},
|
||||
} {
|
||||
row.TenantID, row.Kind = 7, types.AgentPromptKindToolApproval
|
||||
require.NoError(t, repo.Create(ctx, row))
|
||||
}
|
||||
|
||||
expired, err := repo.ListExpired(ctx, now, 10)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, expired, 1)
|
||||
require.Equal(t, "expired", expired[0].ID)
|
||||
|
||||
inSession, err := repo.ListBySession(ctx, "s1", []string{types.AgentPromptSuspended})
|
||||
require.NoError(t, err)
|
||||
ids := []string{}
|
||||
for _, r := range inSession {
|
||||
ids = append(ids, r.ID)
|
||||
}
|
||||
require.ElementsMatch(t, []string{"expired", "open"}, ids)
|
||||
|
||||
answer := func(id string) bool {
|
||||
ok, err := repo.Transition(ctx, id, types.AgentPromptTransition{
|
||||
From: []string{types.AgentPromptSuspended}, To: types.AgentPromptAnswered, UnexpiredAt: &now,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return ok
|
||||
}
|
||||
require.False(t, answer("expired"), "an expired prompt cannot be answered")
|
||||
require.True(t, answer("open"))
|
||||
require.True(t, answer("forever"), "a prompt without expiry stays answerable")
|
||||
}
|
||||
|
||||
func TestAgentPromptTransitionRechecksOwnerAndLease(t *testing.T) {
|
||||
repo := newAgentPromptTestRepo(t)
|
||||
ctx := t.Context()
|
||||
past, now, future := time.Now().Add(-time.Minute), time.Now(), time.Now().Add(time.Minute)
|
||||
owner, other := "owner", "other"
|
||||
require.NoError(t, repo.Create(ctx, &types.AgentPrompt{
|
||||
ID: "p", TenantID: 1, SessionID: "s", Kind: "ask_user",
|
||||
Status: types.AgentPromptPending, OwnerInstance: owner, LeaseUntil: &past,
|
||||
}))
|
||||
transition := types.AgentPromptTransition{
|
||||
From: []string{types.AgentPromptPending}, To: types.AgentPromptSuspended,
|
||||
ExpectedOwner: &other, LeaseBefore: &now,
|
||||
}
|
||||
ok, err := repo.Transition(ctx, "p", transition)
|
||||
require.NoError(t, err)
|
||||
require.False(t, ok)
|
||||
transition.ExpectedOwner = &owner
|
||||
_, err = repo.RenewLease(ctx, "p", owner, future)
|
||||
require.NoError(t, err)
|
||||
ok, err = repo.Transition(ctx, "p", transition)
|
||||
require.NoError(t, err)
|
||||
require.False(t, ok)
|
||||
_, err = repo.RenewLease(ctx, "p", owner, past)
|
||||
require.NoError(t, err)
|
||||
ok, err = repo.Transition(ctx, "p", transition)
|
||||
require.NoError(t, err)
|
||||
require.True(t, ok)
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrAgentShareNotFound = errors.New("agent share not found")
|
||||
ErrAgentShareAlreadyExists = errors.New("agent already shared to this organization")
|
||||
)
|
||||
|
||||
// agentShareRepository implements AgentShareRepository interface
|
||||
type agentShareRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewAgentShareRepository creates a new agent share repository
|
||||
func NewAgentShareRepository(db *gorm.DB) interfaces.AgentShareRepository {
|
||||
return &agentShareRepository{db: db}
|
||||
}
|
||||
|
||||
// Create creates a new agent share record
|
||||
func (r *agentShareRepository) Create(ctx context.Context, share *types.AgentShare) error {
|
||||
var count int64
|
||||
r.db.WithContext(ctx).Model(&types.AgentShare{}).
|
||||
Where("agent_id = ? AND source_tenant_id = ? AND organization_id = ? AND deleted_at IS NULL",
|
||||
share.AgentID, share.SourceTenantID, share.OrganizationID).
|
||||
Count(&count)
|
||||
if count > 0 {
|
||||
return ErrAgentShareAlreadyExists
|
||||
}
|
||||
return r.db.WithContext(ctx).Create(share).Error
|
||||
}
|
||||
|
||||
// GetByID gets a share record by ID
|
||||
func (r *agentShareRepository) GetByID(ctx context.Context, id string) (*types.AgentShare, error) {
|
||||
var share types.AgentShare
|
||||
err := r.db.WithContext(ctx).Where("id = ?", id).First(&share).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrAgentShareNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &share, nil
|
||||
}
|
||||
|
||||
// GetByAgentAndOrg gets a share record by agent ID and organization ID
|
||||
func (r *agentShareRepository) GetByAgentAndOrg(ctx context.Context, agentID string, orgID string) (*types.AgentShare, error) {
|
||||
var share types.AgentShare
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("agent_id = ? AND organization_id = ?", agentID, orgID).
|
||||
First(&share).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrAgentShareNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &share, nil
|
||||
}
|
||||
|
||||
// Update updates a share record
|
||||
func (r *agentShareRepository) Update(ctx context.Context, share *types.AgentShare) error {
|
||||
return r.db.WithContext(ctx).Model(&types.AgentShare{}).
|
||||
Where("id = ?", share.ID).Updates(share).Error
|
||||
}
|
||||
|
||||
// Delete soft deletes a share record
|
||||
func (r *agentShareRepository) Delete(ctx context.Context, id string) error {
|
||||
return r.db.WithContext(ctx).Where("id = ?", id).Delete(&types.AgentShare{}).Error
|
||||
}
|
||||
|
||||
// DeleteByAgentIDAndSourceTenant soft deletes all share records for an agent (id, tenant_id)
|
||||
func (r *agentShareRepository) DeleteByAgentIDAndSourceTenant(ctx context.Context, agentID string, sourceTenantID uint64) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Where("agent_id = ? AND source_tenant_id = ?", agentID, sourceTenantID).
|
||||
Delete(&types.AgentShare{}).Error
|
||||
}
|
||||
|
||||
// DeleteByOrganizationID soft deletes all share records for an organization
|
||||
func (r *agentShareRepository) DeleteByOrganizationID(ctx context.Context, orgID string) error {
|
||||
return r.db.WithContext(ctx).Where("organization_id = ?", orgID).Delete(&types.AgentShare{}).Error
|
||||
}
|
||||
|
||||
// DeleteByOrganizationAndSourceTenant soft deletes the shares a tenant made
|
||||
// into an organization (e.g. when the tenant leaves or is removed from it).
|
||||
func (r *agentShareRepository) DeleteByOrganizationAndSourceTenant(
|
||||
ctx context.Context, orgID string, sourceTenantID uint64,
|
||||
) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Where("organization_id = ? AND source_tenant_id = ?", orgID, sourceTenantID).
|
||||
Delete(&types.AgentShare{}).Error
|
||||
}
|
||||
|
||||
// agentShareSourceMemberJoin keeps a share effective only while its source
|
||||
// tenant is still a member of the organization; see kbShareSourceMemberJoin.
|
||||
const agentShareSourceMemberJoin = "JOIN organization_tenant_members src_member " +
|
||||
"ON src_member.organization_id = agent_shares.organization_id " +
|
||||
"AND src_member.tenant_id = agent_shares.source_tenant_id"
|
||||
|
||||
// ListByAgent lists all share records for an agent
|
||||
func (r *agentShareRepository) ListByAgent(ctx context.Context, agentID string) ([]*types.AgentShare, error) {
|
||||
var shares []*types.AgentShare
|
||||
err := r.db.WithContext(ctx).
|
||||
Preload("Organization").
|
||||
Where("agent_id = ?", agentID).
|
||||
Order("created_at DESC").
|
||||
Find(&shares).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return shares, nil
|
||||
}
|
||||
|
||||
// ListByOrganization lists all share records for an organization (excluding deleted agents)
|
||||
func (r *agentShareRepository) ListByOrganization(ctx context.Context, orgID string) ([]*types.AgentShare, error) {
|
||||
var shares []*types.AgentShare
|
||||
err := r.db.WithContext(ctx).
|
||||
Joins("JOIN custom_agents ON custom_agents.id = agent_shares.agent_id AND custom_agents.tenant_id = agent_shares.source_tenant_id AND custom_agents.deleted_at IS NULL").
|
||||
Joins(agentShareSourceMemberJoin).
|
||||
Preload("Agent").
|
||||
Preload("Organization").
|
||||
Where("agent_shares.organization_id = ? AND agent_shares.deleted_at IS NULL", orgID).
|
||||
Order("agent_shares.created_at DESC").
|
||||
Find(&shares).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return shares, nil
|
||||
}
|
||||
|
||||
// ListByOrganizations lists all share records for the given organizations (batch).
|
||||
func (r *agentShareRepository) ListByOrganizations(ctx context.Context, orgIDs []string) ([]*types.AgentShare, error) {
|
||||
if len(orgIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var shares []*types.AgentShare
|
||||
err := r.db.WithContext(ctx).
|
||||
Joins("JOIN custom_agents ON custom_agents.id = agent_shares.agent_id AND custom_agents.tenant_id = agent_shares.source_tenant_id AND custom_agents.deleted_at IS NULL").
|
||||
Joins(agentShareSourceMemberJoin).
|
||||
Preload("Agent").
|
||||
Preload("Organization").
|
||||
Where("agent_shares.organization_id IN ? AND agent_shares.deleted_at IS NULL", orgIDs).
|
||||
Order("agent_shares.created_at DESC").
|
||||
Find(&shares).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return shares, nil
|
||||
}
|
||||
|
||||
// CountByOrganizations returns share counts per organization (only orgs in orgIDs). Excludes deleted agents.
|
||||
func (r *agentShareRepository) CountByOrganizations(ctx context.Context, orgIDs []string) (map[string]int64, error) {
|
||||
if len(orgIDs) == 0 {
|
||||
return make(map[string]int64), nil
|
||||
}
|
||||
type row struct {
|
||||
OrgID string `gorm:"column:organization_id"`
|
||||
Count int64 `gorm:"column:count"`
|
||||
}
|
||||
var rows []row
|
||||
err := r.db.WithContext(ctx).Model(&types.AgentShare{}).
|
||||
Joins("JOIN custom_agents ON custom_agents.id = agent_shares.agent_id AND custom_agents.tenant_id = agent_shares.source_tenant_id AND custom_agents.deleted_at IS NULL").
|
||||
Joins(agentShareSourceMemberJoin).
|
||||
Select("agent_shares.organization_id as organization_id, COUNT(*) as count").
|
||||
Where("agent_shares.organization_id IN ? AND agent_shares.deleted_at IS NULL", orgIDs).
|
||||
Group("agent_shares.organization_id").
|
||||
Find(&rows).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make(map[string]int64)
|
||||
for _, o := range orgIDs {
|
||||
out[o] = 0
|
||||
}
|
||||
for _, r := range rows {
|
||||
out[r.OrgID] = r.Count
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ListSharedAgentsForTenant lists all agents shared to organizations that the
|
||||
// caller's tenant participates in. Plan 3 of #1303 keys this on tenant rather
|
||||
// than user.
|
||||
func (r *agentShareRepository) ListSharedAgentsForTenant(ctx context.Context, tenantID uint64) ([]*types.AgentShare, error) {
|
||||
var shares []*types.AgentShare
|
||||
err := r.db.WithContext(ctx).
|
||||
Joins("JOIN custom_agents ON custom_agents.id = agent_shares.agent_id AND custom_agents.tenant_id = agent_shares.source_tenant_id AND custom_agents.deleted_at IS NULL").
|
||||
Joins(agentShareSourceMemberJoin).
|
||||
Preload("Agent").
|
||||
Preload("Organization").
|
||||
Joins("JOIN organization_tenant_members otm ON otm.organization_id = agent_shares.organization_id").
|
||||
Joins("JOIN organizations ON organizations.id = agent_shares.organization_id AND organizations.deleted_at IS NULL").
|
||||
Where("otm.tenant_id = ?", tenantID).
|
||||
Where("agent_shares.deleted_at IS NULL").
|
||||
Order("agent_shares.created_at DESC").
|
||||
Find(&shares).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return shares, nil
|
||||
}
|
||||
|
||||
// GetShareByAgentIDForTenant returns one share for the given agentID that the
|
||||
// tenant can reach (tenant participates in some org with the share), excluding
|
||||
// source_tenant_id == excludeTenantID. Single query.
|
||||
func (r *agentShareRepository) GetShareByAgentIDForTenant(ctx context.Context, tenantID uint64, agentID string, excludeTenantID uint64) (*types.AgentShare, error) {
|
||||
var share types.AgentShare
|
||||
tx := r.db.WithContext(ctx).
|
||||
Joins("JOIN organization_tenant_members otm ON otm.organization_id = agent_shares.organization_id").
|
||||
Joins("JOIN organizations ON organizations.id = agent_shares.organization_id "+
|
||||
"AND organizations.deleted_at IS NULL").
|
||||
Joins(agentShareSourceMemberJoin).
|
||||
Where("agent_shares.agent_id = ?", agentID).
|
||||
Where("otm.tenant_id = ?", tenantID).
|
||||
Where("agent_shares.source_tenant_id != ?", excludeTenantID).
|
||||
Where("agent_shares.deleted_at IS NULL").
|
||||
Order("agent_shares.id").
|
||||
Limit(1).
|
||||
Find(&share)
|
||||
if tx.Error != nil {
|
||||
return nil, tx.Error
|
||||
}
|
||||
if tx.RowsAffected == 0 {
|
||||
return nil, ErrAgentShareNotFound
|
||||
}
|
||||
return &share, nil
|
||||
}
|
||||
|
||||
// GetShareByAgentIDAndSourceForTenant validates an exact source selector
|
||||
// against organization membership. This avoids loading every shared agent and
|
||||
// makes same-ID builtins from multiple workspaces deterministic.
|
||||
func (r *agentShareRepository) GetShareByAgentIDAndSourceForTenant(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
agentID string,
|
||||
sourceTenantID uint64,
|
||||
) (*types.AgentShare, error) {
|
||||
var share types.AgentShare
|
||||
tx := r.db.WithContext(ctx).
|
||||
Joins("JOIN organization_tenant_members otm ON otm.organization_id = agent_shares.organization_id").
|
||||
Joins("JOIN organizations ON organizations.id = agent_shares.organization_id AND organizations.deleted_at IS NULL").
|
||||
Joins("JOIN custom_agents ON custom_agents.id = agent_shares.agent_id AND custom_agents.tenant_id = agent_shares.source_tenant_id AND custom_agents.deleted_at IS NULL").
|
||||
Joins(agentShareSourceMemberJoin).
|
||||
Where("agent_shares.agent_id = ?", agentID).
|
||||
Where("agent_shares.source_tenant_id = ?", sourceTenantID).
|
||||
Where("otm.tenant_id = ?", tenantID).
|
||||
Where("agent_shares.deleted_at IS NULL").
|
||||
Order("agent_shares.id").
|
||||
Limit(1).
|
||||
Find(&share)
|
||||
if tx.Error != nil {
|
||||
return nil, tx.Error
|
||||
}
|
||||
if tx.RowsAffected == 0 {
|
||||
return nil, ErrAgentShareNotFound
|
||||
}
|
||||
return &share, nil
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestGetShareByAgentIDAndSourceForTenantDisambiguatesSource(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open("file:agent-share-source?mode=memory&cache=shared"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
statements := []string{
|
||||
`CREATE TABLE agent_shares (
|
||||
id TEXT PRIMARY KEY, agent_id TEXT, organization_id TEXT,
|
||||
shared_by_user_id TEXT, source_tenant_id INTEGER, permission TEXT,
|
||||
created_at DATETIME, updated_at DATETIME, deleted_at DATETIME
|
||||
)`,
|
||||
`CREATE TABLE organization_tenant_members (organization_id TEXT, tenant_id INTEGER)`,
|
||||
`CREATE TABLE organizations (id TEXT PRIMARY KEY, deleted_at DATETIME)`,
|
||||
`CREATE TABLE custom_agents (id TEXT, tenant_id INTEGER, deleted_at DATETIME)`,
|
||||
`INSERT INTO organizations(id) VALUES ('org')`,
|
||||
`INSERT INTO organization_tenant_members(organization_id, tenant_id)
|
||||
VALUES ('org', 7), ('org', 42), ('org', 84)`,
|
||||
`INSERT INTO custom_agents(id, tenant_id) VALUES ('builtin-smart-reasoning', 42), ('builtin-smart-reasoning', 84)`,
|
||||
`INSERT INTO agent_shares(id, agent_id, organization_id, source_tenant_id) VALUES
|
||||
('share-42', 'builtin-smart-reasoning', 'org', 42),
|
||||
('share-84', 'builtin-smart-reasoning', 'org', 84)`,
|
||||
}
|
||||
for _, statement := range statements {
|
||||
require.NoError(t, db.Exec(statement).Error)
|
||||
}
|
||||
|
||||
repo := &agentShareRepository{db: db}
|
||||
share, err := repo.GetShareByAgentIDAndSourceForTenant(
|
||||
context.Background(), 7, "builtin-smart-reasoning", 84,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "share-84", share.ID)
|
||||
require.Equal(t, uint64(84), share.SourceTenantID)
|
||||
|
||||
_, err = repo.GetShareByAgentIDAndSourceForTenant(
|
||||
context.Background(), 8, "builtin-smart-reasoning", 84,
|
||||
)
|
||||
require.ErrorIs(t, err, ErrAgentShareNotFound)
|
||||
|
||||
// A share lapses once its source tenant leaves the organization, even if
|
||||
// the row itself was left behind.
|
||||
require.NoError(t, db.Exec(
|
||||
`DELETE FROM organization_tenant_members WHERE organization_id = 'org' AND tenant_id = 84`).Error)
|
||||
_, err = repo.GetShareByAgentIDAndSourceForTenant(
|
||||
context.Background(), 7, "builtin-smart-reasoning", 84,
|
||||
)
|
||||
require.ErrorIs(t, err, ErrAgentShareNotFound)
|
||||
_, err = repo.GetShareByAgentIDForTenant(context.Background(), 7, "builtin-smart-reasoning", 7)
|
||||
require.NoError(t, err, "the share of the remaining member still resolves")
|
||||
shares, err := repo.ListSharedAgentsForTenant(context.Background(), 7)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, shares, 1)
|
||||
require.Equal(t, uint64(42), shares[0].SourceTenantID)
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
|
||||
"academy/internal/application/attachment"
|
||||
"academy/internal/types"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const (
|
||||
descriptionMetadataKey = types.TemporaryDocumentImageDescriptionsKey
|
||||
maxDocumentDescriptions = 64
|
||||
maxDescriptionCacheBytes = 1 << 20
|
||||
)
|
||||
|
||||
// Descriptions live with the document, inherit its retention/deletion policy,
|
||||
// and do not depend on a sandbox or introduce a second document lifecycle.
|
||||
type attachmentDescriptionRepository struct {
|
||||
db *gorm.DB
|
||||
tenantID uint64
|
||||
}
|
||||
|
||||
// NewAttachmentDescriptionRepository binds the observation cache to its owning tenant.
|
||||
func NewAttachmentDescriptionRepository(db *gorm.DB, tenantID uint64) attachment.DescriptionCache {
|
||||
return &attachmentDescriptionRepository{db: db, tenantID: tenantID}
|
||||
}
|
||||
|
||||
func (r *attachmentDescriptionRepository) loadMetadata(
|
||||
ctx context.Context, id string,
|
||||
) (*types.TemporaryDocument, error) {
|
||||
var doc types.TemporaryDocument
|
||||
err := r.db.WithContext(ctx).Select("metadata").Where("tenant_id = ? AND id = ?", r.tenantID, id).First(&doc).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return &doc, err
|
||||
}
|
||||
|
||||
func (r *attachmentDescriptionRepository) Get(ctx context.Context, id, key string) (*attachment.Description, error) {
|
||||
doc, err := r.loadMetadata(ctx, id)
|
||||
if err != nil || doc == nil {
|
||||
return nil, err
|
||||
}
|
||||
_, entries, err := decodeDescriptions(doc.Metadata)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
value, ok := entries[key]
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
return &value, nil
|
||||
}
|
||||
|
||||
func decodeDescriptions(raw types.JSON) (map[string]json.RawMessage, map[string]attachment.Description, error) {
|
||||
metadata := map[string]json.RawMessage{}
|
||||
if len(raw) > 0 {
|
||||
if err := json.Unmarshal(raw, &metadata); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
if metadata == nil {
|
||||
metadata = map[string]json.RawMessage{}
|
||||
}
|
||||
entries := map[string]attachment.Description{}
|
||||
if value := metadata[descriptionMetadataKey]; len(value) > 0 {
|
||||
if err := json.Unmarshal(value, &entries); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
if entries == nil {
|
||||
entries = map[string]attachment.Description{}
|
||||
}
|
||||
return metadata, entries, nil
|
||||
}
|
||||
|
||||
func (r *attachmentDescriptionRepository) Put(ctx context.Context, id, key string, value attachment.Description) error {
|
||||
encoded, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(encoded) > maxDescriptionCacheBytes/4 {
|
||||
return fmt.Errorf("image observation exceeds cache size limit")
|
||||
}
|
||||
// Compare-and-swap preserves parser metadata and concurrent image writes on
|
||||
// SQLite, PostgreSQL and MySQL without JSON dialect-specific mutation SQL.
|
||||
for attempt := 0; attempt < 8; attempt++ {
|
||||
doc, err := r.loadMetadata(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if doc == nil {
|
||||
return fmt.Errorf("attachment no longer exists")
|
||||
}
|
||||
metadata, entries, err := decodeDescriptions(doc.Metadata)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
entries[key] = value
|
||||
keys := make([]string, 0, len(entries))
|
||||
for k := range entries {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Slice(keys, func(i, j int) bool { return entries[keys[i]].CreatedAt.Before(entries[keys[j]].CreatedAt) })
|
||||
for {
|
||||
encoded, err = json.Marshal(entries)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(entries) <= maxDocumentDescriptions && len(encoded) <= maxDescriptionCacheBytes {
|
||||
break
|
||||
}
|
||||
delete(entries, keys[0])
|
||||
keys = keys[1:]
|
||||
}
|
||||
metadata[descriptionMetadataKey] = encoded
|
||||
updated, err := json.Marshal(metadata)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cast := "CAST(metadata AS TEXT)"
|
||||
if r.db.Name() == "mysql" {
|
||||
cast = "CAST(metadata AS CHAR)"
|
||||
}
|
||||
query := r.db.WithContext(ctx).Model(&types.TemporaryDocument{}).
|
||||
Where("tenant_id = ? AND id = ?", r.tenantID, id)
|
||||
if len(doc.Metadata) == 0 {
|
||||
query = query.Where("metadata IS NULL")
|
||||
} else {
|
||||
query = query.Where(cast+" = ?", string(doc.Metadata))
|
||||
}
|
||||
result := query.UpdateColumn("metadata", types.JSON(updated))
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected > 0 {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("attachment description changed concurrently; retry the read")
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/application/attachment"
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestAttachmentDescriptionPersistenceIsolationAndRetention(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
sqlDB, err := db.DB()
|
||||
require.NoError(t, err)
|
||||
sqlDB.SetMaxOpenConns(1)
|
||||
t.Cleanup(func() { require.NoError(t, sqlDB.Close()) })
|
||||
require.NoError(t, db.AutoMigrate(&types.TemporaryDocument{}))
|
||||
doc := &types.TemporaryDocument{
|
||||
ID: "document", TenantID: 7, SessionID: "parent", Metadata: types.JSON(`{"parser":"pdf"}`),
|
||||
}
|
||||
require.NoError(t, db.Create(doc).Error)
|
||||
ctx := context.Background()
|
||||
cache := NewAttachmentDescriptionRepository(db, 7)
|
||||
for i := range maxDocumentDescriptions + 1 {
|
||||
require.NoError(t, cache.Put(ctx, doc.ID, fmt.Sprint(i), attachment.Description{
|
||||
Text: fmt.Sprint(i), CreatedAt: time.Unix(int64(i), 0),
|
||||
}))
|
||||
}
|
||||
// Reconstructing the repository simulates another turn or process.
|
||||
cache = NewAttachmentDescriptionRepository(db, 7)
|
||||
oldest, err := cache.Get(ctx, doc.ID, "0")
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, oldest)
|
||||
newest, err := cache.Get(ctx, doc.ID, fmt.Sprint(maxDocumentDescriptions))
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, newest)
|
||||
stored, err := NewTemporaryDocumentRepository(db).GetByID(ctx, 7, doc.ID)
|
||||
require.NoError(t, err)
|
||||
var metadata map[string]json.RawMessage
|
||||
require.NoError(t, json.Unmarshal(stored.Metadata, &metadata))
|
||||
require.JSONEq(t, `"pdf"`, string(metadata["parser"]))
|
||||
foreign := NewAttachmentDescriptionRepository(db, 8)
|
||||
value, err := foreign.Get(ctx, doc.ID, "1")
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, value)
|
||||
require.Error(t, foreign.Put(ctx, doc.ID, "foreign", attachment.Description{Text: "no"}))
|
||||
require.NoError(t, NewTemporaryDocumentRepository(db).DeleteScoped(ctx, 7, "parent", doc.ID))
|
||||
value, err = cache.Get(ctx, doc.ID, "1")
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, value)
|
||||
}
|
||||
|
||||
func TestConcurrentAttachmentDescriptionsPreserveEachOther(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
sqlDB, err := db.DB()
|
||||
require.NoError(t, err)
|
||||
sqlDB.SetMaxOpenConns(1)
|
||||
t.Cleanup(func() { require.NoError(t, sqlDB.Close()) })
|
||||
require.NoError(t, db.AutoMigrate(&types.TemporaryDocument{}))
|
||||
require.NoError(t, db.Create(&types.TemporaryDocument{ID: "concurrent", TenantID: 7}).Error)
|
||||
errors := make(chan error, 8)
|
||||
for i := range 8 {
|
||||
go func() {
|
||||
errors <- NewAttachmentDescriptionRepository(db, 7).Put(context.Background(), "concurrent", fmt.Sprint(i),
|
||||
attachment.Description{Text: fmt.Sprint(i), CreatedAt: time.Now()})
|
||||
}()
|
||||
}
|
||||
for range 8 {
|
||||
require.NoError(t, <-errors)
|
||||
}
|
||||
for i := range 8 {
|
||||
value, err := NewAttachmentDescriptionRepository(db, 7).Get(context.Background(), "concurrent", fmt.Sprint(i))
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, value)
|
||||
require.Equal(t, fmt.Sprint(i), value.Text)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// auditLogRepository persists audit events to the audit_logs table.
|
||||
// Rows are append-only — there is no Update, no soft-delete, no
|
||||
// Modify hook. The cursor pagination uses the monotonic id column,
|
||||
// not created_at, so duplicate timestamps don't break iteration.
|
||||
type auditLogRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewAuditLogRepository constructs the production audit log repository
|
||||
// backed by the shared GORM connection.
|
||||
func NewAuditLogRepository(db *gorm.DB) interfaces.AuditLogRepository {
|
||||
return &auditLogRepository{db: db}
|
||||
}
|
||||
|
||||
// Create inserts a single audit row. Validation is light — Action is
|
||||
// the only required field at the schema level; CreatedAt is filled by
|
||||
// the database default if zero. Service-layer Log() fills both before
|
||||
// calling here so this is mostly a pass-through.
|
||||
func (r *auditLogRepository) Create(ctx context.Context, entry *types.AuditLog) error {
|
||||
return r.db.WithContext(ctx).Create(entry).Error
|
||||
}
|
||||
|
||||
// auditLogListLimitMax is the hard ceiling regardless of caller input.
|
||||
// Keeps a misconfigured client from triggering an unbounded scan; the
|
||||
// frontend's default page size is 50 so this is comfortable headroom.
|
||||
const auditLogListLimitMax = 100
|
||||
|
||||
// List returns audit log rows for a tenant, newest-first, applying the
|
||||
// optional cursor and filters from AuditLogQuery. Both Action and
|
||||
// Outcome are exact-match — the filter set is small enough that we
|
||||
// don't need substring matching yet.
|
||||
func (r *auditLogRepository) List(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
q *interfaces.AuditLogQuery,
|
||||
) ([]*types.AuditLog, error) {
|
||||
limit := 50
|
||||
if q != nil && q.Limit > 0 {
|
||||
limit = q.Limit
|
||||
}
|
||||
if limit > auditLogListLimitMax {
|
||||
limit = auditLogListLimitMax
|
||||
}
|
||||
|
||||
tx := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ?", tenantID)
|
||||
if q != nil {
|
||||
if q.AfterID > 0 {
|
||||
tx = tx.Where("id < ?", q.AfterID)
|
||||
}
|
||||
if q.Action != "" {
|
||||
tx = tx.Where("action = ?", q.Action)
|
||||
}
|
||||
if q.Outcome != "" {
|
||||
tx = tx.Where("outcome = ?", q.Outcome)
|
||||
}
|
||||
if q.ActorUserID != "" {
|
||||
tx = tx.Where("actor_user_id = ?", q.ActorUserID)
|
||||
}
|
||||
if q.ScopeType != "" {
|
||||
tx = tx.Where("scope_type = ?", q.ScopeType)
|
||||
}
|
||||
if q.ScopeID != "" {
|
||||
tx = tx.Where("scope_id = ?", q.ScopeID)
|
||||
}
|
||||
if q.UnscopedOnly {
|
||||
tx = tx.Where("scope_type = ''")
|
||||
}
|
||||
}
|
||||
|
||||
var entries []*types.AuditLog
|
||||
if err := tx.Order("id DESC").Limit(limit).Find(&entries).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return entries, nil
|
||||
}
|
||||
|
||||
// CountSinceForDedup powers AuditLogService.LogDenied's sliding-window
|
||||
// dedup. The (tenant_id, action) index makes the count cheap; the
|
||||
// remaining filters are applied as additional WHERE clauses on the
|
||||
// indexed result set.
|
||||
//
|
||||
// Returning early on the first match would be slightly cheaper, but
|
||||
// gorm's Count works on the same plan and the constant overhead is
|
||||
// negligible compared to the dedup benefit.
|
||||
func (r *auditLogRepository) CountSinceForDedup(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
actorUserID string,
|
||||
action types.AuditAction,
|
||||
requestPath string,
|
||||
since time.Time,
|
||||
) (int64, error) {
|
||||
var count int64
|
||||
err := r.db.WithContext(ctx).
|
||||
Model(&types.AuditLog{}).
|
||||
Where("tenant_id = ?", tenantID).
|
||||
Where("actor_user_id = ?", actorUserID).
|
||||
Where("action = ?", action).
|
||||
Where("request_path = ?", requestPath).
|
||||
Where("created_at >= ?", since).
|
||||
Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
// DeleteOlderThan purges rows strictly older than cutoff in a single
|
||||
// DELETE. The retention sweep (driven by the audit log service) calls
|
||||
// it once a day with cutoff = now - retention_days.
|
||||
//
|
||||
// Tenant scope is intentionally not part of this signature: retention
|
||||
// is a global ops policy, not a per-tenant choice. If we ever need
|
||||
// per-tenant retention, we'd add a separate DeleteOlderThanForTenant
|
||||
// rather than overload this primitive.
|
||||
//
|
||||
// Returns the number of rows affected so the caller can log the sweep
|
||||
// outcome at INFO. Errors propagate verbatim — the caller decides
|
||||
// whether they're terminal or transient.
|
||||
func (r *auditLogRepository) DeleteOlderThan(ctx context.Context, cutoff time.Time) (int64, error) {
|
||||
res := r.db.WithContext(ctx).
|
||||
Where("created_at < ?", cutoff).
|
||||
Delete(&types.AuditLog{})
|
||||
if res.Error != nil {
|
||||
return 0, res.Error
|
||||
}
|
||||
return res.RowsAffected, nil
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestAuditLogRepositoryListFiltersKnowledgeBaseScope(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open("file:audit-log-scope?mode=memory&cache=shared"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatalf("open sqlite: %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(&types.AuditLog{}); err != nil {
|
||||
t.Fatalf("migrate audit log: %v", err)
|
||||
}
|
||||
rows := []*types.AuditLog{
|
||||
{TenantID: 7, Action: types.AuditActionMemberAdded},
|
||||
{TenantID: 7, Action: types.AuditActionKBUpdated, ScopeType: "knowledge_base", ScopeID: "kb-a"},
|
||||
{TenantID: 7, Action: types.AuditActionKnowledgeCreated, ScopeType: "knowledge_base", ScopeID: "kb-b"},
|
||||
{TenantID: 8, Action: types.AuditActionKBUpdated, ScopeType: "knowledge_base", ScopeID: "kb-a"},
|
||||
}
|
||||
for _, row := range rows {
|
||||
if err := db.Create(row).Error; err != nil {
|
||||
t.Fatalf("insert audit log: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
repo := NewAuditLogRepository(db)
|
||||
got, err := repo.List(context.Background(), 7, &interfaces.AuditLogQuery{
|
||||
ScopeType: "knowledge_base",
|
||||
ScopeID: "kb-a",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("list audit logs: %v", err)
|
||||
}
|
||||
if len(got) != 1 || got[0].TenantID != 7 || got[0].ScopeID != "kb-a" {
|
||||
t.Fatalf("scope filter returned unexpected rows: %+v", got)
|
||||
}
|
||||
unscoped, err := repo.List(context.Background(), 7, &interfaces.AuditLogQuery{UnscopedOnly: true})
|
||||
if err != nil {
|
||||
t.Fatalf("list unscoped audit logs: %v", err)
|
||||
}
|
||||
if len(unscoped) != 1 || unscoped[0].Action != types.AuditActionMemberAdded {
|
||||
t.Fatalf("unscoped filter returned unexpected rows: %+v", unscoped)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,58 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestEmptyImageMigrationRemovesOnlyProvenEmptyDerivedChunks(t *testing.T) {
|
||||
imageAssetBackends(t, func(t *testing.T, db *gorm.DB) {
|
||||
fx := newImageFixture(t, db)
|
||||
empty := fmt.Sprintf(`{"url":"local://empty.png","sha256":"%x","caption":"请提供图片"}`, sha256.Sum256(nil))
|
||||
valid := `{"url":"local://valid.png","sha256":"nonempty","caption":"请提供图片"}`
|
||||
var removed, kept []*types.Chunk
|
||||
for _, kind := range []string{"image_caption", "image_ocr", "image_vector"} {
|
||||
removed = append(removed, fx.addRaw(kind, 0, "["+empty+"]"))
|
||||
kept = append(kept, fx.addRaw(kind, 0, "["+valid+"]"))
|
||||
}
|
||||
kept = append(kept, fx.addRaw("text", 0, "["+empty+"]"))
|
||||
for _, raw := range []string{
|
||||
"[" + empty + "," + valid + "]", // never delete a mixed chunk
|
||||
`[{"url":"local://unknown.png","caption":"请提供图片"}]`,
|
||||
`[{"url":"local://unknown.png","sha256":""}]`,
|
||||
`[`, `[]`, `{}`, `null`, `"scalar"`,
|
||||
} {
|
||||
kept = append(kept, fx.addRaw("image_caption", 0, raw))
|
||||
}
|
||||
|
||||
path := "../../../migrations/sqlite/000042_remove_empty_image_chunks.up.sql"
|
||||
if db.Name() == "postgres" {
|
||||
path = "../../../migrations/versioned/000125_remove_empty_image_chunks.up.sql"
|
||||
}
|
||||
sql, err := os.ReadFile(path)
|
||||
require.NoError(t, err)
|
||||
for range 2 { // safe to run again; no extra records disappear
|
||||
require.NoError(t, db.Exec(string(sql)).Error)
|
||||
for _, chunk := range removed {
|
||||
var stored types.Chunk
|
||||
require.NoError(t, db.Unscoped().First(&stored, "id = ?", chunk.ID).Error)
|
||||
require.True(t, stored.DeletedAt.Valid)
|
||||
require.Equal(t, chunk.Content, stored.Content, "retain the original row for recovery")
|
||||
var count int64
|
||||
require.NoError(t, db.Table("chunk_images").Where("chunk_id = ?", chunk.ID).Count(&count).Error)
|
||||
require.Zero(t, count, "gallery projection must disappear with the source chunk")
|
||||
}
|
||||
for _, chunk := range kept {
|
||||
var count int64
|
||||
require.NoError(t, db.Model(&types.Chunk{}).Where("id = ?", chunk.ID).Count(&count).Error)
|
||||
require.EqualValues(t, 1, count, "must preserve %s: %s", chunk.ChunkType, chunk.ImageInfo)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestDiffFAQChunkIDsByContentHash(t *testing.T) {
|
||||
toAdd, toDelete, matched := diffFAQChunkIDsByContentHash(
|
||||
[]chunkIDHash{
|
||||
{ID: "src-1", ContentHash: "hash-a"},
|
||||
{ID: "src-2", ContentHash: "hash-b"},
|
||||
{ID: "src-3", ContentHash: "hash-only-src"},
|
||||
},
|
||||
[]chunkIDHash{
|
||||
{ID: "dst-1", ContentHash: "hash-a"},
|
||||
{ID: "dst-2", ContentHash: "hash-only-dst"},
|
||||
},
|
||||
)
|
||||
|
||||
assert.ElementsMatch(t, []string{"src-2", "src-3"}, toAdd)
|
||||
assert.ElementsMatch(t, []string{"dst-2"}, toDelete)
|
||||
require.Len(t, matched, 1)
|
||||
assert.Equal(t, "src-1", matched[0].SrcChunkID)
|
||||
assert.Equal(t, "dst-1", matched[0].DstChunkID)
|
||||
}
|
||||
|
||||
func TestDiffFAQChunkIDsByContentHash_dstDuplicateHash(t *testing.T) {
|
||||
// Two destination chunks share hash-a (same FAQ content, e.g. stale copy after
|
||||
// answer_strategy-only change). Source has one chunk for hash-a → keep dst-1,
|
||||
// delete dst-dup, match for status sync.
|
||||
toAdd, toDelete, matched := diffFAQChunkIDsByContentHash(
|
||||
[]chunkIDHash{{ID: "src-1", ContentHash: "hash-a"}},
|
||||
[]chunkIDHash{
|
||||
{ID: "dst-1", ContentHash: "hash-a"},
|
||||
{ID: "dst-dup", ContentHash: "hash-a"},
|
||||
},
|
||||
)
|
||||
|
||||
assert.Empty(t, toAdd)
|
||||
assert.ElementsMatch(t, []string{"dst-dup"}, toDelete)
|
||||
require.Len(t, matched, 1)
|
||||
assert.Equal(t, "src-1", matched[0].SrcChunkID)
|
||||
assert.Equal(t, "dst-1", matched[0].DstChunkID)
|
||||
}
|
||||
|
||||
func TestDiffFAQChunkIDsByContentHash_dstDuplicateHash_notInSrc(t *testing.T) {
|
||||
// Duplicates whose hash is absent from source are all removed (orphan content).
|
||||
toAdd, toDelete, matched := diffFAQChunkIDsByContentHash(
|
||||
nil,
|
||||
[]chunkIDHash{
|
||||
{ID: "dst-orphan-1", ContentHash: "hash-orphan"},
|
||||
{ID: "dst-orphan-2", ContentHash: "hash-orphan"},
|
||||
},
|
||||
)
|
||||
|
||||
assert.Empty(t, toAdd)
|
||||
assert.ElementsMatch(t, []string{"dst-orphan-1", "dst-orphan-2"}, toDelete)
|
||||
assert.Empty(t, matched)
|
||||
}
|
||||
|
||||
func TestDiffFAQChunkIDsByContentHash_emptySide(t *testing.T) {
|
||||
toAdd, toDelete, matched := diffFAQChunkIDsByContentHash(
|
||||
[]chunkIDHash{{ID: "src-1", ContentHash: "hash-a"}},
|
||||
nil,
|
||||
)
|
||||
assert.Equal(t, []string{"src-1"}, toAdd)
|
||||
assert.Empty(t, toDelete)
|
||||
assert.Empty(t, matched)
|
||||
|
||||
toAdd, toDelete, matched = diffFAQChunkIDsByContentHash(
|
||||
nil,
|
||||
[]chunkIDHash{{ID: "dst-1", ContentHash: "hash-a"}},
|
||||
)
|
||||
assert.Empty(t, toAdd)
|
||||
assert.Equal(t, []string{"dst-1"}, toDelete)
|
||||
assert.Empty(t, matched)
|
||||
}
|
||||
|
||||
func TestFAQChunkDiff_SQLite(t *testing.T) {
|
||||
db := setupChunkTestDB(t)
|
||||
repo := NewChunkRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
srcKBID := uuid.New().String()
|
||||
dstKBID := uuid.New().String()
|
||||
srcKnowledgeID := uuid.New().String()
|
||||
dstKnowledgeID := uuid.New().String()
|
||||
|
||||
require.NoError(t, db.Create(&types.Chunk{
|
||||
ID: uuid.New().String(), TenantID: 1, KnowledgeBaseID: srcKBID, KnowledgeID: srcKnowledgeID,
|
||||
ChunkType: types.ChunkTypeFAQ, ContentHash: "shared", Status: int(types.ChunkStatusIndexed),
|
||||
}).Error)
|
||||
require.NoError(t, db.Create(&types.Chunk{
|
||||
ID: uuid.New().String(), TenantID: 1, KnowledgeBaseID: srcKBID, KnowledgeID: srcKnowledgeID,
|
||||
ChunkType: types.ChunkTypeFAQ, ContentHash: "src-only", Status: int(types.ChunkStatusIndexed),
|
||||
}).Error)
|
||||
require.NoError(t, db.Create(&types.Chunk{
|
||||
ID: uuid.New().String(), TenantID: 1, KnowledgeBaseID: dstKBID, KnowledgeID: dstKnowledgeID,
|
||||
ChunkType: types.ChunkTypeFAQ, ContentHash: "shared", Status: int(types.ChunkStatusIndexed),
|
||||
}).Error)
|
||||
require.NoError(t, db.Create(&types.Chunk{
|
||||
ID: uuid.New().String(), TenantID: 1, KnowledgeBaseID: dstKBID, KnowledgeID: dstKnowledgeID,
|
||||
ChunkType: types.ChunkTypeFAQ, ContentHash: "dst-only", Status: int(types.ChunkStatusIndexed),
|
||||
}).Error)
|
||||
|
||||
diff, err := repo.FAQChunkDiff(ctx, 1, srcKBID, 1, dstKBID)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, diff.ChunksToAdd, 1)
|
||||
assert.Len(t, diff.ChunksToDelete, 1)
|
||||
assert.Len(t, diff.MatchedPairs, 1)
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestTagFieldUpdatesReturnAllAffectedChunks(t *testing.T) {
|
||||
for _, flagsOnly := range []bool{false, true} {
|
||||
name := "tag only"
|
||||
if flagsOnly {
|
||||
name = "flags only"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
db := setupChunkTestDB(t)
|
||||
repo := NewChunkRepository(db)
|
||||
for _, chunk := range []*types.Chunk{
|
||||
{ID: "selected", TenantID: 7, KnowledgeBaseID: "kb", ChunkType: types.ChunkTypeFAQ, TagID: "tag"},
|
||||
{ID: "excluded", TenantID: 7, KnowledgeBaseID: "kb", ChunkType: types.ChunkTypeFAQ, TagID: "tag"},
|
||||
{ID: "other-kb", TenantID: 7, KnowledgeBaseID: "other", ChunkType: types.ChunkTypeFAQ, TagID: "tag"},
|
||||
{ID: "other-tenant", TenantID: 8, KnowledgeBaseID: "kb", ChunkType: types.ChunkTypeFAQ, TagID: "tag"},
|
||||
{ID: "deleted", TenantID: 7, KnowledgeBaseID: "kb", ChunkType: types.ChunkTypeFAQ, TagID: "tag"},
|
||||
} {
|
||||
require.NoError(t, db.Create(chunk).Error)
|
||||
}
|
||||
require.NoError(t, db.Delete(&types.Chunk{ID: "deleted"}).Error)
|
||||
next := "next"
|
||||
var tag *string
|
||||
var flags types.ChunkFlags
|
||||
if flagsOnly {
|
||||
flags = types.ChunkFlagRecommended
|
||||
} else {
|
||||
tag = &next
|
||||
}
|
||||
ids, err := repo.UpdateChunkFieldsByTagID(
|
||||
context.Background(),
|
||||
7,
|
||||
"kb",
|
||||
"tag",
|
||||
nil,
|
||||
flags,
|
||||
0,
|
||||
tag,
|
||||
[]string{"excluded"},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"selected"}, ids)
|
||||
selected, err := repo.GetChunkByID(context.Background(), 7, "selected")
|
||||
require.NoError(t, err)
|
||||
if flagsOnly {
|
||||
require.True(t, selected.Flags.HasFlag(types.ChunkFlagRecommended))
|
||||
} else {
|
||||
require.Equal(t, "next", selected.TagID)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// ListImageAssets returns one page of a knowledge base's images from
|
||||
// chunk_images, the projection of chunks.image_info that database triggers
|
||||
// maintain (migrations versioned/000113, sqlite/000032). An image copied onto
|
||||
// several chunks is listed once, as the copy no other copy beats (see
|
||||
// winnerClause), which an index probe per candidate row decides. A plain
|
||||
// listing therefore reads the page off the listing index and stops; filters
|
||||
// narrow the candidates before the probe.
|
||||
func (r *chunkRepository) ListImageAssets(
|
||||
ctx context.Context, tenantID uint64, kbID string, q *types.ImageAssetQuery,
|
||||
) ([]types.ImageAssetRow, int64, error) {
|
||||
if q == nil {
|
||||
q = &types.ImageAssetQuery{}
|
||||
}
|
||||
limit := q.Limit
|
||||
if limit <= 0 {
|
||||
limit = 20
|
||||
}
|
||||
offset := max(q.Offset, 0)
|
||||
|
||||
d := imageAssetDialect{postgres: r.db.Name() == "postgres"}
|
||||
where, args, filtered := d.where(tenantID, kbID, q)
|
||||
// Unfiltered, the total is the number of distinct images, which the
|
||||
// copies index answers without probing every row.
|
||||
count, countArgs := "SELECT COUNT(*) FROM chunk_images i WHERE "+where, args
|
||||
if !filtered {
|
||||
countArgs = args[:2]
|
||||
// DISTINCT in a subquery, not COUNT(DISTINCT): postgres always sorts
|
||||
// for the latter, while the former walks the copies index in order.
|
||||
count = "SELECT COUNT(*) FROM (SELECT DISTINCT i.image_key FROM chunk_images i " +
|
||||
"WHERE i.knowledge_base_id = ? AND i.tenant_id = ?) d"
|
||||
}
|
||||
dir := " ASC"
|
||||
if q.SortDesc {
|
||||
dir = " DESC"
|
||||
}
|
||||
// Ties (every image of one chunk shares its timestamps) follow the sort
|
||||
// direction, so a created_at listing is one backward walk of the index.
|
||||
order := d.sortKey(q.SortField) + dir + ", i.chunk_id" + dir + ", i.image_index" + dir
|
||||
query := "SELECT i.chunk_id, i.knowledge_id, i.chunk_type, i.is_enabled, i.status, i.created_at, " +
|
||||
"i.updated_at, i.image_index, i.url, i.original_url, i.caption, i.ocr_text, " + d.attrsText() +
|
||||
" AS attrs_json, (" + count + ") AS total_count " +
|
||||
"FROM chunk_images i WHERE " + where + " ORDER BY " + order + " LIMIT ? OFFSET ?"
|
||||
|
||||
var rows []types.ImageAssetRow
|
||||
pageArgs := make([]any, 0, len(countArgs)+len(args)+2)
|
||||
pageArgs = append(append(append(pageArgs, countArgs...), args...), limit, offset)
|
||||
if err := r.db.WithContext(ctx).Raw(query, pageArgs...).Scan(&rows).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if len(rows) > 0 {
|
||||
return rows, rows[0].TotalCount, nil
|
||||
}
|
||||
if offset == 0 {
|
||||
return rows, 0, nil
|
||||
}
|
||||
// A page past the end carries no row to read the total from.
|
||||
var total int64
|
||||
err := r.db.WithContext(ctx).Raw(count, countArgs...).Scan(&total).Error
|
||||
return rows, total, err
|
||||
}
|
||||
|
||||
// winnerClause keeps one copy per image: the one on the most recently updated
|
||||
// chunk, ties broken by chunk id and then array position. The copies index
|
||||
// serves the probe.
|
||||
const winnerClause = "NOT EXISTS (SELECT 1 FROM chunk_images o " +
|
||||
"WHERE o.knowledge_base_id = i.knowledge_base_id AND o.tenant_id = i.tenant_id " +
|
||||
"AND o.image_key = i.image_key AND (o.updated_at > i.updated_at " +
|
||||
"OR (o.updated_at = i.updated_at AND (o.chunk_id < i.chunk_id " +
|
||||
"OR (o.chunk_id = i.chunk_id AND o.image_index < i.image_index)))))"
|
||||
|
||||
// scopedWinnerClause is winnerClause restricted to copies inside the listed
|
||||
// documents: a copy outside them must not hide the image from a document that
|
||||
// carries it too.
|
||||
const scopedWinnerClause = "NOT EXISTS (SELECT 1 FROM chunk_images o " +
|
||||
"WHERE o.knowledge_base_id = i.knowledge_base_id AND o.tenant_id = i.tenant_id " +
|
||||
"AND o.image_key = i.image_key AND o.knowledge_id IN ? AND (o.updated_at > i.updated_at " +
|
||||
"OR (o.updated_at = i.updated_at AND (o.chunk_id < i.chunk_id " +
|
||||
"OR (o.chunk_id = i.chunk_id AND o.image_index < i.image_index)))))"
|
||||
|
||||
// imageAssetDialect holds the expressions postgres and sqlite spell
|
||||
// differently: reading the attrs JSON and matching the keyword.
|
||||
type imageAssetDialect struct {
|
||||
postgres bool
|
||||
}
|
||||
|
||||
// where is the predicate selecting the query's images: the listed copy of
|
||||
// each image of the knowledge base that passes the filters. Filters judge the
|
||||
// listed copy, as if the other copies did not exist. Every clause is written
|
||||
// to be non-NULL, so the NOT in the verdict clause cannot turn an unobserved
|
||||
// image into a hidden one. filtered reports whether anything beyond the
|
||||
// knowledge base scope constrains the result.
|
||||
func (d imageAssetDialect) where(
|
||||
tenantID uint64, kbID string, q *types.ImageAssetQuery,
|
||||
) (sql string, args []any, filtered bool) {
|
||||
clauses := []string{"i.knowledge_base_id = ?", "i.tenant_id = ?"}
|
||||
args = []any{kbID, tenantID}
|
||||
if q.IsEnabled != nil {
|
||||
clauses = append(clauses, "i.is_enabled = ?")
|
||||
args = append(args, *q.IsEnabled)
|
||||
}
|
||||
if len(q.KnowledgeIDs) > 0 {
|
||||
clauses = append(clauses, "i.knowledge_id IN ?")
|
||||
args = append(args, q.KnowledgeIDs)
|
||||
}
|
||||
if kw := strings.TrimSpace(q.Keyword); kw != "" {
|
||||
pattern := "%" + escapeLikeKeyword(kw) + "%"
|
||||
var matches []string
|
||||
for _, f := range q.SearchFields {
|
||||
expr, ok := d.value(f)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if d.postgres {
|
||||
// ILIKE with the default backslash escape, the form the
|
||||
// trigram indexes on caption / ocr_text can serve.
|
||||
matches = append(matches, expr+" ILIKE ?")
|
||||
} else {
|
||||
// sqlite's LIKE folds ASCII case only, so non-ASCII keywords
|
||||
// match case-sensitively there.
|
||||
matches = append(matches, expr+" LIKE ? ESCAPE '"+likeEscapeChar+"'")
|
||||
}
|
||||
args = append(args, pattern)
|
||||
}
|
||||
if len(matches) == 0 {
|
||||
matches = []string{"1 = 0"}
|
||||
}
|
||||
clauses = append(clauses, "("+strings.Join(matches, " OR ")+")")
|
||||
}
|
||||
for _, set := range q.AttrFilters {
|
||||
expr, ok := d.value(set.Field)
|
||||
if !ok || len(set.Values) == 0 {
|
||||
continue
|
||||
}
|
||||
// An image never observed for the attribute is not constrained by
|
||||
// it: absence is silence, not a mismatch.
|
||||
clauses = append(clauses, "("+expr+" IS NULL OR "+expr+" IN ?)")
|
||||
args = append(args, set.Values)
|
||||
}
|
||||
if off, offArgs := d.anyCarries(q.OffRules); off != "" {
|
||||
// An "off" hides the images carrying its value unless an "on" claims
|
||||
// the same image: a forced display outranks a forced hide.
|
||||
on, onArgs := d.anyCarries(q.OnRules)
|
||||
if on == "" {
|
||||
on = "1 = 0"
|
||||
}
|
||||
clauses = append(clauses, "(("+on+") OR NOT ("+off+"))")
|
||||
args = append(append(args, onArgs...), offArgs...)
|
||||
}
|
||||
filtered = len(clauses) > 2
|
||||
winner := winnerClause
|
||||
if len(q.KnowledgeIDs) > 0 {
|
||||
winner = scopedWinnerClause
|
||||
args = append(args, q.KnowledgeIDs)
|
||||
}
|
||||
return strings.Join(append(clauses, winner), " AND "), args, filtered
|
||||
}
|
||||
|
||||
// anyCarries is true for an image carrying any of the sets' values. An image
|
||||
// without a value for a field never matches.
|
||||
func (d imageAssetDialect) anyCarries(sets []types.ImageAssetValueSet) (string, []any) {
|
||||
var clauses []string
|
||||
var args []any
|
||||
for _, set := range sets {
|
||||
expr, ok := d.value(set.Field)
|
||||
if !ok || len(set.Values) == 0 {
|
||||
continue
|
||||
}
|
||||
clauses = append(clauses, "("+expr+" IS NOT NULL AND "+expr+" IN ?)")
|
||||
args = append(args, set.Values)
|
||||
}
|
||||
return strings.Join(clauses, " OR "), args
|
||||
}
|
||||
|
||||
// sortKey is the value images are ordered by. An image without a value for
|
||||
// the field sorts as the empty string.
|
||||
func (d imageAssetDialect) sortKey(f types.ImageAssetField) string {
|
||||
switch f.Builtin {
|
||||
case "created_at", "updated_at", "is_enabled":
|
||||
return "i." + f.Builtin
|
||||
}
|
||||
if expr, ok := d.value(f); ok {
|
||||
return "LOWER(COALESCE(" + expr + ", ''))"
|
||||
}
|
||||
return "i.created_at"
|
||||
}
|
||||
|
||||
// value is the normalized text of a field for one image, NULL when the image
|
||||
// carries none. Booleans read as "true"/"false" on both backends, the same
|
||||
// form the gallery contract lists values in. Timestamps are sort-only: they
|
||||
// have no text form to search or filter on.
|
||||
func (d imageAssetDialect) value(f types.ImageAssetField) (string, bool) {
|
||||
switch f.Builtin {
|
||||
case "":
|
||||
case "caption", "ocr_text":
|
||||
return "i." + f.Builtin, true
|
||||
case "is_enabled":
|
||||
return "(CASE WHEN i.is_enabled THEN 'true' ELSE 'false' END)", true
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
name := f.Attr
|
||||
// The name is embedded as a literal (validated against the gallery
|
||||
// contract upstream); refuse anything that could leave the JSON path.
|
||||
if name == "" || strings.ContainsAny(name, `'"\`) {
|
||||
return "", false
|
||||
}
|
||||
if d.postgres {
|
||||
return "(i.attrs->>'" + name + "')", true
|
||||
}
|
||||
path := `'$."` + name + `"'`
|
||||
return "(CASE json_type(i.attrs, " + path + ") WHEN 'true' THEN 'true' WHEN 'false' THEN 'false' " +
|
||||
"ELSE CAST(json_extract(i.attrs, " + path + ") AS TEXT) END)", true
|
||||
}
|
||||
|
||||
// attrsText reads the attrs column back as JSON text.
|
||||
func (d imageAssetDialect) attrsText() string {
|
||||
if d.postgres {
|
||||
return "i.attrs::text"
|
||||
}
|
||||
return "i.attrs"
|
||||
}
|
||||
@@ -0,0 +1,441 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// imageAssetBackends runs fn against in-memory SQLite and, when
|
||||
// ACADEMY_REPOSITORY_TEST_POSTGRES_DSN points at a disposable database, against
|
||||
// PostgreSQL too — the gallery query is spelled differently per dialect, so
|
||||
// both spellings need the same assertions. For example:
|
||||
//
|
||||
// docker run -d --rm -e POSTGRES_PASSWORD=pg -e POSTGRES_DB=academy -p 55432:5432 \
|
||||
// paradedb/paradedb:v0.25.11-pg17
|
||||
// ACADEMY_REPOSITORY_TEST_POSTGRES_DSN=postgres://postgres:pg@localhost:55432/academy?sslmode=disable
|
||||
//
|
||||
// Both runs apply the real chunk_images migration, so the triggers and the
|
||||
// backfill under test are the ones that ship.
|
||||
func imageAssetBackends(t *testing.T, fn func(t *testing.T, db *gorm.DB)) {
|
||||
t.Run("sqlite", func(t *testing.T) {
|
||||
db := setupChunkTestDB(t)
|
||||
applyChunkImagesMigration(t, db)
|
||||
fn(t, db)
|
||||
})
|
||||
t.Run("postgres", func(t *testing.T) {
|
||||
dsn := os.Getenv("ACADEMY_REPOSITORY_TEST_POSTGRES_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("set ACADEMY_REPOSITORY_TEST_POSTGRES_DSN to run the PostgreSQL gallery query")
|
||||
}
|
||||
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.AutoMigrate(&types.Chunk{}))
|
||||
applyChunkImagesMigration(t, db)
|
||||
fn(t, db)
|
||||
})
|
||||
}
|
||||
|
||||
// applyChunkImagesMigration runs the dialect's chunk_images up migration. It
|
||||
// is idempotent, which is also what lets a test re-run it to exercise the
|
||||
// backfill.
|
||||
func applyChunkImagesMigration(t *testing.T, db *gorm.DB) {
|
||||
t.Helper()
|
||||
path := "../../../migrations/sqlite/000032_chunk_images.up.sql"
|
||||
if db.Name() == "postgres" {
|
||||
path = "../../../migrations/versioned/000113_chunk_images.up.sql"
|
||||
}
|
||||
sql, err := os.ReadFile(path)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.Exec(string(sql)).Error)
|
||||
}
|
||||
|
||||
// imageFixture writes chunks for one fresh knowledge base; every test gets its
|
||||
// own kbID so the postgres run needs no cleanup between tests.
|
||||
type imageFixture struct {
|
||||
t *testing.T
|
||||
db *gorm.DB
|
||||
kbID string
|
||||
base time.Time
|
||||
}
|
||||
|
||||
func newImageFixture(t *testing.T, db *gorm.DB) *imageFixture {
|
||||
return &imageFixture{t: t, db: db, kbID: uuid.NewString(), base: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)}
|
||||
}
|
||||
|
||||
// fixtureImage is one image_info entry, written in the persisted shape: the
|
||||
// observed attributes nest under attrs.attrs.
|
||||
type fixtureImage struct {
|
||||
URL string
|
||||
Caption string
|
||||
OCRText string
|
||||
Attrs map[string]any
|
||||
}
|
||||
|
||||
func (f fixtureImage) MarshalJSON() ([]byte, error) {
|
||||
out := map[string]any{"url": f.URL, "original_url": f.URL, "caption": f.Caption, "ocr_text": f.OCRText}
|
||||
if f.Attrs != nil {
|
||||
out["attrs"] = map[string]any{"schema": "attrs/2", "attrs": f.Attrs}
|
||||
}
|
||||
return json.Marshal(out)
|
||||
}
|
||||
|
||||
// add inserts one chunk carrying images, updated minute minutes after base.
|
||||
func (fx *imageFixture) add(chunkType string, minute int, images ...fixtureImage) *types.Chunk {
|
||||
fx.t.Helper()
|
||||
raw, err := json.Marshal(images)
|
||||
require.NoError(fx.t, err)
|
||||
return fx.addRaw(chunkType, minute, string(raw))
|
||||
}
|
||||
|
||||
func (fx *imageFixture) addRaw(chunkType string, minute int, imageInfo string) *types.Chunk {
|
||||
fx.t.Helper()
|
||||
at := fx.base.Add(time.Duration(minute) * time.Minute)
|
||||
c := &types.Chunk{
|
||||
ID: uuid.NewString(),
|
||||
TenantID: 1,
|
||||
KnowledgeBaseID: fx.kbID,
|
||||
KnowledgeID: "doc-" + fx.kbID[:8],
|
||||
Content: "x",
|
||||
ChunkType: chunkType,
|
||||
IsEnabled: true,
|
||||
ImageInfo: imageInfo,
|
||||
CreatedAt: at,
|
||||
UpdatedAt: at,
|
||||
}
|
||||
require.NoError(fx.t, fx.db.Create(c).Error)
|
||||
return c
|
||||
}
|
||||
|
||||
func (fx *imageFixture) list(q types.ImageAssetQuery) ([]types.ImageAssetRow, int64) {
|
||||
fx.t.Helper()
|
||||
if q.Limit == 0 {
|
||||
q.Limit = 100
|
||||
}
|
||||
rows, total, err := NewChunkRepository(fx.db).ListImageAssets(context.Background(), 1, fx.kbID, &q)
|
||||
require.NoError(fx.t, err)
|
||||
return rows, total
|
||||
}
|
||||
|
||||
func rowURLs(t *testing.T, rows []types.ImageAssetRow) []string {
|
||||
t.Helper()
|
||||
urls := make([]string, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
urls = append(urls, r.URL)
|
||||
}
|
||||
return urls
|
||||
}
|
||||
|
||||
var (
|
||||
fieldCaption = types.ImageAssetField{Builtin: "caption"}
|
||||
fieldOCR = types.ImageAssetField{Builtin: "ocr_text"}
|
||||
fieldText = types.ImageAssetField{Attr: "contain.text"}
|
||||
fieldVisual = types.ImageAssetField{Attr: "contain.data_visual"}
|
||||
)
|
||||
|
||||
func TestListImageAssets_DedupsAndExpandsArrays(t *testing.T) {
|
||||
imageAssetBackends(t, func(t *testing.T, db *gorm.DB) {
|
||||
fx := newImageFixture(t, db)
|
||||
// The multimodal pipeline writes the same image to its OCR and caption
|
||||
// children; the most recently updated copy is the one listed.
|
||||
fx.add("image_ocr", 1, fixtureImage{URL: "local://a.png", Caption: "old"})
|
||||
caption := fx.add("image_caption", 2, fixtureImage{URL: "local://a.png", Caption: "new"})
|
||||
// A pre-2026-02 text chunk carrying several images, one of them shared.
|
||||
legacy := fx.add("text", 0,
|
||||
fixtureImage{URL: "local://b.png"}, fixtureImage{URL: "local://c.png"}, fixtureImage{URL: "local://a.png"})
|
||||
|
||||
rows, total := fx.list(types.ImageAssetQuery{SortField: types.ImageAssetField{Builtin: "created_at"}})
|
||||
require.EqualValues(t, 3, total)
|
||||
require.ElementsMatch(t, []string{"local://a.png", "local://b.png", "local://c.png"}, rowURLs(t, rows))
|
||||
for _, r := range rows {
|
||||
switch rowURLs(t, []types.ImageAssetRow{r})[0] {
|
||||
case "local://a.png":
|
||||
require.Equal(t, caption.ID, r.ChunkID)
|
||||
require.Equal(t, "new", r.Caption)
|
||||
case "local://c.png":
|
||||
require.Equal(t, legacy.ID, r.ChunkID)
|
||||
require.Equal(t, 1, r.ImageIndex)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestListImageAssets_SkipsForeignDeletedAndMalformedRows(t *testing.T) {
|
||||
imageAssetBackends(t, func(t *testing.T, db *gorm.DB) {
|
||||
fx := newImageFixture(t, db)
|
||||
fx.add("image_caption", 0, fixtureImage{URL: "local://keep.png"})
|
||||
deleted := fx.add("image_caption", 0, fixtureImage{URL: "local://deleted.png"})
|
||||
require.NoError(t, db.Delete(deleted).Error)
|
||||
fx.addRaw("text", 0, "")
|
||||
fx.addRaw("text", 0, `{"url":"local://object.png"}`)
|
||||
other := newImageFixture(t, db)
|
||||
other.add("image_caption", 0, fixtureImage{URL: "local://other-kb.png"})
|
||||
// A malformed row must neither fail the chunk write nor the listing.
|
||||
fx.addRaw("text", 0, `[{"url": broken`)
|
||||
|
||||
rows, total := fx.list(types.ImageAssetQuery{})
|
||||
require.EqualValues(t, 1, total)
|
||||
require.Equal(t, []string{"local://keep.png"}, rowURLs(t, rows))
|
||||
})
|
||||
}
|
||||
|
||||
func TestListImageAssets_PagesStablyThroughTies(t *testing.T) {
|
||||
imageAssetBackends(t, func(t *testing.T, db *gorm.DB) {
|
||||
fx := newImageFixture(t, db)
|
||||
// Every image of one chunk shares its timestamps: a desc sort on
|
||||
// created_at is all ties and must still page without repeats or gaps.
|
||||
var imgs []fixtureImage
|
||||
for _, name := range []string{"p0", "p1", "p2", "p3", "p4"} {
|
||||
imgs = append(imgs, fixtureImage{URL: "local://" + name + ".png"})
|
||||
}
|
||||
fx.add("text", 0, imgs...)
|
||||
|
||||
var seen []string
|
||||
for offset := 0; offset < 6; offset += 2 {
|
||||
rows, total := fx.list(types.ImageAssetQuery{
|
||||
SortField: types.ImageAssetField{Builtin: "created_at"}, SortDesc: true, Offset: offset, Limit: 2,
|
||||
})
|
||||
require.EqualValues(t, 5, total, "offset %d", offset)
|
||||
seen = append(seen, rowURLs(t, rows)...)
|
||||
}
|
||||
// Ties follow the sort direction, so newest-first walks the chunk's
|
||||
// images from the last one, like images of separate chunks.
|
||||
require.Equal(t, []string{
|
||||
"local://p4.png", "local://p3.png", "local://p2.png", "local://p1.png", "local://p0.png",
|
||||
}, seen)
|
||||
|
||||
rows, total := fx.list(types.ImageAssetQuery{Offset: 10, Limit: 2})
|
||||
require.Empty(t, rows)
|
||||
require.EqualValues(t, 5, total, "a page past the end still reports the total")
|
||||
})
|
||||
}
|
||||
|
||||
func TestListImageAssets_KeywordSearch(t *testing.T) {
|
||||
imageAssetBackends(t, func(t *testing.T, db *gorm.DB) {
|
||||
fx := newImageFixture(t, db)
|
||||
fx.add("image_caption", 0, fixtureImage{URL: "local://chart.png", Caption: "Quarterly Revenue chart"})
|
||||
fx.add("image_caption", 1, fixtureImage{URL: "local://scan.png", OCRText: "growth 50% year over year"})
|
||||
fx.add("image_caption", 2, fixtureImage{URL: "local://logo.png", Caption: "company logo"})
|
||||
|
||||
search := func(kw string, fields ...types.ImageAssetField) []string {
|
||||
rows, _ := fx.list(types.ImageAssetQuery{Keyword: kw, SearchFields: fields})
|
||||
return rowURLs(t, rows)
|
||||
}
|
||||
require.Equal(t, []string{"local://chart.png"}, search("revenue", fieldCaption, fieldOCR),
|
||||
"matching is case-insensitive")
|
||||
require.Equal(t, []string{"local://scan.png"}, search("50%", fieldCaption, fieldOCR),
|
||||
"LIKE wildcards in the keyword are literal")
|
||||
require.Empty(t, search("50%", fieldCaption), "only the requested fields are searched")
|
||||
require.Empty(t, search("local://"), "no searchable field means no match")
|
||||
_, total := fx.list(types.ImageAssetQuery{Keyword: "local://"})
|
||||
require.Zero(t, total, "and the total agrees")
|
||||
})
|
||||
}
|
||||
|
||||
func TestListImageAssets_AttributeFiltersAndRules(t *testing.T) {
|
||||
imageAssetBackends(t, func(t *testing.T, db *gorm.DB) {
|
||||
fx := newImageFixture(t, db)
|
||||
fx.add("image_caption", 0, fixtureImage{
|
||||
URL: "local://block.png",
|
||||
Attrs: map[string]any{"contain.text": "block", "contain.data_visual": true},
|
||||
})
|
||||
fx.add("image_caption", 1, fixtureImage{
|
||||
URL: "local://none.png",
|
||||
Attrs: map[string]any{"contain.text": "none", "contain.data_visual": false},
|
||||
})
|
||||
// Never observed: no attribute keys at all.
|
||||
fx.add("image_caption", 2, fixtureImage{URL: "local://blank.png"})
|
||||
|
||||
list := func(q types.ImageAssetQuery) []string {
|
||||
q.SortField = types.ImageAssetField{Builtin: "created_at"}
|
||||
rows, _ := fx.list(q)
|
||||
return rowURLs(t, rows)
|
||||
}
|
||||
|
||||
require.Equal(t, []string{"local://block.png", "local://blank.png"}, list(types.ImageAssetQuery{
|
||||
AttrFilters: []types.ImageAssetValueSet{{Field: fieldText, Values: []string{"block"}}},
|
||||
}), "a filter narrows observed images and leaves unobserved ones alone")
|
||||
|
||||
require.Equal(t, []string{"local://block.png", "local://blank.png"}, list(types.ImageAssetQuery{
|
||||
AttrFilters: []types.ImageAssetValueSet{{Field: fieldVisual, Values: []string{"true"}}},
|
||||
}), "JSON booleans compare as \"true\"/\"false\" on both backends")
|
||||
|
||||
require.Equal(t, []string{"local://none.png", "local://blank.png"}, list(types.ImageAssetQuery{
|
||||
OffRules: []types.ImageAssetValueSet{{Field: fieldText, Values: []string{"block"}}},
|
||||
}), "off hides the images carrying the value and nothing else")
|
||||
|
||||
require.Equal(t, []string{"local://block.png", "local://blank.png"}, list(types.ImageAssetQuery{
|
||||
OffRules: []types.ImageAssetValueSet{{Field: fieldText, Values: []string{"none", "block"}}},
|
||||
OnRules: []types.ImageAssetValueSet{{Field: fieldVisual, Values: []string{"true"}}},
|
||||
}), "on outranks off for the same image, even across attributes")
|
||||
|
||||
disabled := false
|
||||
require.Empty(t, list(types.ImageAssetQuery{IsEnabled: &disabled}))
|
||||
})
|
||||
}
|
||||
|
||||
func TestListImageAssets_KnowledgeIDFilter(t *testing.T) {
|
||||
imageAssetBackends(t, func(t *testing.T, db *gorm.DB) {
|
||||
fx := newImageFixture(t, db)
|
||||
// addRaw writes into the fixture's default document; a second chunk in
|
||||
// another document of the same KB gives the filter something to exclude.
|
||||
defaultDoc := fx.addRaw("text", 0,
|
||||
`[{"url":"local://a.png","original_url":"local://a.png","caption":"a","ocr_text":""}]`)
|
||||
other := &types.Chunk{
|
||||
ID: uuid.NewString(),
|
||||
TenantID: 1,
|
||||
KnowledgeBaseID: fx.kbID,
|
||||
KnowledgeID: "doc-other-" + fx.kbID[:8],
|
||||
Content: "x",
|
||||
ChunkType: "text",
|
||||
IsEnabled: true,
|
||||
ImageInfo: `[{"url":"local://b.png","original_url":"local://b.png","caption":"b","ocr_text":""}]`,
|
||||
CreatedAt: fx.base,
|
||||
UpdatedAt: fx.base,
|
||||
}
|
||||
require.NoError(t, db.Create(other).Error)
|
||||
|
||||
rows, total := fx.list(types.ImageAssetQuery{
|
||||
KnowledgeIDs: []string{defaultDoc.KnowledgeID},
|
||||
SortField: types.ImageAssetField{Builtin: "created_at"},
|
||||
})
|
||||
require.EqualValues(t, 1, total, "the total reflects the filtered scope")
|
||||
require.Equal(t, []string{"local://a.png"}, rowURLs(t, rows))
|
||||
|
||||
rows, total = fx.list(types.ImageAssetQuery{
|
||||
KnowledgeIDs: []string{defaultDoc.KnowledgeID, other.KnowledgeID},
|
||||
})
|
||||
require.EqualValues(t, 2, total)
|
||||
require.ElementsMatch(t, []string{"local://a.png", "local://b.png"}, rowURLs(t, rows))
|
||||
})
|
||||
}
|
||||
|
||||
func TestListImageAssets_KnowledgeIDFilterKeepsSharedImage(t *testing.T) {
|
||||
imageAssetBackends(t, func(t *testing.T, db *gorm.DB) {
|
||||
fx := newImageFixture(t, db)
|
||||
shared := `[{"url":"https://example.com/logo.png","original_url":"","caption":"logo","ocr_text":""}]`
|
||||
older := fx.addRaw("text", 0, shared)
|
||||
// The same image on a newer chunk of another document wins the
|
||||
// knowledge-base-wide de-duplication.
|
||||
newer := &types.Chunk{
|
||||
ID: uuid.NewString(),
|
||||
TenantID: 1,
|
||||
KnowledgeBaseID: fx.kbID,
|
||||
KnowledgeID: "doc-newer-" + fx.kbID[:8],
|
||||
Content: "x",
|
||||
ChunkType: "text",
|
||||
IsEnabled: true,
|
||||
ImageInfo: shared,
|
||||
CreatedAt: fx.base.Add(5 * time.Minute),
|
||||
UpdatedAt: fx.base.Add(5 * time.Minute),
|
||||
}
|
||||
require.NoError(t, db.Create(newer).Error)
|
||||
|
||||
rows, total := fx.list(types.ImageAssetQuery{KnowledgeIDs: []string{older.KnowledgeID}})
|
||||
require.EqualValues(t, 1, total, "the older document still lists its copy")
|
||||
require.Len(t, rows, 1)
|
||||
require.Equal(t, older.ID, rows[0].ChunkID)
|
||||
|
||||
rows, total = fx.list(types.ImageAssetQuery{KnowledgeIDs: []string{older.KnowledgeID, newer.KnowledgeID}})
|
||||
require.EqualValues(t, 1, total, "copies inside the scope still de-duplicate")
|
||||
require.Len(t, rows, 1)
|
||||
require.Equal(t, newer.ID, rows[0].ChunkID)
|
||||
})
|
||||
}
|
||||
|
||||
func TestListImageAssets_SortsByAttribute(t *testing.T) {
|
||||
imageAssetBackends(t, func(t *testing.T, db *gorm.DB) {
|
||||
fx := newImageFixture(t, db)
|
||||
fx.add("image_caption", 0, fixtureImage{URL: "local://s.png", Attrs: map[string]any{"contain.text": "sparse"}})
|
||||
fx.add("image_caption", 1, fixtureImage{URL: "local://b.png", Attrs: map[string]any{"contain.text": "block"}})
|
||||
fx.add("image_caption", 2, fixtureImage{URL: "local://u.png"})
|
||||
|
||||
rows, _ := fx.list(types.ImageAssetQuery{SortField: fieldText})
|
||||
require.Equal(t, []string{"local://u.png", "local://b.png", "local://s.png"}, rowURLs(t, rows),
|
||||
"an image without the attribute sorts as the empty string")
|
||||
})
|
||||
}
|
||||
|
||||
func TestListImageAssets_TriggersFollowChunkWrites(t *testing.T) {
|
||||
imageAssetBackends(t, func(t *testing.T, db *gorm.DB) {
|
||||
fx := newImageFixture(t, db)
|
||||
older := fx.add("image_ocr", 1, fixtureImage{URL: "local://a.png", Caption: "old"})
|
||||
newer := fx.add("image_caption", 2, fixtureImage{URL: "local://a.png", Caption: "new"})
|
||||
keep := fx.add("image_caption", 3, fixtureImage{URL: "local://b.png", Caption: "b"})
|
||||
captions := func() []string {
|
||||
rows, _ := fx.list(types.ImageAssetQuery{SortField: types.ImageAssetField{Builtin: "created_at"}})
|
||||
out := make([]string, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
out = append(out, r.Caption)
|
||||
}
|
||||
return out
|
||||
}
|
||||
require.Equal(t, []string{"new", "b"}, captions())
|
||||
|
||||
// A status-only write (no image change) still moves the image to the
|
||||
// copy that is now the most recently updated.
|
||||
require.NoError(t, db.Model(older).Updates(map[string]any{
|
||||
"status": 2, "updated_at": fx.base.Add(time.Hour),
|
||||
}).Error)
|
||||
require.Equal(t, []string{"old", "b"}, captions())
|
||||
require.NoError(t, db.Model(newer).Updates(map[string]any{
|
||||
"status": 2, "updated_at": fx.base.Add(2 * time.Hour),
|
||||
}).Error)
|
||||
require.Equal(t, []string{"new", "b"}, captions())
|
||||
|
||||
// Soft-deleting the winning copy hands the image to the other copy.
|
||||
require.NoError(t, db.Delete(newer).Error)
|
||||
require.Equal(t, []string{"old", "b"}, captions())
|
||||
|
||||
// An edit to image_info shows up at once.
|
||||
raw, _ := json.Marshal([]fixtureImage{{URL: "local://a.png", Caption: "edited"}})
|
||||
require.NoError(t, db.Model(older).Update("image_info", string(raw)).Error)
|
||||
require.Equal(t, []string{"edited", "b"}, captions())
|
||||
|
||||
// So does the enabled flag.
|
||||
require.NoError(t, db.Model(keep).Update("is_enabled", false).Error)
|
||||
disabled := false
|
||||
rows, _ := fx.list(types.ImageAssetQuery{IsEnabled: &disabled})
|
||||
require.Equal(t, []string{"local://b.png"}, rowURLs(t, rows))
|
||||
|
||||
// Moving a document to another knowledge base moves its images.
|
||||
target := newImageFixture(t, db)
|
||||
require.NoError(t, db.Model(keep).Update("knowledge_base_id", target.kbID).Error)
|
||||
require.Equal(t, []string{"edited"}, captions())
|
||||
rows, _ = target.list(types.ImageAssetQuery{})
|
||||
require.Equal(t, []string{"local://b.png"}, rowURLs(t, rows))
|
||||
|
||||
// A hard delete removes the image entirely.
|
||||
require.NoError(t, db.Unscoped().Delete(older).Error)
|
||||
require.Empty(t, captions())
|
||||
})
|
||||
}
|
||||
|
||||
func TestListImageAssets_MigrationBackfillsExistingChunks(t *testing.T) {
|
||||
imageAssetBackends(t, func(t *testing.T, db *gorm.DB) {
|
||||
fx := newImageFixture(t, db)
|
||||
fx.add("image_ocr", 1, fixtureImage{URL: "local://a.png", Caption: "old"})
|
||||
fx.add("image_caption", 2, fixtureImage{URL: "local://a.png", Caption: "new"})
|
||||
fx.add("text", 0, fixtureImage{URL: "local://b.png"}, fixtureImage{URL: "local://c.png"})
|
||||
// Forget the projection, as a database that predates the migration.
|
||||
require.NoError(t, db.Exec("DELETE FROM chunk_images WHERE knowledge_base_id = ?", fx.kbID).Error)
|
||||
applyChunkImagesMigration(t, db)
|
||||
|
||||
rows, total := fx.list(types.ImageAssetQuery{})
|
||||
require.EqualValues(t, 3, total)
|
||||
require.ElementsMatch(t, []string{"local://a.png", "local://b.png", "local://c.png"}, rowURLs(t, rows))
|
||||
for _, r := range rows {
|
||||
if r.URL == "local://a.png" {
|
||||
require.Equal(t, "new", r.Caption, "the backfill elects the most recently updated copy")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql/driver"
|
||||
"testing"
|
||||
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestCreateChunks_PostgresPreservesEnabledStateAndReturnsSeqIDs(t *testing.T) {
|
||||
sqlDB, mock, err := sqlmock.New()
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = sqlDB.Close() })
|
||||
db, err := gorm.Open(postgres.New(postgres.Config{Conn: sqlDB}), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
|
||||
chunks := []*types.Chunk{
|
||||
makeChunk("kb", "faq", types.ChunkTypeFAQ),
|
||||
makeChunk("kb", "faq", types.ChunkTypeFAQ),
|
||||
}
|
||||
chunks[1].IsEnabled = false
|
||||
// Check the bound values for both rows, not only the caller's structs.
|
||||
stmt := &gorm.Statement{DB: db}
|
||||
require.NoError(t, stmt.Parse(&types.Chunk{}))
|
||||
var args []driver.Value
|
||||
for _, chunk := range chunks {
|
||||
for _, name := range stmt.Schema.DBNames {
|
||||
if name == "seq_id" {
|
||||
continue // PostgreSQL generates these and returns them to the embedded chunks.
|
||||
}
|
||||
if name == "is_enabled" {
|
||||
args = append(args, chunk.IsEnabled)
|
||||
} else {
|
||||
args = append(args, sqlmock.AnyArg())
|
||||
}
|
||||
}
|
||||
}
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(`INSERT INTO "chunks" .*RETURNING "seq_id"`).WithArgs(args...).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"seq_id"}).AddRow(101).AddRow(102))
|
||||
mock.ExpectCommit()
|
||||
|
||||
require.NoError(t, NewChunkRepository(db).CreateChunks(context.Background(), chunks))
|
||||
require.EqualValues(t, 101, chunks[0].SeqID)
|
||||
require.EqualValues(t, 102, chunks[1].SeqID)
|
||||
require.True(t, chunks[0].IsEnabled)
|
||||
require.False(t, chunks[1].IsEnabled)
|
||||
require.False(t, chunks[0].CreatedAt.IsZero())
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestSaveChunkRevisionIsAtomicAndOptimistic(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open("file:"+uuid.NewString()+"?mode=memory&cache=shared"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.AutoMigrate(&types.Chunk{}, &types.ChunkRevision{}))
|
||||
repo := NewChunkRepository(db)
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
chunk := &types.Chunk{
|
||||
ID: uuid.NewString(), TenantID: 1, KnowledgeBaseID: "kb", KnowledgeID: "knowledge",
|
||||
Content: "before", SourceContent: "before", ChunkType: types.ChunkTypeText,
|
||||
SourceLocators: types.SourceLocators{{
|
||||
Type: "pdf",
|
||||
Page: 1,
|
||||
Mapping: "exact",
|
||||
SourceID: "block:1",
|
||||
SourceHash: "revision-one",
|
||||
Partial: true,
|
||||
}},
|
||||
IsEnabled: true, IndexStatus: "ready", CreatedAt: now, UpdatedAt: now,
|
||||
}
|
||||
require.NoError(t, repo.CreateChunks(ctx, []*types.Chunk{chunk}))
|
||||
initial, err := repo.GetChunkByID(ctx, 1, chunk.ID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, chunk.SourceLocators, initial.SourceLocators)
|
||||
|
||||
snapshot := &types.ChunkRevision{
|
||||
ID: uuid.NewString(), TenantID: 1, KnowledgeBaseID: "kb", KnowledgeID: "knowledge",
|
||||
ChunkID: chunk.ID, Revision: 0, Content: "before", IsEnabled: true,
|
||||
EditSource: "user", EditedAt: now, CreatedAt: now,
|
||||
}
|
||||
chunk.Content = "after"
|
||||
chunk.SourceLocators = nil
|
||||
chunk.ContentRevision = 1
|
||||
require.NoError(t, repo.SaveChunkRevision(ctx, chunk, snapshot, 0))
|
||||
|
||||
stored, err := repo.GetChunkByID(ctx, 1, chunk.ID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "after", stored.Content)
|
||||
require.Empty(t, stored.SourceLocators)
|
||||
require.Equal(t, 1, stored.ContentRevision)
|
||||
revisions, err := repo.ListChunkRevisions(ctx, 1, chunk.ID)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, revisions, 1)
|
||||
require.Equal(t, "before", revisions[0].Content)
|
||||
|
||||
stale := *chunk
|
||||
stale.Content = "stale write"
|
||||
stale.ContentRevision = 1
|
||||
staleSnapshot := *snapshot
|
||||
staleSnapshot.ID = uuid.NewString()
|
||||
require.ErrorIs(t, repo.SaveChunkRevision(ctx, &stale, &staleSnapshot, 0), ErrChunkRevisionConflict)
|
||||
|
||||
stored, err = repo.GetChunkByID(ctx, 1, chunk.ID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "after", stored.Content)
|
||||
require.Empty(t, stored.SourceLocators)
|
||||
count := int64(0)
|
||||
require.NoError(t, db.Model(&types.ChunkRevision{}).Count(&count).Error)
|
||||
require.Equal(t, int64(1), count)
|
||||
require.False(t, errors.Is(gorm.ErrRecordNotFound, ErrChunkRevisionConflict))
|
||||
}
|
||||
@@ -0,0 +1,591 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// setupChunkTestDB creates an in-memory SQLite database with chunk and tag tables.
|
||||
func setupChunkTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.AutoMigrate(&types.Chunk{}, &types.ChunkRevision{}, &types.KnowledgeTag{}))
|
||||
return db
|
||||
}
|
||||
|
||||
func makeChunk(kbID, knowledgeID string, chunkType string) *types.Chunk {
|
||||
return &types.Chunk{
|
||||
ID: uuid.New().String(),
|
||||
TenantID: 1,
|
||||
KnowledgeBaseID: kbID,
|
||||
KnowledgeID: knowledgeID,
|
||||
Content: "test content",
|
||||
ChunkType: chunkType,
|
||||
IsEnabled: true,
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateChunks_SQLite_SeqIDAutoAssigned(t *testing.T) {
|
||||
db := setupChunkTestDB(t)
|
||||
repo := NewChunkRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
kbID := uuid.New().String()
|
||||
knowledgeID := uuid.New().String()
|
||||
|
||||
// Create a batch of 5 chunks
|
||||
chunks := []*types.Chunk{
|
||||
makeChunk(kbID, knowledgeID, "faq"),
|
||||
makeChunk(kbID, knowledgeID, "faq"),
|
||||
makeChunk(kbID, knowledgeID, "faq"),
|
||||
makeChunk(kbID, knowledgeID, "faq"),
|
||||
makeChunk(kbID, knowledgeID, "faq"),
|
||||
}
|
||||
|
||||
err := repo.CreateChunks(ctx, chunks)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Verify all chunks got unique sequential seq_ids
|
||||
var saved []types.Chunk
|
||||
require.NoError(t, db.Order("seq_id").Find(&saved).Error)
|
||||
assert.Len(t, saved, 5)
|
||||
|
||||
for i, c := range saved {
|
||||
assert.Equal(t, int64(i+1), c.SeqID, "chunk %d should have seq_id %d", i, i+1)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateChunks_CleansContextHeaderBeforePersistence(t *testing.T) {
|
||||
db := setupChunkTestDB(t)
|
||||
repo := NewChunkRepository(db)
|
||||
chunk := makeChunk(uuid.New().String(), uuid.New().String(), types.ChunkTypeText)
|
||||
chunk.ContextHeader = "# \x00投资评级说明\xff"
|
||||
|
||||
require.NoError(t, repo.CreateChunks(context.Background(), []*types.Chunk{chunk}))
|
||||
|
||||
require.Equal(t, "# 投资评级说明", chunk.ContextHeader)
|
||||
require.NotContains(t, chunk.ContextHeader, "\x00")
|
||||
require.True(t, utf8.ValidString(chunk.ContextHeader))
|
||||
|
||||
var saved types.Chunk
|
||||
require.NoError(t, db.First(&saved, "id = ?", chunk.ID).Error)
|
||||
assert.Equal(t, "# 投资评级说明", saved.ContextHeader)
|
||||
assert.NotContains(t, saved.ContextHeader, "\x00")
|
||||
assert.True(t, utf8.ValidString(saved.ContextHeader))
|
||||
}
|
||||
|
||||
func TestCreateChunks_SQLite_SeqIDContinuesFromExisting(t *testing.T) {
|
||||
db := setupChunkTestDB(t)
|
||||
repo := NewChunkRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
kbID := uuid.New().String()
|
||||
knowledgeID := uuid.New().String()
|
||||
|
||||
// Create first batch
|
||||
batch1 := []*types.Chunk{
|
||||
makeChunk(kbID, knowledgeID, "faq"),
|
||||
makeChunk(kbID, knowledgeID, "faq"),
|
||||
makeChunk(kbID, knowledgeID, "faq"),
|
||||
}
|
||||
require.NoError(t, repo.CreateChunks(ctx, batch1))
|
||||
|
||||
// Create second batch - seq_ids should continue from 3
|
||||
batch2 := []*types.Chunk{
|
||||
makeChunk(kbID, knowledgeID, "faq"),
|
||||
makeChunk(kbID, knowledgeID, "faq"),
|
||||
}
|
||||
require.NoError(t, repo.CreateChunks(ctx, batch2))
|
||||
|
||||
var saved []types.Chunk
|
||||
require.NoError(t, db.Order("seq_id").Find(&saved).Error)
|
||||
assert.Len(t, saved, 5)
|
||||
|
||||
for i, c := range saved {
|
||||
assert.Equal(t, int64(i+1), c.SeqID, "chunk %d should have seq_id %d", i, i+1)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateChunks_SQLite_SeqIDUniqueAcrossKBs(t *testing.T) {
|
||||
db := setupChunkTestDB(t)
|
||||
repo := NewChunkRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
kb1 := uuid.New().String()
|
||||
kb2 := uuid.New().String()
|
||||
k1 := uuid.New().String()
|
||||
k2 := uuid.New().String()
|
||||
|
||||
// Create chunks in two different knowledge bases
|
||||
require.NoError(t, repo.CreateChunks(ctx, []*types.Chunk{
|
||||
makeChunk(kb1, k1, "faq"),
|
||||
makeChunk(kb1, k1, "faq"),
|
||||
}))
|
||||
require.NoError(t, repo.CreateChunks(ctx, []*types.Chunk{
|
||||
makeChunk(kb2, k2, "faq"),
|
||||
makeChunk(kb2, k2, "faq"),
|
||||
}))
|
||||
|
||||
// All seq_ids should be globally unique (1,2,3,4)
|
||||
var saved []types.Chunk
|
||||
require.NoError(t, db.Order("seq_id").Find(&saved).Error)
|
||||
assert.Len(t, saved, 4)
|
||||
|
||||
seqIDs := map[int64]bool{}
|
||||
for _, c := range saved {
|
||||
assert.NotZero(t, c.SeqID)
|
||||
assert.False(t, seqIDs[c.SeqID], "seq_id %d should be unique", c.SeqID)
|
||||
seqIDs[c.SeqID] = true
|
||||
}
|
||||
}
|
||||
|
||||
func TestKnowledgeTag_SQLite_SeqIDAutoAssigned(t *testing.T) {
|
||||
db := setupChunkTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
kbID := uuid.New().String()
|
||||
|
||||
// Create tags one by one (as the application does)
|
||||
tag1 := &types.KnowledgeTag{
|
||||
ID: uuid.New().String(),
|
||||
TenantID: 1,
|
||||
KnowledgeBaseID: kbID,
|
||||
Name: "tag1",
|
||||
}
|
||||
tag2 := &types.KnowledgeTag{
|
||||
ID: uuid.New().String(),
|
||||
TenantID: 1,
|
||||
KnowledgeBaseID: kbID,
|
||||
Name: "tag2",
|
||||
}
|
||||
|
||||
require.NoError(t, db.WithContext(ctx).Create(tag1).Error)
|
||||
require.NoError(t, db.WithContext(ctx).Create(tag2).Error)
|
||||
|
||||
// Both should have non-zero, unique seq_ids
|
||||
assert.NotZero(t, tag1.SeqID)
|
||||
assert.NotZero(t, tag2.SeqID)
|
||||
assert.NotEqual(t, tag1.SeqID, tag2.SeqID)
|
||||
}
|
||||
|
||||
func TestPurgeSupersededChunksByKnowledgeIDRemovesOnlyReplacedHistory(t *testing.T) {
|
||||
db := setupChunkTestDB(t)
|
||||
repo := NewChunkRepository(db).(*chunkRepository)
|
||||
ctx := context.Background()
|
||||
const tenantID uint64 = 1
|
||||
const knowledgeID = "knowledge-1"
|
||||
|
||||
deletedAt := time.Now().UTC().Add(-time.Minute)
|
||||
old := &types.Chunk{
|
||||
ID: "old", TenantID: tenantID, KnowledgeID: knowledgeID, KnowledgeBaseID: "kb-1",
|
||||
ChunkIndex: 0, ChunkType: types.ChunkTypeText, Content: "old", IsEnabled: true,
|
||||
CreatedAt: deletedAt.Add(-time.Minute), DeletedAt: gorm.DeletedAt{Time: deletedAt, Valid: true},
|
||||
}
|
||||
replacement := &types.Chunk{
|
||||
ID: "replacement", TenantID: tenantID, KnowledgeID: knowledgeID, KnowledgeBaseID: "kb-1",
|
||||
ChunkIndex: 0, ChunkType: types.ChunkTypeText, Content: "new", IsEnabled: true,
|
||||
CreatedAt: deletedAt.Add(time.Minute),
|
||||
}
|
||||
// This is deliberately deleted but has no active replacement. It models a
|
||||
// cancelled/failed parse or a user deletion and must stay recoverable.
|
||||
keep := &types.Chunk{
|
||||
ID: "keep", TenantID: tenantID, KnowledgeID: knowledgeID, KnowledgeBaseID: "kb-1",
|
||||
ChunkIndex: 1, ChunkType: types.ChunkTypeText, Content: "keep", IsEnabled: true,
|
||||
CreatedAt: deletedAt.Add(-time.Minute), DeletedAt: gorm.DeletedAt{Time: deletedAt, Valid: true},
|
||||
}
|
||||
require.NoError(t, db.Unscoped().Create([]*types.Chunk{old, replacement, keep}).Error)
|
||||
require.NoError(t, db.Create(&types.ChunkRevision{
|
||||
ID: "old-revision", TenantID: tenantID, KnowledgeID: knowledgeID, KnowledgeBaseID: "kb-1",
|
||||
ChunkID: old.ID, Revision: 1, Content: "old", EditedAt: deletedAt,
|
||||
}).Error)
|
||||
require.NoError(t, db.Create(&types.ChunkRevision{
|
||||
ID: "keep-revision", TenantID: tenantID, KnowledgeID: knowledgeID, KnowledgeBaseID: "kb-1",
|
||||
ChunkID: keep.ID, Revision: 1, Content: "keep", EditedAt: deletedAt,
|
||||
}).Error)
|
||||
|
||||
purged, err := repo.PurgeSupersededChunksByKnowledgeID(ctx, tenantID, knowledgeID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, int64(1), purged)
|
||||
|
||||
var oldCount, keepCount, replacementCount, oldRevisions, keepRevisions int64
|
||||
require.NoError(t, db.Unscoped().Model(&types.Chunk{}).Where("id = ?", old.ID).Count(&oldCount).Error)
|
||||
require.NoError(t, db.Unscoped().Model(&types.Chunk{}).Where("id = ?", keep.ID).Count(&keepCount).Error)
|
||||
require.NoError(t, db.Model(&types.Chunk{}).Where("id = ?", replacement.ID).Count(&replacementCount).Error)
|
||||
require.NoError(t, db.Model(&types.ChunkRevision{}).Where("chunk_id = ?", old.ID).Count(&oldRevisions).Error)
|
||||
require.NoError(t, db.Model(&types.ChunkRevision{}).Where("chunk_id = ?", keep.ID).Count(&keepRevisions).Error)
|
||||
assert.Zero(t, oldCount, "the superseded chunk must be physically reclaimed")
|
||||
assert.Equal(t, int64(1), keepCount, "unreplaced history must remain recoverable")
|
||||
assert.Equal(t, int64(1), replacementCount)
|
||||
assert.Zero(t, oldRevisions, "revisions of a purged chunk must not become orphaned")
|
||||
assert.Equal(t, int64(1), keepRevisions)
|
||||
}
|
||||
|
||||
func TestPurgeSupersededChunksByKnowledgeIDDoesNotPurgeEarlierActiveChunk(t *testing.T) {
|
||||
db := setupChunkTestDB(t)
|
||||
repo := NewChunkRepository(db).(*chunkRepository)
|
||||
ctx := context.Background()
|
||||
const tenantID uint64 = 1
|
||||
const knowledgeID = "knowledge-1"
|
||||
|
||||
// The live row predates the deletion, so it cannot be a replacement for it.
|
||||
liveCreated := time.Now().UTC().Add(-2 * time.Minute)
|
||||
deletedAt := time.Now().UTC().Add(-time.Minute)
|
||||
old := &types.Chunk{
|
||||
ID: "old", TenantID: tenantID, KnowledgeID: knowledgeID, KnowledgeBaseID: "kb-1",
|
||||
ChunkIndex: 0, ChunkType: types.ChunkTypeText, Content: "old", IsEnabled: true,
|
||||
CreatedAt: deletedAt.Add(-time.Minute), DeletedAt: gorm.DeletedAt{Time: deletedAt, Valid: true},
|
||||
}
|
||||
unrelatedLive := &types.Chunk{
|
||||
ID: "live", TenantID: tenantID, KnowledgeID: knowledgeID, KnowledgeBaseID: "kb-1",
|
||||
ChunkIndex: 0, ChunkType: types.ChunkTypeText, Content: "live", IsEnabled: true,
|
||||
CreatedAt: liveCreated,
|
||||
}
|
||||
require.NoError(t, db.Unscoped().Create([]*types.Chunk{old, unrelatedLive}).Error)
|
||||
|
||||
purged, err := repo.PurgeSupersededChunksByKnowledgeID(ctx, tenantID, knowledgeID)
|
||||
require.NoError(t, err)
|
||||
assert.Zero(t, purged)
|
||||
|
||||
var count int64
|
||||
require.NoError(t, db.Unscoped().Model(&types.Chunk{}).Where("id = ?", old.ID).Count(&count).Error)
|
||||
assert.Equal(t, int64(1), count)
|
||||
}
|
||||
|
||||
func TestCreateChunks_SQLite_SeqIDAfterSoftDelete(t *testing.T) {
|
||||
db := setupChunkTestDB(t)
|
||||
repo := NewChunkRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
kbID := uuid.New().String()
|
||||
knowledgeID := uuid.New().String()
|
||||
|
||||
// Create first batch
|
||||
batch1 := []*types.Chunk{
|
||||
makeChunk(kbID, knowledgeID, "faq"),
|
||||
makeChunk(kbID, knowledgeID, "faq"),
|
||||
makeChunk(kbID, knowledgeID, "faq"),
|
||||
}
|
||||
require.NoError(t, repo.CreateChunks(ctx, batch1))
|
||||
|
||||
// Soft-delete all chunks (like frontend "clear" does)
|
||||
require.NoError(t, db.Where("knowledge_base_id = ?", kbID).Delete(&types.Chunk{}).Error)
|
||||
|
||||
// Verify soft-deleted
|
||||
var activeCount int64
|
||||
db.Model(&types.Chunk{}).Where("knowledge_base_id = ?", kbID).Count(&activeCount)
|
||||
assert.Equal(t, int64(0), activeCount, "all chunks should be soft-deleted")
|
||||
|
||||
// Create second batch — seq_ids must NOT conflict with soft-deleted ones
|
||||
batch2 := []*types.Chunk{
|
||||
makeChunk(kbID, knowledgeID, "faq"),
|
||||
makeChunk(kbID, knowledgeID, "faq"),
|
||||
}
|
||||
err := repo.CreateChunks(ctx, batch2)
|
||||
require.NoError(t, err, "should not get UNIQUE constraint error after soft delete")
|
||||
|
||||
// Verify new seq_ids start after the soft-deleted max (3)
|
||||
var saved []types.Chunk
|
||||
require.NoError(t, db.Order("seq_id").Find(&saved).Error)
|
||||
assert.Len(t, saved, 2)
|
||||
assert.Equal(t, int64(4), saved[0].SeqID)
|
||||
assert.Equal(t, int64(5), saved[1].SeqID)
|
||||
}
|
||||
|
||||
func TestUpdateChunk_SQLite_NoNOWError(t *testing.T) {
|
||||
db := setupChunkTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
kbID := uuid.New().String()
|
||||
knowledgeID := uuid.New().String()
|
||||
|
||||
chunk := makeChunk(kbID, knowledgeID, "faq")
|
||||
require.NoError(t, db.WithContext(ctx).Create(chunk).Error)
|
||||
|
||||
// Test updating a chunk field — verifies no NOW() related errors
|
||||
err := db.WithContext(ctx).Model(chunk).Update("content", "updated content").Error
|
||||
assert.NoError(t, err)
|
||||
|
||||
var saved types.Chunk
|
||||
require.NoError(t, db.First(&saved, "id = ?", chunk.ID).Error)
|
||||
assert.Equal(t, "updated content", saved.Content)
|
||||
}
|
||||
|
||||
func TestListPagedChunksByKnowledgeID_FiltersEnabledState(t *testing.T) {
|
||||
db := setupChunkTestDB(t)
|
||||
repo := NewChunkRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
enabledChunk := makeChunk("kb-1", "faq-knowledge", types.ChunkTypeFAQ)
|
||||
disabledChunk := makeChunk("kb-1", "faq-knowledge", types.ChunkTypeFAQ)
|
||||
require.NoError(t, repo.CreateChunks(ctx, []*types.Chunk{enabledChunk, disabledChunk}))
|
||||
require.NoError(t, db.Model(&types.Chunk{}).
|
||||
Where("id = ?", disabledChunk.ID).
|
||||
Update("is_enabled", false).Error)
|
||||
|
||||
enabled := true
|
||||
chunks, total, err := repo.ListPagedChunksByKnowledgeID(
|
||||
ctx, 1, "faq-knowledge", &types.Pagination{Page: 1, PageSize: 20},
|
||||
[]types.ChunkType{types.ChunkTypeFAQ}, nil, "", "", "", types.KnowledgeTypeFAQ, &enabled,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, int64(1), total)
|
||||
require.Len(t, chunks, 1)
|
||||
assert.Equal(t, enabledChunk.ID, chunks[0].ID)
|
||||
|
||||
disabled := false
|
||||
chunks, total, err = repo.ListPagedChunksByKnowledgeID(
|
||||
ctx, 1, "faq-knowledge", &types.Pagination{Page: 1, PageSize: 20},
|
||||
[]types.ChunkType{types.ChunkTypeFAQ}, nil, "", "", "", types.KnowledgeTypeFAQ, &disabled,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, int64(1), total)
|
||||
require.Len(t, chunks, 1)
|
||||
assert.Equal(t, disabledChunk.ID, chunks[0].ID)
|
||||
|
||||
allChunks, allTotal, err := repo.ListPagedChunksByKnowledgeID(
|
||||
ctx, 1, "faq-knowledge", &types.Pagination{Page: 1, PageSize: 20},
|
||||
[]types.ChunkType{types.ChunkTypeFAQ}, nil, "", "", "", types.KnowledgeTypeFAQ, nil,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(2), allTotal)
|
||||
assert.Len(t, allChunks, 2)
|
||||
}
|
||||
|
||||
func makeSuggestedFAQChunk(t *testing.T, kbID, knowledgeID, tagID, question string) *types.Chunk {
|
||||
t.Helper()
|
||||
chunk := makeChunk(kbID, knowledgeID, types.ChunkTypeFAQ)
|
||||
chunk.TagID = tagID
|
||||
chunk.Flags = types.ChunkFlagRecommended
|
||||
require.NoError(t, chunk.SetFAQMetadata(&types.FAQChunkMetadata{StandardQuestion: question}))
|
||||
return chunk
|
||||
}
|
||||
|
||||
func makeSuggestedDocumentChunk(t *testing.T, kbID, knowledgeID, question string) *types.Chunk {
|
||||
t.Helper()
|
||||
chunk := makeChunk(kbID, knowledgeID, types.ChunkTypeText)
|
||||
require.NoError(t, chunk.SetDocumentMetadata(&types.DocumentChunkMetadata{
|
||||
GeneratedQuestions: []types.GeneratedQuestion{{ID: uuid.NewString(), Question: question}},
|
||||
}))
|
||||
return chunk
|
||||
}
|
||||
|
||||
func TestListRecommendedFAQChunks_FiltersByTagWithoutWideningToParentKB(t *testing.T) {
|
||||
db := setupChunkTestDB(t)
|
||||
repo := NewChunkRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
selectedTag := uuid.NewString()
|
||||
otherTag := uuid.NewString()
|
||||
selected := makeSuggestedFAQChunk(t, "kb-1", "faq-knowledge", selectedTag, "selected question")
|
||||
other := makeSuggestedFAQChunk(t, "kb-1", "faq-knowledge", otherTag, "other question")
|
||||
require.NoError(t, repo.CreateChunks(ctx, []*types.Chunk{selected, other}))
|
||||
|
||||
got, err := repo.ListRecommendedFAQChunks(ctx, 1, nil, nil, []string{selectedTag}, 10)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got, 1)
|
||||
assert.Equal(t, selected.ID, got[0].ID)
|
||||
}
|
||||
|
||||
func TestListRecommendedFAQChunks_UnionsOnlyExplicitScopes(t *testing.T) {
|
||||
db := setupChunkTestDB(t)
|
||||
repo := NewChunkRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
selectedTag := uuid.NewString()
|
||||
tagged := makeSuggestedFAQChunk(t, "kb-tag", "faq-tag", selectedTag, "tagged question")
|
||||
explicitKB := makeSuggestedFAQChunk(t, "kb-explicit", "faq-explicit", uuid.NewString(), "explicit KB question")
|
||||
unselected := makeSuggestedFAQChunk(t, "kb-other", "faq-other", uuid.NewString(), "unselected question")
|
||||
require.NoError(t, repo.CreateChunks(ctx, []*types.Chunk{tagged, explicitKB, unselected}))
|
||||
|
||||
got, err := repo.ListRecommendedFAQChunks(ctx, 1, []string{"kb-explicit"}, nil, []string{selectedTag}, 10)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got, 2)
|
||||
assert.ElementsMatch(t, []string{tagged.ID, explicitKB.ID}, []string{got[0].ID, got[1].ID})
|
||||
}
|
||||
|
||||
func TestListRecentDocumentChunksWithQuestions_KnowledgeScopeDoesNotIncludeSiblingDocuments(t *testing.T) {
|
||||
db := setupChunkTestDB(t)
|
||||
repo := NewChunkRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
selected := makeSuggestedDocumentChunk(t, "kb-1", "doc-selected", "selected document question")
|
||||
sibling := makeSuggestedDocumentChunk(t, "kb-1", "doc-sibling", "sibling document question")
|
||||
require.NoError(t, repo.CreateChunks(ctx, []*types.Chunk{selected, sibling}))
|
||||
|
||||
got, err := repo.ListRecentDocumentChunksWithQuestions(ctx, 1, nil, []string{"doc-selected"}, 10)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got, 1)
|
||||
assert.Equal(t, selected.ID, got[0].ID)
|
||||
}
|
||||
|
||||
func TestListRecentDocumentChunksWithQuestions_UnionsExplicitKBAndKnowledge(t *testing.T) {
|
||||
db := setupChunkTestDB(t)
|
||||
repo := NewChunkRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
fromExplicitKB := makeSuggestedDocumentChunk(t, "kb-explicit", "doc-1", "explicit KB question")
|
||||
fromExplicitDocument := makeSuggestedDocumentChunk(t, "kb-other", "doc-selected", "selected document question")
|
||||
unselected := makeSuggestedDocumentChunk(t, "kb-other", "doc-other", "unselected question")
|
||||
require.NoError(t, repo.CreateChunks(ctx, []*types.Chunk{fromExplicitKB, fromExplicitDocument, unselected}))
|
||||
|
||||
got, err := repo.ListRecentDocumentChunksWithQuestions(
|
||||
ctx, 1, []string{"kb-explicit"}, []string{"doc-selected"}, 10,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got, 2)
|
||||
assert.ElementsMatch(t, []string{fromExplicitKB.ID, fromExplicitDocument.ID}, []string{got[0].ID, got[1].ID})
|
||||
}
|
||||
|
||||
func TestCreateChunks_LeavesSourceContentEmpty(t *testing.T) {
|
||||
db := setupChunkTestDB(t)
|
||||
repo := NewChunkRepository(db)
|
||||
|
||||
chunk := makeChunk("kb-src", "k-src", types.ChunkTypeText)
|
||||
require.NoError(t, repo.CreateChunks(context.Background(), []*types.Chunk{chunk}))
|
||||
|
||||
var saved types.Chunk
|
||||
require.NoError(t, db.First(&saved, "id = ?", chunk.ID).Error)
|
||||
assert.Equal(t, "test content", saved.Content)
|
||||
assert.Empty(t, saved.SourceContent, "source_content is backfilled lazily on first edit, not on create")
|
||||
assert.Equal(t, "ready", saved.IndexStatus)
|
||||
}
|
||||
|
||||
func TestUpdateChunks_UpdatesOnlyDocumentedColumns(t *testing.T) {
|
||||
db := setupChunkTestDB(t)
|
||||
repo := NewChunkRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
chunks := make([]*types.Chunk, 0, 3)
|
||||
for i := 0; i < 3; i++ {
|
||||
c := makeChunk("kb-upd", "k-upd", types.ChunkTypeFAQ)
|
||||
c.Metadata = types.JSON(`{"keep":"me"}`)
|
||||
c.ContentHash = "hash-original"
|
||||
chunks = append(chunks, c)
|
||||
}
|
||||
require.NoError(t, repo.CreateChunks(ctx, chunks))
|
||||
|
||||
var before types.Chunk
|
||||
require.NoError(t, db.First(&before, "id = ?", chunks[0].ID).Error)
|
||||
|
||||
chunks[0].Content = "edited-0"
|
||||
chunks[0].IsEnabled = false
|
||||
chunks[0].Flags = 0
|
||||
chunks[0].Status = int(types.ChunkStatusIndexed)
|
||||
chunks[0].TagID = "tag-a"
|
||||
chunks[0].ContentHash = "hash-should-not-persist"
|
||||
chunks[1].Content = "edited-1"
|
||||
chunks[1].Status = int(types.ChunkStatusStored)
|
||||
// chunks[2] is deliberately not passed to UpdateChunks.
|
||||
require.NoError(t, repo.UpdateChunks(ctx, chunks[:2]))
|
||||
|
||||
var saved []types.Chunk
|
||||
require.NoError(t, db.Order("chunk_index").Find(&saved, "knowledge_id = ?", "k-upd").Error)
|
||||
byID := make(map[string]types.Chunk, len(saved))
|
||||
for _, s := range saved {
|
||||
byID[s.ID] = s
|
||||
}
|
||||
|
||||
c0 := byID[chunks[0].ID]
|
||||
assert.Equal(t, "edited-0", c0.Content)
|
||||
assert.False(t, c0.IsEnabled, "zero-value bool must be written")
|
||||
assert.Equal(t, types.ChunkFlags(0), c0.Flags, "zero-value flags must be written")
|
||||
assert.Equal(t, int(types.ChunkStatusIndexed), c0.Status)
|
||||
assert.Equal(t, "tag-a", c0.TagID)
|
||||
assert.Equal(t, "hash-original", c0.ContentHash, "content_hash is outside the UpdateChunks contract")
|
||||
assert.JSONEq(t, `{"keep":"me"}`, string(c0.Metadata), "metadata is outside the UpdateChunks contract")
|
||||
assert.Equal(t, before.SeqID, c0.SeqID)
|
||||
assert.False(t, c0.UpdatedAt.Before(before.UpdatedAt))
|
||||
|
||||
c1 := byID[chunks[1].ID]
|
||||
assert.Equal(t, "edited-1", c1.Content)
|
||||
assert.True(t, c1.IsEnabled)
|
||||
assert.Equal(t, int(types.ChunkStatusStored), c1.Status)
|
||||
|
||||
c2 := byID[chunks[2].ID]
|
||||
assert.Equal(t, "test content", c2.Content, "rows not in the batch stay untouched")
|
||||
}
|
||||
|
||||
func TestUpdateChunks_CleansInvalidUTF8(t *testing.T) {
|
||||
db := setupChunkTestDB(t)
|
||||
repo := NewChunkRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
chunk := makeChunk("kb-utf8", "k-utf8", types.ChunkTypeText)
|
||||
require.NoError(t, repo.CreateChunks(ctx, []*types.Chunk{chunk}))
|
||||
|
||||
chunk.Content = "ok\xffbad"
|
||||
require.NoError(t, repo.UpdateChunks(ctx, []*types.Chunk{chunk}))
|
||||
|
||||
var saved types.Chunk
|
||||
require.NoError(t, db.First(&saved, "id = ?", chunk.ID).Error)
|
||||
assert.True(t, utf8.ValidString(saved.Content))
|
||||
}
|
||||
|
||||
func TestUpdateChunkFieldsByIDs_ScopesByTenantAndSetsUpdatedAt(t *testing.T) {
|
||||
db := setupChunkTestDB(t)
|
||||
repo := NewChunkRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
mine := makeChunk("kb-fields", "k-fields", types.ChunkTypeFAQ)
|
||||
other := makeChunk("kb-fields", "k-fields", types.ChunkTypeFAQ)
|
||||
other.TenantID = 2
|
||||
require.NoError(t, repo.CreateChunks(ctx, []*types.Chunk{mine, other}))
|
||||
|
||||
var before types.Chunk
|
||||
require.NoError(t, db.First(&before, "id = ?", mine.ID).Error)
|
||||
|
||||
require.NoError(t, repo.UpdateChunkFieldsByIDs(ctx, 1, []string{mine.ID, other.ID}, map[string]interface{}{
|
||||
"status": int(types.ChunkStatusIndexed),
|
||||
}))
|
||||
|
||||
var savedMine, savedOther types.Chunk
|
||||
require.NoError(t, db.First(&savedMine, "id = ?", mine.ID).Error)
|
||||
require.NoError(t, db.First(&savedOther, "id = ?", other.ID).Error)
|
||||
assert.Equal(t, int(types.ChunkStatusIndexed), savedMine.Status)
|
||||
assert.Equal(t, "test content", savedMine.Content, "other columns are untouched")
|
||||
assert.False(t, savedMine.UpdatedAt.Before(before.UpdatedAt))
|
||||
assert.Equal(t, int(types.ChunkStatusDefault), savedOther.Status, "rows of another tenant must not change")
|
||||
|
||||
// Empty inputs are no-ops.
|
||||
require.NoError(t, repo.UpdateChunkFieldsByIDs(ctx, 1, nil, map[string]interface{}{"status": 0}))
|
||||
require.NoError(t, repo.UpdateChunkFieldsByIDs(ctx, 1, []string{mine.ID}, nil))
|
||||
}
|
||||
|
||||
// Exercise the actual batch insert used by FAQ imports, including a second SQL batch.
|
||||
func TestCreateChunks_PreservesExplicitEnabledState(t *testing.T) {
|
||||
for _, count := range []int{2, createChunksBatchSize + 2} {
|
||||
t.Run(fmt.Sprint(count), func(t *testing.T) {
|
||||
db := setupChunkTestDB(t)
|
||||
repo := NewChunkRepository(db)
|
||||
chunks := make([]*types.Chunk, count)
|
||||
for i := range chunks {
|
||||
chunks[i] = makeChunk("kb-enabled", "faq-enabled", types.ChunkTypeFAQ)
|
||||
chunks[i].IsEnabled = i%2 == 0
|
||||
chunks[i].ChunkIndex = i
|
||||
}
|
||||
require.NoError(t, repo.CreateChunks(context.Background(), chunks))
|
||||
var saved []types.Chunk
|
||||
require.NoError(t, db.Order("chunk_index").Find(&saved).Error)
|
||||
require.Len(t, saved, count)
|
||||
for i, chunk := range saved {
|
||||
assert.Equal(t, i%2 == 0, chunk.IsEnabled, "stored chunk %d", i)
|
||||
assert.Equal(t, i%2 == 0, chunks[i].IsEnabled, "caller chunk %d", i)
|
||||
assert.Equal(t, chunks[i].SeqID, chunk.SeqID)
|
||||
assert.Positive(t, chunk.SeqID)
|
||||
assert.False(t, chunks[i].CreatedAt.IsZero())
|
||||
assert.True(t, chunks[i].CreatedAt.Equal(chunk.CreatedAt))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ErrCustomAgentNotFound is returned when a custom agent is not found
|
||||
var ErrCustomAgentNotFound = errors.New("custom agent not found")
|
||||
|
||||
// customAgentRepository implements the CustomAgentRepository interface
|
||||
type customAgentRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewCustomAgentRepository creates a new custom agent repository
|
||||
func NewCustomAgentRepository(db *gorm.DB) interfaces.CustomAgentRepository {
|
||||
return &customAgentRepository{db: db}
|
||||
}
|
||||
|
||||
// CreateAgent creates a new custom agent
|
||||
func (r *customAgentRepository) CreateAgent(ctx context.Context, agent *types.CustomAgent) error {
|
||||
return r.db.WithContext(ctx).Create(agent).Error
|
||||
}
|
||||
|
||||
// GetAgentByID gets an agent by id and tenant
|
||||
func (r *customAgentRepository) GetAgentByID(ctx context.Context, id string, tenantID uint64) (*types.CustomAgent, error) {
|
||||
var agent types.CustomAgent
|
||||
if err := r.db.WithContext(ctx).Where("id = ? AND tenant_id = ?", id, tenantID).First(&agent).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrCustomAgentNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &agent, nil
|
||||
}
|
||||
|
||||
// ListAgentsByTenantID lists all agents for a specific tenant
|
||||
func (r *customAgentRepository) ListAgentsByTenantID(ctx context.Context, tenantID uint64) ([]*types.CustomAgent, error) {
|
||||
var agents []*types.CustomAgent
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ?", tenantID).
|
||||
Order("created_at DESC").
|
||||
Find(&agents).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return agents, nil
|
||||
}
|
||||
|
||||
// UpdateAgent updates an agent
|
||||
func (r *customAgentRepository) UpdateAgent(ctx context.Context, agent *types.CustomAgent) error {
|
||||
return r.db.WithContext(ctx).Save(agent).Error
|
||||
}
|
||||
|
||||
// DeleteAgent deletes an agent (soft delete)
|
||||
func (r *customAgentRepository) DeleteAgent(ctx context.Context, id string, tenantID uint64) error {
|
||||
return r.db.WithContext(ctx).Where("id = ? AND tenant_id = ?", id, tenantID).Delete(&types.CustomAgent{}).Error
|
||||
}
|
||||
|
||||
// CountByModelID counts active agents whose config references modelID.
|
||||
func (r *customAgentRepository) CountByModelID(
|
||||
ctx context.Context, tenantID uint64, modelID string,
|
||||
) (int64, error) {
|
||||
var count int64
|
||||
query := r.db.WithContext(ctx).
|
||||
Model(&types.CustomAgent{}).
|
||||
Where("tenant_id = ?", tenantID)
|
||||
query = scopeCustomAgentsByModelID(query, modelID)
|
||||
err := query.Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
// ListModelUsages returns active agents that reference modelID. Only id, name,
|
||||
// and config are loaded; the config is decoded locally and never returned.
|
||||
func (r *customAgentRepository) ListModelUsages(
|
||||
ctx context.Context, tenantID uint64, modelID string,
|
||||
) ([]types.ModelUsageResource, error) {
|
||||
rows := make([]*types.CustomAgent, 0)
|
||||
query := r.db.WithContext(ctx).
|
||||
Model(&types.CustomAgent{}).
|
||||
Select("id", "name", "config").
|
||||
Where("tenant_id = ?", tenantID)
|
||||
query = scopeCustomAgentsByModelID(query, modelID)
|
||||
if err := query.Order("name ASC, id ASC").Limit(types.ModelUsageListLimit).Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
usages := make([]types.ModelUsageResource, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
bindings := customAgentModelUsageBindings(row, modelID)
|
||||
if len(bindings) == 0 {
|
||||
continue
|
||||
}
|
||||
usages = append(usages, types.ModelUsageResource{
|
||||
ID: row.ID,
|
||||
Name: row.Name,
|
||||
Bindings: bindings,
|
||||
})
|
||||
}
|
||||
return usages, nil
|
||||
}
|
||||
|
||||
// CountBySandboxConfigID counts agents pointing at a sandbox config.
|
||||
//
|
||||
// Used only to warn the admin which agents reference a config; never use it to
|
||||
// refuse operations. Agent references are permanent state, so blocking on them
|
||||
// would make credential rotation impossible.
|
||||
func (r *customAgentRepository) CountBySandboxConfigID(
|
||||
ctx context.Context, tenantID uint64, configID string,
|
||||
) (int64, error) {
|
||||
var count int64
|
||||
query := r.db.WithContext(ctx).
|
||||
Model(&types.CustomAgent{}).
|
||||
Where("tenant_id = ?", tenantID)
|
||||
query = scopeCustomAgentsBySandboxConfigID(query, configID)
|
||||
err := query.Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
// ListNamesBySandboxConfigID returns agent names pointing at a sandbox config.
|
||||
//
|
||||
// Used only to warn the admin which agents reference a config; never use it to
|
||||
// refuse operations. Agent references are permanent state, so blocking on them
|
||||
// would make credential rotation impossible.
|
||||
func (r *customAgentRepository) ListNamesBySandboxConfigID(
|
||||
ctx context.Context, tenantID uint64, configID string,
|
||||
) ([]string, error) {
|
||||
var names []string
|
||||
query := r.db.WithContext(ctx).
|
||||
Model(&types.CustomAgent{}).
|
||||
Where("tenant_id = ?", tenantID)
|
||||
query = scopeCustomAgentsBySandboxConfigID(query, configID)
|
||||
err := query.Order("name ASC").Pluck("name", &names).Error
|
||||
return names, err
|
||||
}
|
||||
@@ -0,0 +1,409 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// DataSourceRepository provides data access for data sources
|
||||
type DataSourceRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewDataSourceRepository creates a new data source repository
|
||||
func NewDataSourceRepository(db *gorm.DB) interfaces.DataSourceRepository {
|
||||
return &DataSourceRepository{db: db}
|
||||
}
|
||||
|
||||
// Create inserts a new data source record
|
||||
func (r *DataSourceRepository) Create(ctx context.Context, ds *types.DataSource) error {
|
||||
if ds == nil {
|
||||
return errors.New("data source is nil")
|
||||
}
|
||||
// GORM treats false as the zero value of bool. For a field tagged
|
||||
// default:true it replaces both the INSERT value and the in-memory field
|
||||
// with true, so a caller-selected false would be lost. Capture it, force
|
||||
// the column write, then restore the struct so Create's return value (and
|
||||
// the HTTP 201 body) match the database.
|
||||
syncDeletions := ds.SyncDeletions
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Create(ds).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Model(&types.DataSource{}).
|
||||
Where("id = ?", ds.ID).
|
||||
UpdateColumn("sync_deletions", syncDeletions).Error
|
||||
})
|
||||
ds.SyncDeletions = syncDeletions
|
||||
return err
|
||||
}
|
||||
|
||||
// FindByID retrieves a data source by ID
|
||||
func (r *DataSourceRepository) FindByID(ctx context.Context, id string) (*types.DataSource, error) {
|
||||
if id == "" {
|
||||
return nil, errors.New("id is empty")
|
||||
}
|
||||
var ds types.DataSource
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("id = ?", id).
|
||||
Where("deleted_at IS NULL").
|
||||
First(&ds).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, errors.New("data source not found")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &ds, nil
|
||||
}
|
||||
|
||||
// FindByKnowledgeBase lists all data sources for a knowledge base
|
||||
func (r *DataSourceRepository) FindByKnowledgeBase(ctx context.Context, kbID string) ([]*types.DataSource, error) {
|
||||
if kbID == "" {
|
||||
return nil, errors.New("knowledge base id is empty")
|
||||
}
|
||||
var dataSources []*types.DataSource
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("knowledge_base_id = ?", kbID).
|
||||
Where("deleted_at IS NULL").
|
||||
Order("created_at DESC").
|
||||
Find(&dataSources).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return dataSources, nil
|
||||
}
|
||||
|
||||
// Update updates an existing data source
|
||||
func (r *DataSourceRepository) Update(ctx context.Context, ds *types.DataSource) error {
|
||||
if ds == nil {
|
||||
return errors.New("data source is nil")
|
||||
}
|
||||
if ds.ID == "" {
|
||||
return errors.New("data source id is empty")
|
||||
}
|
||||
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Model(ds).Updates(ds).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
// GORM Updates(struct) deliberately skips zero values, which would make
|
||||
// a user-selected sync_deletions=false or manual-only schedule impossible to persist.
|
||||
return tx.Model(&types.DataSource{}).
|
||||
Where("id = ?", ds.ID).
|
||||
UpdateColumns(map[string]interface{}{
|
||||
"sync_deletions": ds.SyncDeletions,
|
||||
"sync_schedule": ds.SyncSchedule,
|
||||
}).Error
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateSyncState updates only fields managed by sync execution. GORM's
|
||||
// Updates(struct) skips zero values, so use a map here to persist cleared error
|
||||
// messages without broadening the generic Update method.
|
||||
func (r *DataSourceRepository) UpdateSyncState(ctx context.Context, ds *types.DataSource) error {
|
||||
if ds == nil {
|
||||
return errors.New("data source is nil")
|
||||
}
|
||||
if ds.ID == "" {
|
||||
return errors.New("data source id is empty")
|
||||
}
|
||||
if err := r.db.WithContext(ctx).
|
||||
Model(&types.DataSource{}).
|
||||
Where("id = ?", ds.ID).
|
||||
Updates(map[string]interface{}{
|
||||
"status": ds.Status,
|
||||
"last_sync_at": ds.LastSyncAt,
|
||||
"last_sync_cursor": ds.LastSyncCursor,
|
||||
"last_sync_result": ds.LastSyncResult,
|
||||
"error_message": ds.ErrorMessage,
|
||||
"updated_at": time.Now().UTC(),
|
||||
}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Delete performs a soft delete
|
||||
func (r *DataSourceRepository) Delete(ctx context.Context, id string) error {
|
||||
if id == "" {
|
||||
return errors.New("id is empty")
|
||||
}
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("id = ?", id).
|
||||
Delete(&types.DataSource{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// FindActive retrieves all active data sources (used for scheduling)
|
||||
func (r *DataSourceRepository) FindActive(ctx context.Context) ([]*types.DataSource, error) {
|
||||
var dataSources []*types.DataSource
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("status = ?", types.DataSourceStatusActive).
|
||||
Where("deleted_at IS NULL").
|
||||
Where("sync_schedule != ''").
|
||||
Order("created_at DESC").
|
||||
Find(&dataSources).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return dataSources, nil
|
||||
}
|
||||
|
||||
// SyncLogRepository provides data access for sync logs
|
||||
type SyncLogRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewSyncLogRepository creates a new sync log repository
|
||||
func NewSyncLogRepository(db *gorm.DB) interfaces.SyncLogRepository {
|
||||
return &SyncLogRepository{db: db}
|
||||
}
|
||||
|
||||
// Create inserts a new sync log entry
|
||||
func (r *SyncLogRepository) Create(ctx context.Context, log *types.SyncLog) error {
|
||||
if log == nil {
|
||||
return errors.New("sync log is nil")
|
||||
}
|
||||
if err := r.db.WithContext(ctx).Create(log).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// FindByID retrieves a sync log by ID
|
||||
func (r *SyncLogRepository) FindByID(ctx context.Context, id string) (*types.SyncLog, error) {
|
||||
if id == "" {
|
||||
return nil, errors.New("id is empty")
|
||||
}
|
||||
var log types.SyncLog
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("id = ?", id).
|
||||
First(&log).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, errors.New("sync log not found")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &log, nil
|
||||
}
|
||||
|
||||
// FindByDataSource lists sync logs for a data source with pagination
|
||||
func (r *SyncLogRepository) FindByDataSource(ctx context.Context, dsID string, limit int, offset int) ([]*types.SyncLog, error) {
|
||||
if dsID == "" {
|
||||
return nil, errors.New("data source id is empty")
|
||||
}
|
||||
if limit <= 0 {
|
||||
limit = 10
|
||||
}
|
||||
if offset < 0 {
|
||||
offset = 0
|
||||
}
|
||||
var logs []*types.SyncLog
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("data_source_id = ?", dsID).
|
||||
Order("started_at DESC").
|
||||
Limit(limit).
|
||||
Offset(offset).
|
||||
Find(&logs).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return logs, nil
|
||||
}
|
||||
|
||||
// FindLatest retrieves the most recent sync log for a data source
|
||||
func (r *SyncLogRepository) FindLatest(ctx context.Context, dsID string) (*types.SyncLog, error) {
|
||||
if dsID == "" {
|
||||
return nil, errors.New("data source id is empty")
|
||||
}
|
||||
var log types.SyncLog
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("data_source_id = ?", dsID).
|
||||
Order("started_at DESC").
|
||||
Limit(1).
|
||||
First(&log).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &log, nil
|
||||
}
|
||||
|
||||
// HasRunningSync checks if a data source has any sync currently in "running" status.
|
||||
func (r *SyncLogRepository) HasRunningSync(ctx context.Context, dsID string) (bool, error) {
|
||||
if dsID == "" {
|
||||
return false, errors.New("data source id is empty")
|
||||
}
|
||||
var count int64
|
||||
if err := r.db.WithContext(ctx).
|
||||
Model(&types.SyncLog{}).
|
||||
Where("data_source_id = ?", dsID).
|
||||
Where("status = ?", types.SyncLogStatusRunning).
|
||||
Count(&count).Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
return count > 0, nil
|
||||
}
|
||||
|
||||
// Update updates an existing sync log entry
|
||||
func (r *SyncLogRepository) Update(ctx context.Context, log *types.SyncLog) error {
|
||||
if log == nil {
|
||||
return errors.New("sync log is nil")
|
||||
}
|
||||
if log.ID == "" {
|
||||
return errors.New("sync log id is empty")
|
||||
}
|
||||
if err := r.db.WithContext(ctx).
|
||||
Model(log).
|
||||
Updates(log).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateResult updates only fields produced by sync execution. Use an explicit
|
||||
// map so empty error messages are written when a later sync succeeds.
|
||||
func (r *SyncLogRepository) UpdateResult(ctx context.Context, log *types.SyncLog) error {
|
||||
if log == nil {
|
||||
return errors.New("sync log is nil")
|
||||
}
|
||||
if log.ID == "" {
|
||||
return errors.New("sync log id is empty")
|
||||
}
|
||||
if err := r.db.WithContext(ctx).
|
||||
Model(&types.SyncLog{}).
|
||||
Where("id = ?", log.ID).
|
||||
Updates(map[string]interface{}{
|
||||
"status": log.Status,
|
||||
"finished_at": log.FinishedAt,
|
||||
"items_total": log.ItemsTotal,
|
||||
"items_created": log.ItemsCreated,
|
||||
"items_updated": log.ItemsUpdated,
|
||||
"items_deleted": log.ItemsDeleted,
|
||||
"items_skipped": log.ItemsSkipped,
|
||||
"items_failed": log.ItemsFailed,
|
||||
"error_message": log.ErrorMessage,
|
||||
"result": log.Result,
|
||||
"updated_at": time.Now().UTC(),
|
||||
}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CancelPendingByDataSource marks all non-terminal sync logs for a data source as canceled.
|
||||
func (r *SyncLogRepository) CancelPendingByDataSource(ctx context.Context, dsID string) error {
|
||||
if dsID == "" {
|
||||
return errors.New("data source id is empty")
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
return r.db.WithContext(ctx).
|
||||
Model(&types.SyncLog{}).
|
||||
Where("data_source_id = ?", dsID).
|
||||
Where("status IN ?", []string{types.SyncLogStatusRunning, "pending"}).
|
||||
Updates(map[string]interface{}{
|
||||
"status": types.SyncLogStatusCanceled,
|
||||
"finished_at": &now,
|
||||
"error_message": "data source deleted",
|
||||
}).Error
|
||||
}
|
||||
|
||||
// CleanupOldLogs applies each source's retention policy, including soft-deleted
|
||||
// sources. Missing sources and non-positive policies use the default (normally
|
||||
// 30 days). Failed logs of live sources may still be retried by Asynq.
|
||||
func (r *SyncLogRepository) CleanupOldLogs(ctx context.Context, defaultRetentionDays int) error {
|
||||
if defaultRetentionDays <= 0 {
|
||||
defaultRetentionDays = 30
|
||||
}
|
||||
var periods []int
|
||||
if err := r.db.WithContext(ctx).Unscoped().Model(&types.DataSource{}).
|
||||
Where("sync_log_retention_days > 0 AND sync_log_retention_days <> ?", defaultRetentionDays).
|
||||
Distinct().Pluck("sync_log_retention_days", &periods).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
periods = append(periods, defaultRetentionDays)
|
||||
now := time.Now().UTC()
|
||||
sourceByID := "data_sources.id = sync_logs.data_source_id"
|
||||
sourceMatch := sourceByID + " AND data_sources.tenant_id = sync_logs.tenant_id"
|
||||
liveSource := r.db.WithContext(ctx).Model(&types.DataSource{}).Select("1").Where(sourceByID)
|
||||
terminal := r.db.WithContext(ctx).
|
||||
Where("status IN ?", []string{
|
||||
types.SyncLogStatusSuccess, types.SyncLogStatusPartial, types.SyncLogStatusCanceled,
|
||||
}).
|
||||
Or("status = ? AND NOT EXISTS (?)", types.SyncLogStatusFailed, liveSource)
|
||||
for _, days := range periods {
|
||||
// A very large user policy must not overflow a time.Duration and turn
|
||||
// into a recent cutoff. No valid log can predate year 1.
|
||||
if days > now.Year()*366 {
|
||||
continue
|
||||
}
|
||||
cutoff := now.AddDate(0, 0, -days)
|
||||
if cutoff.Year() < 1 {
|
||||
continue
|
||||
}
|
||||
sources := r.db.WithContext(ctx).Unscoped().Model(&types.DataSource{}).
|
||||
Select("1")
|
||||
policy := "EXISTS (?)"
|
||||
if days == defaultRetentionDays {
|
||||
// Also retire orphan logs after the default horizon instead of
|
||||
// keeping them forever once their source has been removed.
|
||||
policy = "NOT EXISTS (?)"
|
||||
sources = sources.Where(sourceByID).
|
||||
Where("sync_log_retention_days > 0 AND sync_log_retention_days <> ?", days)
|
||||
} else {
|
||||
sources = sources.Where(sourceMatch).
|
||||
Where("sync_log_retention_days = ?", days)
|
||||
}
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where(terminal).
|
||||
Where("COALESCE(finished_at, started_at) < ?", cutoff).
|
||||
Where(policy, sources).
|
||||
Delete(&types.SyncLog{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// PatchSyncSettings never writes runtime state or fields omitted by the request.
|
||||
func (r *DataSourceRepository) PatchSyncSettings(
|
||||
ctx context.Context, ds *types.DataSource, expectedConfig types.JSON, fields []string,
|
||||
) error {
|
||||
if ds == nil || ds.ID == "" || ds.TenantID == 0 || len(fields) == 0 {
|
||||
return errors.New("data source identity and settings are required")
|
||||
}
|
||||
values := map[string]any{}
|
||||
query := r.db.WithContext(ctx).Model(&types.DataSource{}).
|
||||
Where("id = ? AND tenant_id = ?", ds.ID, ds.TenantID)
|
||||
for _, field := range fields {
|
||||
switch field {
|
||||
case "sync_schedule":
|
||||
values[field] = ds.SyncSchedule
|
||||
case "sync_mode":
|
||||
values[field] = ds.SyncMode
|
||||
case "conflict_strategy":
|
||||
values[field] = ds.ConflictStrategy
|
||||
case "sync_deletions":
|
||||
values[field] = ds.SyncDeletions
|
||||
case "config":
|
||||
values[field] = ds.Config
|
||||
// Config includes credentials and connector settings. Refuse to replace
|
||||
// them if another request changed them while selection was being edited.
|
||||
query = query.Where("config = ?", expectedConfig)
|
||||
default:
|
||||
return errors.New("unsupported sync setting")
|
||||
}
|
||||
}
|
||||
result := query.Updates(values)
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
return types.ErrDataSourceSettingsConflict
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func setupDataSourceRepoTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.AutoMigrate(&types.DataSource{}, &types.SyncLog{}))
|
||||
return db
|
||||
}
|
||||
|
||||
func TestDataSourceRepositoryUpdateSyncStateClearsErrorMessage(t *testing.T) {
|
||||
db := setupDataSourceRepoTestDB(t)
|
||||
repo := NewDataSourceRepository(db)
|
||||
now := time.Now().UTC()
|
||||
result := types.JSON(`{"total":0}`)
|
||||
|
||||
ds := &types.DataSource{
|
||||
ID: "ds-1",
|
||||
TenantID: 1,
|
||||
KnowledgeBaseID: "kb-1",
|
||||
Name: "Feishu",
|
||||
Type: types.ConnectorTypeFeishu,
|
||||
Status: types.DataSourceStatusError,
|
||||
ErrorMessage: "previous failure",
|
||||
}
|
||||
require.NoError(t, repo.Create(context.Background(), ds))
|
||||
|
||||
ds.Status = types.DataSourceStatusActive
|
||||
ds.ErrorMessage = ""
|
||||
ds.LastSyncAt = &now
|
||||
ds.LastSyncResult = result
|
||||
require.NoError(t, repo.UpdateSyncState(context.Background(), ds))
|
||||
|
||||
var stored types.DataSource
|
||||
require.NoError(t, db.First(&stored, "id = ?", ds.ID).Error)
|
||||
assert.Equal(t, types.DataSourceStatusActive, stored.Status)
|
||||
assert.Empty(t, stored.ErrorMessage)
|
||||
assert.Equal(t, result.ToString(), stored.LastSyncResult.ToString())
|
||||
require.NotNil(t, stored.LastSyncAt)
|
||||
}
|
||||
|
||||
func TestDataSourceRepositoryUpdatePersistsDisabledSyncDeletions(t *testing.T) {
|
||||
db := setupDataSourceRepoTestDB(t)
|
||||
repo := NewDataSourceRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
ds := &types.DataSource{
|
||||
ID: "ds-sync-deletions",
|
||||
TenantID: 1,
|
||||
KnowledgeBaseID: "kb-1",
|
||||
Name: "Feishu",
|
||||
Type: types.ConnectorTypeFeishu,
|
||||
SyncDeletions: true,
|
||||
}
|
||||
require.NoError(t, repo.Create(ctx, ds))
|
||||
|
||||
ds.SyncDeletions = false
|
||||
require.NoError(t, repo.Update(ctx, ds))
|
||||
assert.False(t, ds.SyncDeletions)
|
||||
|
||||
var stored types.DataSource
|
||||
require.NoError(t, db.First(&stored, "id = ?", ds.ID).Error)
|
||||
assert.False(t, stored.SyncDeletions)
|
||||
|
||||
ds.SyncDeletions = true
|
||||
require.NoError(t, repo.Update(ctx, ds))
|
||||
assert.True(t, ds.SyncDeletions)
|
||||
require.NoError(t, db.First(&stored, "id = ?", ds.ID).Error)
|
||||
assert.True(t, stored.SyncDeletions)
|
||||
}
|
||||
|
||||
func TestDataSourceRepositoryCreatePersistsDisabledSyncDeletions(t *testing.T) {
|
||||
db := setupDataSourceRepoTestDB(t)
|
||||
repo := NewDataSourceRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
ds := &types.DataSource{
|
||||
ID: "ds-create-sync-deletions",
|
||||
TenantID: 1,
|
||||
KnowledgeBaseID: "kb-1",
|
||||
Name: "Feishu",
|
||||
Type: types.ConnectorTypeFeishu,
|
||||
SyncDeletions: false,
|
||||
}
|
||||
require.NoError(t, repo.Create(ctx, ds))
|
||||
assert.False(t, ds.SyncDeletions, "Create must not leave the in-memory field hydrated to the GORM default")
|
||||
|
||||
var stored types.DataSource
|
||||
require.NoError(t, db.First(&stored, "id = ?", ds.ID).Error)
|
||||
assert.False(t, stored.SyncDeletions)
|
||||
|
||||
// A later Updates() on the same pointer must not persist the hydrated default.
|
||||
ds.Name = "Renamed"
|
||||
require.NoError(t, repo.Update(ctx, ds))
|
||||
require.NoError(t, db.First(&stored, "id = ?", ds.ID).Error)
|
||||
assert.False(t, stored.SyncDeletions)
|
||||
assert.Equal(t, "Renamed", stored.Name)
|
||||
}
|
||||
|
||||
func TestDataSourceRepositoryCreatePersistsEnabledSyncDeletions(t *testing.T) {
|
||||
db := setupDataSourceRepoTestDB(t)
|
||||
repo := NewDataSourceRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
ds := &types.DataSource{
|
||||
ID: "ds-create-sync-deletions-enabled",
|
||||
TenantID: 1,
|
||||
KnowledgeBaseID: "kb-1",
|
||||
Name: "Feishu",
|
||||
Type: types.ConnectorTypeFeishu,
|
||||
SyncDeletions: true,
|
||||
}
|
||||
require.NoError(t, repo.Create(ctx, ds))
|
||||
assert.True(t, ds.SyncDeletions)
|
||||
|
||||
var stored types.DataSource
|
||||
require.NoError(t, db.First(&stored, "id = ?", ds.ID).Error)
|
||||
assert.True(t, stored.SyncDeletions)
|
||||
}
|
||||
|
||||
func TestDataSourceRepositoryDeleteSoftDeletesOnSQLite(t *testing.T) {
|
||||
db := setupDataSourceRepoTestDB(t)
|
||||
repo := NewDataSourceRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
target := &types.DataSource{
|
||||
ID: "ds-delete-target",
|
||||
TenantID: 1,
|
||||
KnowledgeBaseID: "kb-1",
|
||||
Name: "Delete target",
|
||||
Type: types.ConnectorTypeFeishu,
|
||||
}
|
||||
other := &types.DataSource{
|
||||
ID: "ds-delete-other",
|
||||
TenantID: 1,
|
||||
KnowledgeBaseID: "kb-1",
|
||||
Name: "Other data source",
|
||||
Type: types.ConnectorTypeFeishu,
|
||||
}
|
||||
require.NoError(t, repo.Create(ctx, target))
|
||||
require.NoError(t, repo.Create(ctx, other))
|
||||
|
||||
require.NoError(t, repo.Delete(ctx, target.ID))
|
||||
|
||||
var deleted types.DataSource
|
||||
require.NoError(t, db.Unscoped().First(&deleted, "id = ?", target.ID).Error)
|
||||
assert.True(t, deleted.DeletedAt.Valid)
|
||||
|
||||
found, err := repo.FindByID(ctx, target.ID)
|
||||
assert.Error(t, err)
|
||||
assert.Nil(t, found)
|
||||
|
||||
untouched, err := repo.FindByID(ctx, other.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, other.ID, untouched.ID)
|
||||
}
|
||||
|
||||
func TestSyncLogRepositoryUpdateResultClearsErrorMessage(t *testing.T) {
|
||||
db := setupDataSourceRepoTestDB(t)
|
||||
repo := NewSyncLogRepository(db)
|
||||
finishedAt := time.Now().UTC()
|
||||
result := types.JSON(`{"total":0}`)
|
||||
|
||||
log := &types.SyncLog{
|
||||
ID: "log-1",
|
||||
DataSourceID: "ds-1",
|
||||
TenantID: 1,
|
||||
Status: types.SyncLogStatusFailed,
|
||||
ErrorMessage: "previous failure",
|
||||
ItemsTotal: 1,
|
||||
ItemsFailed: 1,
|
||||
}
|
||||
require.NoError(t, repo.Create(context.Background(), log))
|
||||
|
||||
log.Status = types.SyncLogStatusSuccess
|
||||
log.ErrorMessage = ""
|
||||
log.FinishedAt = &finishedAt
|
||||
log.ItemsTotal = 0
|
||||
log.ItemsFailed = 0
|
||||
log.Result = result
|
||||
require.NoError(t, repo.UpdateResult(context.Background(), log))
|
||||
|
||||
var stored types.SyncLog
|
||||
require.NoError(t, db.First(&stored, "id = ?", log.ID).Error)
|
||||
assert.Equal(t, types.SyncLogStatusSuccess, stored.Status)
|
||||
assert.Empty(t, stored.ErrorMessage)
|
||||
assert.Zero(t, stored.ItemsTotal)
|
||||
assert.Zero(t, stored.ItemsFailed)
|
||||
assert.Equal(t, result.ToString(), stored.Result.ToString())
|
||||
require.NotNil(t, stored.FinishedAt)
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestSyncLogRetentionPerSource(t *testing.T) {
|
||||
for _, backend := range []string{"sqlite", "postgres"} {
|
||||
t.Run(backend, func(t *testing.T) {
|
||||
dialect := sqlite.Open(":memory:")
|
||||
if backend == "postgres" {
|
||||
dsn := os.Getenv("ACADEMY_REPOSITORY_TEST_POSTGRES_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("set ACADEMY_REPOSITORY_TEST_POSTGRES_DSN for PostgreSQL sync log retention tests")
|
||||
}
|
||||
dialect = postgres.Open(dsn)
|
||||
}
|
||||
db, err := gorm.Open(dialect, &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
sqlDB, err := db.DB()
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { require.NoError(t, sqlDB.Close()) })
|
||||
db = db.Begin()
|
||||
require.NoError(t, db.Error)
|
||||
t.Cleanup(func() { require.NoError(t, db.Rollback().Error) })
|
||||
// Temporary tables exercise both dialects without modifying any
|
||||
// existing deployment data when an integration-test DSN is supplied.
|
||||
require.NoError(t, db.Exec(`CREATE TEMP TABLE data_sources (
|
||||
id TEXT PRIMARY KEY, tenant_id BIGINT, sync_log_retention_days INT, deleted_at TIMESTAMP
|
||||
)`).Error)
|
||||
require.NoError(t, db.Exec(`CREATE TEMP TABLE sync_logs (
|
||||
id TEXT PRIMARY KEY, data_source_id TEXT, tenant_id BIGINT, status TEXT,
|
||||
started_at TIMESTAMP, finished_at TIMESTAMP
|
||||
)`).Error)
|
||||
now := time.Now().UTC()
|
||||
for _, source := range []struct {
|
||||
id string
|
||||
tenant uint64
|
||||
days int
|
||||
deleted bool
|
||||
}{
|
||||
{"short", 1, 1, false},
|
||||
{"long", 2, 30, false},
|
||||
{"unrelated", 3, 90, false},
|
||||
{"unset", 1, 0, false},
|
||||
{"negative", 1, -1, false},
|
||||
{"deleted-long", 2, 90, true},
|
||||
{"deleted-short", 2, 1, true},
|
||||
{"large", 1, 1 << 30, false},
|
||||
} {
|
||||
var deletedAt *time.Time
|
||||
if source.deleted {
|
||||
deletedAt = &now
|
||||
}
|
||||
require.NoError(t, db.Exec("INSERT INTO data_sources VALUES (?, ?, ?, ?)",
|
||||
source.id, source.tenant, source.days, deletedAt).Error)
|
||||
}
|
||||
var want []string
|
||||
for _, log := range []struct {
|
||||
id string
|
||||
source string
|
||||
tenant uint64
|
||||
status string
|
||||
ageDays int
|
||||
finishedAge int
|
||||
keep bool
|
||||
}{
|
||||
{"short-expired", "short", 1, types.SyncLogStatusSuccess, 2, 2, false},
|
||||
{"partial-expired", "short", 1, types.SyncLogStatusPartial, 2, 2, false},
|
||||
{"canceled-expired", "short", 1, types.SyncLogStatusCanceled, 2, 2, false},
|
||||
{"recent", "short", 1, types.SyncLogStatusSuccess, 0, 0, true},
|
||||
{"recently-finished", "short", 1, types.SyncLogStatusSuccess, 60, 0, true},
|
||||
{"legacy-expired", "short", 1, types.SyncLogStatusSuccess, 2, -1, false},
|
||||
{"running", "short", 1, types.SyncLogStatusRunning, 60, -1, true},
|
||||
{"pending", "short", 1, "pending", 60, -1, true},
|
||||
{"retry", "short", 1, "retry", 60, -1, true},
|
||||
{"failed-retryable", "short", 1, types.SyncLogStatusFailed, 60, 60, true},
|
||||
{"long-retained", "long", 2, types.SyncLogStatusSuccess, 2, 2, true},
|
||||
{"long-expired", "long", 2, types.SyncLogStatusSuccess, 31, 31, false},
|
||||
{"unrelated-retained", "unrelated", 3, types.SyncLogStatusSuccess, 60, 60, true},
|
||||
{"unset-expired", "unset", 1, types.SyncLogStatusSuccess, 31, 31, false},
|
||||
{"negative-retained", "negative", 1, types.SyncLogStatusSuccess, 2, 2, true},
|
||||
{"negative-expired", "negative", 1, types.SyncLogStatusSuccess, 31, 31, false},
|
||||
{"deleted-policy-retained", "deleted-long", 2, types.SyncLogStatusSuccess, 60, 60, true},
|
||||
{"deleted-policy-expired", "deleted-short", 2, types.SyncLogStatusFailed, 2, 2, false},
|
||||
{"orphan-retained", "missing", 1, types.SyncLogStatusSuccess, 2, 2, true},
|
||||
{"orphan-expired", "missing", 1, types.SyncLogStatusFailed, 31, 31, false},
|
||||
{"tenant-mismatch-retained", "short", 9, types.SyncLogStatusSuccess, 60, 60, true},
|
||||
{"large-policy-retained", "large", 1, types.SyncLogStatusSuccess, 60, 60, true},
|
||||
} {
|
||||
var finishedAt *time.Time
|
||||
if log.finishedAge >= 0 {
|
||||
finished := now.AddDate(0, 0, -log.finishedAge)
|
||||
finishedAt = &finished
|
||||
}
|
||||
require.NoError(t, db.Exec("INSERT INTO sync_logs VALUES (?, ?, ?, ?, ?, ?)",
|
||||
log.id, log.source, log.tenant, log.status, now.AddDate(0, 0, -log.ageDays), finishedAt).Error)
|
||||
if log.keep {
|
||||
want = append(want, log.id)
|
||||
}
|
||||
}
|
||||
repo := NewSyncLogRepository(db)
|
||||
for _, defaultDays := range []int{30, 0} {
|
||||
require.NoError(t, repo.CleanupOldLogs(context.Background(), defaultDays))
|
||||
var got []string
|
||||
require.NoError(t, db.Table("sync_logs").Pluck("id", &got).Error)
|
||||
require.ElementsMatch(t, want, got, "cleanup must be isolated and idempotent")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type embedChannelRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewEmbedChannelRepository(db *gorm.DB) interfaces.EmbedChannelRepository {
|
||||
return &embedChannelRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *embedChannelRepository) Create(ctx context.Context, ch *types.EmbedChannel) error {
|
||||
return r.db.WithContext(ctx).Create(ch).Error
|
||||
}
|
||||
|
||||
func (r *embedChannelRepository) GetByID(ctx context.Context, id string) (*types.EmbedChannel, error) {
|
||||
var ch types.EmbedChannel
|
||||
err := r.db.WithContext(ctx).Where("id = ?", id).First(&ch).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &ch, nil
|
||||
}
|
||||
|
||||
func (r *embedChannelRepository) GetByPublishToken(ctx context.Context, token string) (*types.EmbedChannel, error) {
|
||||
var ch types.EmbedChannel
|
||||
err := r.db.WithContext(ctx).Where("publish_token = ?", token).First(&ch).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &ch, nil
|
||||
}
|
||||
|
||||
func (r *embedChannelRepository) ListByAgent(
|
||||
ctx context.Context, tenantID uint64, agentID string,
|
||||
) ([]*types.EmbedChannel, error) {
|
||||
var rows []*types.EmbedChannel
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND agent_id = ?", tenantID, agentID).
|
||||
Order("created_at DESC").
|
||||
Find(&rows).Error
|
||||
return rows, err
|
||||
}
|
||||
|
||||
func (r *embedChannelRepository) ListByTenant(
|
||||
ctx context.Context, tenantID uint64,
|
||||
) ([]*types.EmbedChannel, error) {
|
||||
var rows []*types.EmbedChannel
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ?", tenantID).
|
||||
Order("created_at DESC").
|
||||
Find(&rows).Error
|
||||
return rows, err
|
||||
}
|
||||
|
||||
func (r *embedChannelRepository) Update(ctx context.Context, ch *types.EmbedChannel) error {
|
||||
return r.db.WithContext(ctx).Save(ch).Error
|
||||
}
|
||||
|
||||
func (r *embedChannelRepository) Delete(ctx context.Context, tenantID uint64, id string) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND id = ?", tenantID, id).
|
||||
Delete(&types.EmbedChannel{}).Error
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type graphSearchEvidenceRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewGraphSearchEvidenceRepository constructs the scoped live-source projection.
|
||||
func NewGraphSearchEvidenceRepository(db *gorm.DB) interfaces.GraphSearchEvidenceRepository {
|
||||
return &graphSearchEvidenceRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *graphSearchEvidenceRepository) GetGraphSourceChunks(
|
||||
ctx context.Context, tenantID uint64, kbID string, ids []string,
|
||||
) ([]types.GraphSearchSourceChunk, error) {
|
||||
if tenantID == 0 || kbID == "" || len(ids) > types.GraphSearchMaxEvidence {
|
||||
return nil, fmt.Errorf("invalid graph evidence scope or budget")
|
||||
}
|
||||
rows := []types.GraphSearchSourceChunk{}
|
||||
if len(ids) == 0 {
|
||||
return rows, nil
|
||||
}
|
||||
// Explicit soft-delete predicates are necessary: Table/Joins do not apply
|
||||
// the two models' GORM default scopes. SUBSTR is supported by every SQL
|
||||
// backend; fetching one extra character detects clipping without loading
|
||||
// unbounded content or doing a second, racy metadata-to-content lookup.
|
||||
err := r.db.WithContext(ctx).Table("chunks AS c").
|
||||
Select(`c.id, c.tenant_id, c.knowledge_base_id, c.knowledge_id,
|
||||
c.chunk_index, c.start_at, c.end_at,
|
||||
SUBSTR(c.content, 1, ?) AS content, SUBSTR(k.title, 1, 513) AS title`,
|
||||
types.GraphSearchMaxContentRunes+1).
|
||||
Joins(`JOIN knowledges AS k ON k.id = c.knowledge_id
|
||||
AND k.tenant_id = c.tenant_id AND k.knowledge_base_id = c.knowledge_base_id`).
|
||||
Where("c.tenant_id = ? AND c.knowledge_base_id = ? AND c.id IN ?", tenantID, kbID, ids).
|
||||
Where("c.deleted_at IS NULL AND k.deleted_at IS NULL AND c.is_enabled = ?", true).
|
||||
Where("k.enable_status = ? AND k.parse_status <> ?", "enabled", types.ParseStatusDeleting).
|
||||
Where("(c.index_status = ? OR c.index_status = ?)", "ready", "").
|
||||
Order("c.id").Scan(&rows).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := range rows {
|
||||
rows[i].Content, rows[i].ContentTruncated = graphSearchClip(rows[i].Content, types.GraphSearchMaxContentRunes)
|
||||
rows[i].Title, rows[i].TitleTruncated = graphSearchClip(rows[i].Title, 512)
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
func graphSearchClip(text string, limit int) (string, bool) {
|
||||
runes := []rune(text) // SQL has already bounded this allocation.
|
||||
if len(runes) > limit {
|
||||
return string(runes[:limit]), true
|
||||
}
|
||||
return text, false
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestGraphSearchLiveEvidenceSQL(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
sqlDB, err := db.DB()
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { require.NoError(t, sqlDB.Close()) })
|
||||
require.NoError(t, db.AutoMigrate(&types.Knowledge{}, &types.Chunk{}))
|
||||
for _, name := range []string{
|
||||
"live", "chunk-deleted", "doc-deleted", "chunk-disabled", "doc-disabled",
|
||||
"deleting", "wrong-tenant", "wrong-kb", "wrong-parent", "indexing", "long",
|
||||
} {
|
||||
doc := &types.Knowledge{
|
||||
ID: name, TenantID: 7, KnowledgeBaseID: "kb",
|
||||
EnableStatus: "enabled", ParseStatus: types.ParseStatusCompleted, Title: "标题",
|
||||
}
|
||||
chunk := &types.Chunk{
|
||||
ID: name, TenantID: 7, KnowledgeBaseID: "kb", KnowledgeID: name,
|
||||
Content: "内容", IsEnabled: true, IndexStatus: "ready",
|
||||
}
|
||||
switch name {
|
||||
case "chunk-deleted":
|
||||
chunk.DeletedAt = gorm.DeletedAt{Time: time.Now(), Valid: true}
|
||||
case "doc-deleted":
|
||||
doc.DeletedAt = gorm.DeletedAt{Time: time.Now(), Valid: true}
|
||||
case "chunk-disabled":
|
||||
// GORM's default:true would rewrite false at insert; disable below.
|
||||
case "doc-disabled":
|
||||
doc.EnableStatus = "disabled"
|
||||
case "deleting":
|
||||
doc.ParseStatus = types.ParseStatusDeleting
|
||||
case "wrong-tenant":
|
||||
chunk.TenantID, doc.TenantID = 8, 8
|
||||
case "wrong-kb":
|
||||
chunk.KnowledgeBaseID, doc.KnowledgeBaseID = "other", "other"
|
||||
case "wrong-parent":
|
||||
doc.KnowledgeBaseID = "other"
|
||||
case "indexing":
|
||||
chunk.IndexStatus = "processing"
|
||||
case "long":
|
||||
chunk.Content = strings.Repeat("中", 2100)
|
||||
doc.Title = strings.Repeat("题", 600)
|
||||
}
|
||||
require.NoError(t, db.Create(doc).Error)
|
||||
require.NoError(t, db.Create(chunk).Error)
|
||||
}
|
||||
require.NoError(t, db.Model(&types.Chunk{}).Where("id = ?", "chunk-disabled").
|
||||
UpdateColumn("is_enabled", false).Error)
|
||||
repo := NewGraphSearchEvidenceRepository(db)
|
||||
ids := []string{
|
||||
"live", "chunk-deleted", "doc-deleted", "chunk-disabled", "doc-disabled",
|
||||
"deleting", "wrong-tenant", "wrong-kb", "wrong-parent", "indexing", "missing", "long",
|
||||
}
|
||||
rows, err := repo.GetGraphSourceChunks(context.Background(), 7, "kb", ids)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, rows, 2)
|
||||
require.Equal(t, "live", rows[0].ID)
|
||||
require.Equal(t, "内容", rows[0].Content)
|
||||
require.False(t, rows[0].ContentTruncated)
|
||||
require.Equal(t, "long", rows[1].ID)
|
||||
require.Equal(t, 2000, utf8.RuneCountInString(rows[1].Content))
|
||||
require.True(t, utf8.ValidString(rows[1].Content))
|
||||
require.True(t, rows[1].ContentTruncated)
|
||||
require.Equal(t, 512, utf8.RuneCountInString(rows[1].Title))
|
||||
require.True(t, rows[1].TitleTruncated)
|
||||
_, err = repo.GetGraphSourceChunks(context.Background(), 7, "kb", make([]string, 513))
|
||||
require.Error(t, err)
|
||||
_, err = repo.GetGraphSourceChunks(context.Background(), 0, "kb", []string{"live"})
|
||||
require.Error(t, err)
|
||||
require.NoError(t, db.Migrator().DropTable(&types.Chunk{}))
|
||||
rows, err = repo.GetGraphSourceChunks(context.Background(), 7, "kb", []string{"live"})
|
||||
require.Error(t, err)
|
||||
require.Nil(t, rows, "database failure is not an empty successful search")
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrKBShareNotFound = errors.New("knowledge base share not found")
|
||||
ErrKBShareAlreadyExists = errors.New("knowledge base already shared to this organization")
|
||||
)
|
||||
|
||||
// kbShareRepository implements KBShareRepository interface
|
||||
type kbShareRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewKBShareRepository creates a new knowledge base share repository
|
||||
func NewKBShareRepository(db *gorm.DB) interfaces.KBShareRepository {
|
||||
return &kbShareRepository{db: db}
|
||||
}
|
||||
|
||||
// Create creates a new share record
|
||||
func (r *kbShareRepository) Create(ctx context.Context, share *types.KnowledgeBaseShare) error {
|
||||
// Check if share already exists
|
||||
var count int64
|
||||
r.db.WithContext(ctx).Model(&types.KnowledgeBaseShare{}).
|
||||
Where("knowledge_base_id = ? AND organization_id = ? AND deleted_at IS NULL", share.KnowledgeBaseID, share.OrganizationID).
|
||||
Count(&count)
|
||||
|
||||
if count > 0 {
|
||||
return ErrKBShareAlreadyExists
|
||||
}
|
||||
|
||||
return r.db.WithContext(ctx).Create(share).Error
|
||||
}
|
||||
|
||||
// GetByID gets a share record by ID
|
||||
func (r *kbShareRepository) GetByID(ctx context.Context, id string) (*types.KnowledgeBaseShare, error) {
|
||||
var share types.KnowledgeBaseShare
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("id = ?", id).
|
||||
First(&share).Error
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrKBShareNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &share, nil
|
||||
}
|
||||
|
||||
// GetByKBAndOrg gets a share record by knowledge base ID and organization ID
|
||||
func (r *kbShareRepository) GetByKBAndOrg(ctx context.Context, kbID string, orgID string) (*types.KnowledgeBaseShare, error) {
|
||||
var share types.KnowledgeBaseShare
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("knowledge_base_id = ? AND organization_id = ?", kbID, orgID).
|
||||
First(&share).Error
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrKBShareNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &share, nil
|
||||
}
|
||||
|
||||
// Update updates a share record
|
||||
func (r *kbShareRepository) Update(ctx context.Context, share *types.KnowledgeBaseShare) error {
|
||||
return r.db.WithContext(ctx).Model(&types.KnowledgeBaseShare{}).
|
||||
Where("id = ?", share.ID).
|
||||
Updates(share).Error
|
||||
}
|
||||
|
||||
// Delete soft deletes a share record
|
||||
func (r *kbShareRepository) Delete(ctx context.Context, id string) error {
|
||||
return r.db.WithContext(ctx).Where("id = ?", id).Delete(&types.KnowledgeBaseShare{}).Error
|
||||
}
|
||||
|
||||
// DeleteByKnowledgeBaseID soft deletes all share records for a knowledge base (e.g. when the KB is deleted)
|
||||
func (r *kbShareRepository) DeleteByKnowledgeBaseID(ctx context.Context, kbID string) error {
|
||||
return r.db.WithContext(ctx).Where("knowledge_base_id = ?", kbID).Delete(&types.KnowledgeBaseShare{}).Error
|
||||
}
|
||||
|
||||
// DeleteByOrganizationID soft deletes all share records for an organization (e.g. when the org is deleted)
|
||||
func (r *kbShareRepository) DeleteByOrganizationID(ctx context.Context, orgID string) error {
|
||||
return r.db.WithContext(ctx).Where("organization_id = ?", orgID).Delete(&types.KnowledgeBaseShare{}).Error
|
||||
}
|
||||
|
||||
// DeleteByOrganizationAndSourceTenant soft deletes the shares a tenant made
|
||||
// into an organization (e.g. when the tenant leaves or is removed from it).
|
||||
func (r *kbShareRepository) DeleteByOrganizationAndSourceTenant(
|
||||
ctx context.Context, orgID string, sourceTenantID uint64,
|
||||
) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Where("organization_id = ? AND source_tenant_id = ?", orgID, sourceTenantID).
|
||||
Delete(&types.KnowledgeBaseShare{}).Error
|
||||
}
|
||||
|
||||
// kbShareSourceMemberJoin keeps a share effective only while its source tenant
|
||||
// is still a member of the organization. Leaving or removal deletes the
|
||||
// tenant's shares; the join also covers rows left behind by older versions.
|
||||
const kbShareSourceMemberJoin = "JOIN organization_tenant_members src_member " +
|
||||
"ON src_member.organization_id = kb_shares.organization_id " +
|
||||
"AND src_member.tenant_id = kb_shares.source_tenant_id"
|
||||
|
||||
// ListByKnowledgeBase lists all share records for a knowledge base
|
||||
func (r *kbShareRepository) ListByKnowledgeBase(ctx context.Context, kbID string) ([]*types.KnowledgeBaseShare, error) {
|
||||
var shares []*types.KnowledgeBaseShare
|
||||
err := r.db.WithContext(ctx).
|
||||
Preload("Organization").
|
||||
Where("knowledge_base_id = ?", kbID).
|
||||
Order("created_at DESC").
|
||||
Find(&shares).Error
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return shares, nil
|
||||
}
|
||||
|
||||
// ListByOrganization lists all share records for an organization.
|
||||
// Excludes shares whose knowledge base has been soft-deleted.
|
||||
func (r *kbShareRepository) ListByOrganization(ctx context.Context, orgID string) ([]*types.KnowledgeBaseShare, error) {
|
||||
var shares []*types.KnowledgeBaseShare
|
||||
err := r.db.WithContext(ctx).
|
||||
Joins("JOIN knowledge_bases ON knowledge_bases.id = kb_shares.knowledge_base_id AND knowledge_bases.deleted_at IS NULL").
|
||||
Joins(kbShareSourceMemberJoin).
|
||||
Preload("KnowledgeBase").
|
||||
Preload("Organization").
|
||||
Where("kb_shares.organization_id = ? AND kb_shares.deleted_at IS NULL", orgID).
|
||||
Order("kb_shares.created_at DESC").
|
||||
Find(&shares).Error
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return shares, nil
|
||||
}
|
||||
|
||||
// ListByOrganizations lists all share records for the given organizations (batch).
|
||||
func (r *kbShareRepository) ListByOrganizations(ctx context.Context, orgIDs []string) ([]*types.KnowledgeBaseShare, error) {
|
||||
if len(orgIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var shares []*types.KnowledgeBaseShare
|
||||
err := r.db.WithContext(ctx).
|
||||
Joins("JOIN knowledge_bases ON knowledge_bases.id = kb_shares.knowledge_base_id AND knowledge_bases.deleted_at IS NULL").
|
||||
Joins(kbShareSourceMemberJoin).
|
||||
Preload("KnowledgeBase").
|
||||
Preload("Organization").
|
||||
Where("kb_shares.organization_id IN ? AND kb_shares.deleted_at IS NULL", orgIDs).
|
||||
Order("kb_shares.created_at DESC").
|
||||
Find(&shares).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return shares, nil
|
||||
}
|
||||
|
||||
// ListSharedKBsForTenant lists all knowledge bases shared to organizations that the tenant participates in.
|
||||
// Excludes shares for soft-deleted organizations and soft-deleted knowledge bases.
|
||||
func (r *kbShareRepository) ListSharedKBsForTenant(ctx context.Context, tenantID uint64) ([]*types.KnowledgeBaseShare, error) {
|
||||
var shares []*types.KnowledgeBaseShare
|
||||
|
||||
// Get shares for organizations the tenant is a member of; exclude deleted orgs and deleted KBs.
|
||||
err := r.db.WithContext(ctx).
|
||||
Joins("JOIN knowledge_bases ON knowledge_bases.id = kb_shares.knowledge_base_id AND knowledge_bases.deleted_at IS NULL").
|
||||
Joins(kbShareSourceMemberJoin).
|
||||
Preload("KnowledgeBase").
|
||||
Preload("Organization").
|
||||
Joins("JOIN organization_tenant_members otm ON otm.organization_id = kb_shares.organization_id").
|
||||
Joins("JOIN organizations ON organizations.id = kb_shares.organization_id AND organizations.deleted_at IS NULL").
|
||||
Where("otm.tenant_id = ?", tenantID).
|
||||
Where("kb_shares.deleted_at IS NULL").
|
||||
Order("kb_shares.created_at DESC").
|
||||
Find(&shares).Error
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return shares, nil
|
||||
}
|
||||
|
||||
// CountSharesByKnowledgeBaseID counts the number of organizations a knowledge base is shared with
|
||||
func (r *kbShareRepository) CountSharesByKnowledgeBaseID(ctx context.Context, kbID string) (int64, error) {
|
||||
var count int64
|
||||
err := r.db.WithContext(ctx).Model(&types.KnowledgeBaseShare{}).
|
||||
Where("knowledge_base_id = ? AND deleted_at IS NULL", kbID).
|
||||
Count(&count).Error
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
// CountSharesByKnowledgeBaseIDs counts the number of shares for multiple knowledge bases at once
|
||||
func (r *kbShareRepository) CountSharesByKnowledgeBaseIDs(ctx context.Context, kbIDs []string) (map[string]int64, error) {
|
||||
if len(kbIDs) == 0 {
|
||||
return make(map[string]int64), nil
|
||||
}
|
||||
|
||||
type result struct {
|
||||
KnowledgeBaseID string `gorm:"column:knowledge_base_id"`
|
||||
Count int64 `gorm:"column:count"`
|
||||
}
|
||||
|
||||
var results []result
|
||||
err := r.db.WithContext(ctx).Model(&types.KnowledgeBaseShare{}).
|
||||
Select("knowledge_base_id, COUNT(*) as count").
|
||||
Where("knowledge_base_id IN ? AND deleted_at IS NULL", kbIDs).
|
||||
Group("knowledge_base_id").
|
||||
Find(&results).Error
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
countMap := make(map[string]int64)
|
||||
for _, r := range results {
|
||||
countMap[r.KnowledgeBaseID] = r.Count
|
||||
}
|
||||
return countMap, nil
|
||||
}
|
||||
|
||||
// CountByOrganizations returns share counts per organization (only orgs in orgIDs). Excludes deleted KBs.
|
||||
func (r *kbShareRepository) CountByOrganizations(ctx context.Context, orgIDs []string) (map[string]int64, error) {
|
||||
if len(orgIDs) == 0 {
|
||||
return make(map[string]int64), nil
|
||||
}
|
||||
type row struct {
|
||||
OrgID string `gorm:"column:organization_id"`
|
||||
Count int64 `gorm:"column:count"`
|
||||
}
|
||||
var rows []row
|
||||
err := r.db.WithContext(ctx).Model(&types.KnowledgeBaseShare{}).
|
||||
Joins("JOIN knowledge_bases ON knowledge_bases.id = kb_shares.knowledge_base_id AND knowledge_bases.deleted_at IS NULL").
|
||||
Joins(kbShareSourceMemberJoin).
|
||||
Select("kb_shares.organization_id as organization_id, COUNT(*) as count").
|
||||
Where("kb_shares.organization_id IN ? AND kb_shares.deleted_at IS NULL", orgIDs).
|
||||
Group("kb_shares.organization_id").
|
||||
Find(&rows).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make(map[string]int64)
|
||||
for _, o := range orgIDs {
|
||||
out[o] = 0
|
||||
}
|
||||
for _, r := range rows {
|
||||
out[r.OrgID] = r.Count
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,40 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestCreateKnowledgeDefaultsCustomMetadataToEmptyObject(t *testing.T) {
|
||||
dsn := "file:" + uuid.New().String() + "?mode=memory&cache=shared"
|
||||
db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
sqlDB, err := db.DB()
|
||||
require.NoError(t, err)
|
||||
sqlDB.SetMaxOpenConns(1)
|
||||
t.Cleanup(func() { _ = sqlDB.Close() })
|
||||
require.NoError(t, db.AutoMigrate(&types.Knowledge{}))
|
||||
|
||||
repo := NewKnowledgeRepository(db)
|
||||
knowledge := &types.Knowledge{
|
||||
TenantID: 1,
|
||||
KnowledgeBaseID: "kb-1",
|
||||
Type: "file",
|
||||
Title: "document.txt",
|
||||
ParseStatus: types.ParseStatusPending,
|
||||
EnableStatus: "disabled",
|
||||
}
|
||||
|
||||
require.NoError(t, repo.CreateKnowledge(context.Background(), knowledge))
|
||||
require.JSONEq(t, `{}`, string(knowledge.CustomMetadata))
|
||||
|
||||
persisted, err := repo.GetKnowledgeByID(context.Background(), knowledge.TenantID, knowledge.ID)
|
||||
require.NoError(t, err)
|
||||
require.JSONEq(t, `{}`, string(persisted.CustomMetadata))
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestFindByDataSourceExternalID(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
|
||||
ctx := context.Background()
|
||||
|
||||
const tenantID uint64 = 50
|
||||
kbID := uuid.New().String()
|
||||
dsA := uuid.New().String()
|
||||
dsB := uuid.New().String()
|
||||
|
||||
insertRow := func(dsID, extID string) string {
|
||||
id := uuid.New().String()
|
||||
metadata := fmt.Sprintf(`{"datasource_id":%q,"external_id":%q}`, dsID, extID)
|
||||
require.NoError(t, db.Exec(`
|
||||
INSERT INTO knowledges
|
||||
(id, tenant_id, knowledge_base_id, type, title, source, parse_status, metadata)
|
||||
VALUES (?, ?, ?, 'document', ?, 'feishu', 'completed', ?)
|
||||
`, id, tenantID, kbID, extID, metadata).Error)
|
||||
return id
|
||||
}
|
||||
|
||||
idA := insertRow(dsA, "file:shared")
|
||||
_ = insertRow(dsB, "file:shared")
|
||||
|
||||
found, err := repo.FindByDataSourceExternalID(ctx, tenantID, kbID, dsA, "file:shared")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, found)
|
||||
assert.Equal(t, idA, found.ID)
|
||||
}
|
||||
|
||||
func TestFindByDataSourceExternalID_DeletedRowsExcluded(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
|
||||
ctx := context.Background()
|
||||
|
||||
const tenantID uint64 = 51
|
||||
kbID := uuid.New().String()
|
||||
dsID := uuid.New().String()
|
||||
|
||||
id := uuid.New().String()
|
||||
metadata := fmt.Sprintf(`{"datasource_id":%q,"external_id":%q}`, dsID, "file:gone")
|
||||
require.NoError(t, db.Exec(`
|
||||
INSERT INTO knowledges
|
||||
(id, tenant_id, knowledge_base_id, type, title, source, parse_status, metadata, deleted_at)
|
||||
VALUES (?, ?, ?, 'document', 'gone', 'feishu', 'completed', ?, '2026-01-01 00:00:00')
|
||||
`, id, tenantID, kbID, metadata).Error)
|
||||
|
||||
found, err := repo.FindByDataSourceExternalID(ctx, tenantID, kbID, dsID, "file:gone")
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, found)
|
||||
}
|
||||
|
||||
func TestHardDeleteKnowledge(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
|
||||
ctx := context.Background()
|
||||
|
||||
const tenantID uint64 = 52
|
||||
kbID := uuid.New().String()
|
||||
id := uuid.New().String()
|
||||
metadata := `{"datasource_id":"ds-1","external_id":"file:1"}`
|
||||
require.NoError(t, db.Exec(`
|
||||
INSERT INTO knowledges
|
||||
(id, tenant_id, knowledge_base_id, type, title, source, parse_status, metadata, deleted_at)
|
||||
VALUES (?, ?, ?, 'document', 'file:1', 'feishu', 'completed', ?, '2026-01-01 00:00:00')
|
||||
`, id, tenantID, kbID, metadata).Error)
|
||||
|
||||
require.NoError(t, repo.HardDeleteKnowledge(ctx, tenantID, id))
|
||||
|
||||
var count int64
|
||||
require.NoError(t, db.Unscoped().Model(&struct{}{}).Table("knowledges").Where("id = ?", id).Count(&count).Error)
|
||||
assert.Equal(t, int64(0), count)
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestCheckKnowledgeExists_FileHashIsScopedByFileType(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db)
|
||||
ctx := context.Background()
|
||||
tenantID := uint64(1)
|
||||
kbID := uuid.NewString()
|
||||
const fileHash = "same-content-hash"
|
||||
|
||||
require.NoError(t, db.Exec(`
|
||||
INSERT INTO knowledges (id, tenant_id, knowledge_base_id, type, title, file_name, file_type, file_hash, parse_status)
|
||||
VALUES (?, ?, ?, 'file', 'document.md', 'document.md', 'md', ?, 'completed')
|
||||
`, uuid.NewString(), tenantID, kbID, fileHash).Error)
|
||||
|
||||
t.Run("same content with another file type is allowed", func(t *testing.T) {
|
||||
exists, knowledge, err := repo.CheckKnowledgeExists(ctx, tenantID, kbID, &types.KnowledgeCheckParams{
|
||||
Type: "file",
|
||||
FileHash: fileHash,
|
||||
FileType: "txt",
|
||||
})
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.False(t, exists)
|
||||
assert.Nil(t, knowledge)
|
||||
})
|
||||
|
||||
t.Run("same content and file type remains a duplicate", func(t *testing.T) {
|
||||
exists, knowledge, err := repo.CheckKnowledgeExists(ctx, tenantID, kbID, &types.KnowledgeCheckParams{
|
||||
Type: "file",
|
||||
FileHash: fileHash,
|
||||
FileType: "md",
|
||||
})
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.True(t, exists)
|
||||
require.NotNil(t, knowledge)
|
||||
assert.Equal(t, "md", knowledge.FileType)
|
||||
})
|
||||
|
||||
t.Run("file type matching is case-insensitive", func(t *testing.T) {
|
||||
exists, knowledge, err := repo.CheckKnowledgeExists(ctx, tenantID, kbID, &types.KnowledgeCheckParams{
|
||||
Type: "file",
|
||||
FileHash: fileHash,
|
||||
FileType: "MD",
|
||||
})
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.True(t, exists)
|
||||
require.NotNil(t, knowledge)
|
||||
assert.Equal(t, "md", knowledge.FileType)
|
||||
})
|
||||
}
|
||||
|
||||
func TestCheckKnowledgeExists_FileSourceIdentity(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db)
|
||||
const metadata = `{"datasource_id":"ds-1","external_id":"gitlab:1:main:README.md"}`
|
||||
require.NoError(t, db.Exec(`
|
||||
INSERT INTO knowledges (
|
||||
id, tenant_id, knowledge_base_id, type, file_name, file_type, file_size, file_hash, parse_status, metadata
|
||||
)
|
||||
VALUES (?, 1, 'kb-1', 'file', 'README.md', 'md', 10, 'same-hash', 'completed', ?)
|
||||
`, uuid.NewString(), metadata).Error)
|
||||
for _, tc := range []struct {
|
||||
name, source, externalID, hash, fileType string
|
||||
want bool
|
||||
}{
|
||||
{"same source item", "ds-1", "gitlab:1:main:README.md", "same-hash", "md", true},
|
||||
{"nested path", "ds-1", "gitlab:1:main:a/b/c/README.md", "same-hash", "md", false},
|
||||
{"another branch", "ds-1", "gitlab:1:release:README.md", "same-hash", "md", false},
|
||||
{"another source", "ds-2", "gitlab:1:main:README.md", "same-hash", "md", false},
|
||||
{"updated content", "ds-1", "gitlab:1:main:README.md", "new-hash", "md", false},
|
||||
{"another format", "ds-1", "gitlab:1:main:README.md", "same-hash", "txt", false},
|
||||
{"case insensitive format", "ds-1", "gitlab:1:main:README.md", "same-hash", "MD", true},
|
||||
{"unscoped upload", "", "", "same-hash", "md", true},
|
||||
{"missing source", "", "new-path", "same-hash", "md", true},
|
||||
{"missing external ID", "ds-2", "", "same-hash", "md", true},
|
||||
{"filename fallback same item", "ds-1", "gitlab:1:main:README.md", "", "md", true},
|
||||
{"filename fallback nested item", "ds-1", "gitlab:1:main:a/b/c/README.md", "", "md", false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
exists, _, err := repo.CheckKnowledgeExists(context.Background(), 1, "kb-1", &types.KnowledgeCheckParams{
|
||||
Type: "file", FileName: "README.md", FileSize: 10, FileHash: tc.hash, FileType: tc.fileType,
|
||||
DataSourceID: tc.source, ExternalID: tc.externalID,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tc.want, exists)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckKnowledgeExists_ParseStatusMatrix(t *testing.T) {
|
||||
// Pins the duplicate-check status policy (issue #3338): failed and
|
||||
// deleting rows must not block an upload — a deleting row is on its way
|
||||
// out regardless of how the async delete task concludes — while pending,
|
||||
// processing and completed rows remain real duplicates.
|
||||
for _, tc := range []struct {
|
||||
parseStatus string
|
||||
want bool
|
||||
}{
|
||||
{"failed", false},
|
||||
{"deleting", false},
|
||||
{"pending", true},
|
||||
{"processing", true},
|
||||
{"completed", true},
|
||||
} {
|
||||
t.Run("parse_status="+tc.parseStatus, func(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db)
|
||||
require.NoError(t, db.Exec(`
|
||||
INSERT INTO knowledges (id, tenant_id, knowledge_base_id, type, file_name, file_type, file_size, file_hash, parse_status)
|
||||
VALUES (?, 1, 'kb-1', 'file', 'doc.md', 'md', 10, 'hash-1', ?)
|
||||
`, uuid.NewString(), tc.parseStatus).Error)
|
||||
|
||||
exists, _, err := repo.CheckKnowledgeExists(context.Background(), 1, "kb-1", &types.KnowledgeCheckParams{
|
||||
Type: "file", FileHash: "hash-1", FileType: "md",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tc.want, exists)
|
||||
|
||||
// The filename/size fallback path shares the same base filter.
|
||||
exists, _, err = repo.CheckKnowledgeExists(context.Background(), 1, "kb-1", &types.KnowledgeCheckParams{
|
||||
Type: "file", FileName: "doc.md", FileSize: 10,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tc.want, exists)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestCountKnowledgeByKnowledgeBaseID_ExcludesDeleting pins the count/list
|
||||
// alignment (issues #3338/#3345): the document list hides rows mid-deletion,
|
||||
// so the KB card count must not include them either — otherwise a stranded
|
||||
// delete shows up as "4 documents, 3 listed".
|
||||
func TestCountKnowledgeByKnowledgeBaseID_ExcludesDeleting(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db)
|
||||
for _, tc := range []struct{ id, status string }{
|
||||
{"k-done", "completed"},
|
||||
{"k-failed", "failed"},
|
||||
{"k-deleting", "deleting"},
|
||||
} {
|
||||
require.NoError(t, db.Exec(`
|
||||
INSERT INTO knowledges (id, tenant_id, knowledge_base_id, type, file_name, parse_status)
|
||||
VALUES (?, 1, 'kb-cnt', 'file', ?, ?)
|
||||
`, tc.id, tc.id+".md", tc.status).Error)
|
||||
}
|
||||
|
||||
count, err := repo.CountKnowledgeByKnowledgeBaseID(context.Background(), 1, "kb-cnt")
|
||||
require.NoError(t, err)
|
||||
// failed rows stay counted (they are visible, actionable cards); only
|
||||
// the hidden mid-deletion row drops out.
|
||||
require.Equal(t, int64(2), count)
|
||||
}
|
||||
@@ -0,0 +1,523 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"unicode/utf8"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// knowledgesTestDDL mirrors the columns of `knowledges` that
|
||||
// SetFinalizing / FinalizeSubtask / UpdateKnowledge actually read or write.
|
||||
// We inline the DDL (instead of AutoMigrate) so the schema is explicit,
|
||||
// and we include pending_subtasks_count from migration 000056 plus the
|
||||
// processing/finalizing/completed columns the helpers care about.
|
||||
const knowledgesTestDDL = `
|
||||
CREATE TABLE IF NOT EXISTS knowledges (
|
||||
profile TEXT,
|
||||
id VARCHAR(36) PRIMARY KEY,
|
||||
tenant_id INTEGER NOT NULL,
|
||||
knowledge_base_id VARCHAR(36) NOT NULL,
|
||||
type VARCHAR(50) NOT NULL DEFAULT '',
|
||||
title VARCHAR(255) NOT NULL DEFAULT '',
|
||||
description TEXT,
|
||||
source VARCHAR(2048) NOT NULL DEFAULT '',
|
||||
parse_status VARCHAR(50) NOT NULL DEFAULT 'unprocessed',
|
||||
enable_status VARCHAR(50) NOT NULL DEFAULT 'enabled',
|
||||
embedding_model_id VARCHAR(64),
|
||||
file_name VARCHAR(255),
|
||||
folder_path VARCHAR(1024) NOT NULL DEFAULT '',
|
||||
file_type VARCHAR(50),
|
||||
file_size BIGINT,
|
||||
file_path TEXT,
|
||||
file_hash VARCHAR(64),
|
||||
storage_size BIGINT NOT NULL DEFAULT 0,
|
||||
metadata TEXT,
|
||||
tag_id VARCHAR(36),
|
||||
summary_status VARCHAR(32) DEFAULT 'none',
|
||||
last_faq_import_result TEXT DEFAULT NULL,
|
||||
channel VARCHAR(50) NOT NULL DEFAULT 'web',
|
||||
pending_subtasks_count INT NOT NULL DEFAULT 0,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
processed_at DATETIME,
|
||||
error_message TEXT,
|
||||
deleted_at DATETIME
|
||||
);
|
||||
`
|
||||
|
||||
// setupKnowledgeTestDB returns an in-memory SQLite db with the knowledges
|
||||
// table. SQLite has a single-writer constraint, so we cap MaxOpenConns at 1
|
||||
// and set a busy timeout: concurrent goroutines line up on the same
|
||||
// connection (just like production write workloads serialize at the row
|
||||
// level). This is enough to exercise the atomic semantics of the helpers
|
||||
// without flaking on "database table is locked".
|
||||
func setupKnowledgeTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
dsn := "file:" + uuid.New().String() + "?mode=memory&cache=shared&_busy_timeout=5000"
|
||||
db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
sqlDB, err := db.DB()
|
||||
require.NoError(t, err)
|
||||
sqlDB.SetMaxOpenConns(1)
|
||||
require.NoError(t, db.Exec(knowledgesTestDDL).Error)
|
||||
t.Cleanup(func() { _ = sqlDB.Close() })
|
||||
return db
|
||||
}
|
||||
|
||||
// insertProcessingKnowledge seeds a row in `processing` state ready for a
|
||||
// SetFinalizing transition.
|
||||
func insertProcessingKnowledge(t *testing.T, db *gorm.DB) string {
|
||||
t.Helper()
|
||||
id := uuid.New().String()
|
||||
require.NoError(t, db.Exec(`
|
||||
INSERT INTO knowledges (id, tenant_id, knowledge_base_id, type, title, source, parse_status, pending_subtasks_count)
|
||||
VALUES (?, 1, ?, 'document', 'finalize-test', 'manual', 'processing', 0)
|
||||
`, id, uuid.New().String()).Error)
|
||||
return id
|
||||
}
|
||||
|
||||
// reloadKnowledgeRow returns the parse_status and pending_subtasks_count of
|
||||
// a row directly via raw SQL — bypasses any GORM hook noise.
|
||||
func reloadKnowledgeRow(t *testing.T, db *gorm.DB, id string) (status string, count int) {
|
||||
t.Helper()
|
||||
row := db.Raw(`SELECT parse_status, pending_subtasks_count FROM knowledges WHERE id = ?`, id).Row()
|
||||
require.NoError(t, row.Scan(&status, &count))
|
||||
return status, count
|
||||
}
|
||||
|
||||
func reloadKnowledgeErrorMessage(t *testing.T, db *gorm.DB, id string) string {
|
||||
t.Helper()
|
||||
var msg string
|
||||
require.NoError(t, db.Raw(`SELECT COALESCE(error_message, '') FROM knowledges WHERE id = ?`, id).Scan(&msg).Error)
|
||||
return msg
|
||||
}
|
||||
|
||||
func TestKnowledgeRepository_UpdateKnowledgeColumnsSanitizesErrorMessage(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db)
|
||||
id := insertProcessingKnowledge(t, db)
|
||||
invalid := "parse failed " + string([]byte{0xef, 0xbc, 0x2e})
|
||||
|
||||
require.NoError(t, repo.UpdateKnowledgeColumns(context.Background(), id, map[string]interface{}{
|
||||
"error_message": invalid,
|
||||
}))
|
||||
|
||||
got := reloadKnowledgeErrorMessage(t, db, id)
|
||||
if !utf8.ValidString(got) {
|
||||
t.Fatalf("persisted error_message is invalid UTF-8: % x", []byte(got))
|
||||
}
|
||||
assert.Equal(t, "parse failed .", got)
|
||||
}
|
||||
|
||||
func insertKnowledgeWithStatus(t *testing.T, db *gorm.DB, status string, deleted bool) string {
|
||||
t.Helper()
|
||||
id := uuid.New().String()
|
||||
deletedAt := interface{}(nil)
|
||||
if deleted {
|
||||
deletedAt = "2026-06-16 12:00:00"
|
||||
}
|
||||
require.NoError(t, db.Exec(`
|
||||
INSERT INTO knowledges (id, tenant_id, knowledge_base_id, type, title, source, parse_status, deleted_at)
|
||||
VALUES (?, 1, ?, 'document', 'delete-test', 'manual', ?, ?)
|
||||
`, id, uuid.New().String(), status, deletedAt).Error)
|
||||
return id
|
||||
}
|
||||
|
||||
// TestFinalizeSubtask_Concurrent_ExactlyOnePromote spawns N goroutines that
|
||||
// each call FinalizeSubtask after SetFinalizing(N), and asserts:
|
||||
// - the counter ends at zero,
|
||||
// - parse_status is "completed",
|
||||
// - exactly one caller observed promoted=true.
|
||||
//
|
||||
// This is the behavior the original "stuck pending_subtasks_count" bug
|
||||
// violated: clobbered counters meant some callers saw a non-zero value
|
||||
// after the true count had reached zero, and none of them promoted.
|
||||
func TestFinalizeSubtask_Concurrent_ExactlyOnePromote(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
|
||||
ctx := context.Background()
|
||||
|
||||
const n = 20
|
||||
id := insertProcessingKnowledge(t, db)
|
||||
|
||||
transitioned, err := repo.SetFinalizing(ctx, id, n)
|
||||
require.NoError(t, err)
|
||||
require.True(t, transitioned, "SetFinalizing should transition processing -> finalizing")
|
||||
|
||||
var promoteWins atomic.Int32
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < n; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
_, promoted, ferr := repo.FinalizeSubtask(ctx, id)
|
||||
if ferr != nil {
|
||||
t.Errorf("FinalizeSubtask: %v", ferr)
|
||||
return
|
||||
}
|
||||
if promoted {
|
||||
promoteWins.Add(1)
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
assert.Equal(t, int32(1), promoteWins.Load(),
|
||||
"exactly one caller must observe promoted=true even under concurrent decrements")
|
||||
|
||||
status, count := reloadKnowledgeRow(t, db, id)
|
||||
assert.Equal(t, types.ParseStatusCompleted, status)
|
||||
assert.Equal(t, 0, count)
|
||||
}
|
||||
|
||||
// TestFinalizeSubtask_PartialDecrement_StaysFinalizing verifies the row
|
||||
// remains in "finalizing" with the expected residual count when fewer
|
||||
// callers decrement than were seeded — the promote guard must not fire
|
||||
// early.
|
||||
func TestFinalizeSubtask_PartialDecrement_StaysFinalizing(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
|
||||
ctx := context.Background()
|
||||
|
||||
id := insertProcessingKnowledge(t, db)
|
||||
_, err := repo.SetFinalizing(ctx, id, 3)
|
||||
require.NoError(t, err)
|
||||
|
||||
for i := 0; i < 2; i++ {
|
||||
_, promoted, ferr := repo.FinalizeSubtask(ctx, id)
|
||||
require.NoError(t, ferr)
|
||||
assert.False(t, promoted, "promote must not fire while count > 0")
|
||||
}
|
||||
|
||||
status, count := reloadKnowledgeRow(t, db, id)
|
||||
assert.Equal(t, types.ParseStatusFinalizing, status)
|
||||
assert.Equal(t, 1, count)
|
||||
}
|
||||
|
||||
// TestFinalizeSubtask_DecrementClampedAtZero verifies the safety-net
|
||||
// clamp on the decrement: extra calls past the seeded count must not
|
||||
// underflow pending_subtasks_count below zero. (Reconciliation's
|
||||
// shortfall-release loop relies on this.)
|
||||
func TestFinalizeSubtask_DecrementClampedAtZero(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
|
||||
ctx := context.Background()
|
||||
|
||||
id := insertProcessingKnowledge(t, db)
|
||||
_, err := repo.SetFinalizing(ctx, id, 1)
|
||||
require.NoError(t, err)
|
||||
|
||||
// First decrement drains the only slot and promotes.
|
||||
_, promoted, err := repo.FinalizeSubtask(ctx, id)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, promoted)
|
||||
|
||||
// Subsequent decrements must be no-ops, not underflow.
|
||||
for i := 0; i < 3; i++ {
|
||||
_, promoted, err := repo.FinalizeSubtask(ctx, id)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, promoted)
|
||||
}
|
||||
|
||||
status, count := reloadKnowledgeRow(t, db, id)
|
||||
assert.Equal(t, types.ParseStatusCompleted, status)
|
||||
assert.Equal(t, 0, count, "pending_subtasks_count must be clamped at zero")
|
||||
}
|
||||
|
||||
// A row no longer in finalizing (cancelled, failed by housekeeping) only has
|
||||
// its counter decremented: reaching zero must not promote it to completed.
|
||||
func TestFinalizeSubtask_NonFinalizingRowOnlyDecrements(t *testing.T) {
|
||||
for _, status := range []string{types.ParseStatusCancelled, types.ParseStatusFailed, types.ParseStatusProcessing} {
|
||||
t.Run(status, func(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
|
||||
id := insertKnowledgeWithStatus(t, db, status, false)
|
||||
require.NoError(t, db.Exec(`UPDATE knowledges SET pending_subtasks_count = 1 WHERE id = ?`, id).Error)
|
||||
|
||||
count, promoted, err := repo.FinalizeSubtask(context.Background(), id)
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.False(t, promoted)
|
||||
assert.Zero(t, count)
|
||||
got, n := reloadKnowledgeRow(t, db, id)
|
||||
assert.Equal(t, status, got)
|
||||
assert.Zero(t, n)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Decrement and promote commit together: a promote that failed after its
|
||||
// decrement had committed left the counter at zero with nobody left to
|
||||
// promote the row. A failed promote must roll the decrement back so the
|
||||
// retried release drains the same slot again.
|
||||
func TestFinalizeSubtask_FailedPromoteRollsBackDecrement(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
|
||||
ctx := context.Background()
|
||||
id := insertProcessingKnowledge(t, db)
|
||||
_, err := repo.SetFinalizing(ctx, id, 1)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.Exec(`
|
||||
CREATE TRIGGER refuse_promote BEFORE UPDATE OF parse_status ON knowledges
|
||||
WHEN NEW.parse_status = 'completed'
|
||||
BEGIN SELECT RAISE(ABORT, 'promote refused'); END
|
||||
`).Error)
|
||||
|
||||
_, promoted, err := repo.FinalizeSubtask(ctx, id)
|
||||
|
||||
require.ErrorContains(t, err, "promote refused")
|
||||
assert.False(t, promoted)
|
||||
status, count := reloadKnowledgeRow(t, db, id)
|
||||
assert.Equal(t, types.ParseStatusFinalizing, status)
|
||||
assert.Equal(t, 1, count, "the decrement must roll back with the failed promote")
|
||||
|
||||
require.NoError(t, db.Exec(`DROP TRIGGER refuse_promote`).Error)
|
||||
_, promoted, err = repo.FinalizeSubtask(ctx, id)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, promoted, "the retried release drains and promotes")
|
||||
status, count = reloadKnowledgeRow(t, db, id)
|
||||
assert.Equal(t, types.ParseStatusCompleted, status)
|
||||
assert.Zero(t, count)
|
||||
}
|
||||
|
||||
// TestSetFinalizingAndFinalizeSubtask_ClearStaleErrorMessage is the
|
||||
// regression test for stale error_message: a row that failed once keeps
|
||||
// error_message set, and both entering finalizing (a new attempt) and
|
||||
// promoting to completed (a successful finish) must clear it so the UI
|
||||
// no longer shows an outdated failure.
|
||||
func TestSetFinalizingAndFinalizeSubtask_ClearStaleErrorMessage(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
|
||||
ctx := context.Background()
|
||||
|
||||
id := insertProcessingKnowledge(t, db)
|
||||
require.NoError(t, db.Exec(
|
||||
`UPDATE knowledges SET error_message = ? WHERE id = ?`,
|
||||
"Task interrupted due to application restart",
|
||||
id,
|
||||
).Error)
|
||||
|
||||
transitioned, err := repo.SetFinalizing(ctx, id, 1)
|
||||
require.NoError(t, err)
|
||||
require.True(t, transitioned)
|
||||
assert.Empty(t, reloadKnowledgeErrorMessage(t, db, id),
|
||||
"SetFinalizing must clear error_message from the previous attempt")
|
||||
|
||||
require.NoError(t, db.Exec(
|
||||
`UPDATE knowledges SET error_message = ? WHERE id = ?`,
|
||||
"stale finalizing failure",
|
||||
id,
|
||||
).Error)
|
||||
_, promoted, err := repo.FinalizeSubtask(ctx, id)
|
||||
require.NoError(t, err)
|
||||
require.True(t, promoted)
|
||||
assert.Empty(t, reloadKnowledgeErrorMessage(t, db, id),
|
||||
"promotion to completed must clear error_message")
|
||||
}
|
||||
|
||||
// TestUpdateKnowledge_DoesNotClobberPendingCounter is the regression test
|
||||
// for the original bug: a full-row Save with a stale in-memory counter
|
||||
// must not write that stale value back, otherwise it overwrites atomic
|
||||
// decrements made by other goroutines.
|
||||
//
|
||||
// Sequence:
|
||||
// 1. SetFinalizing(N=5) -> counter=5
|
||||
// 2. Caller A loads the row (sees counter=5)
|
||||
// 3. FinalizeSubtask runs concurrently and decrements to counter=4
|
||||
// 4. Caller A modifies an unrelated field (Title) and calls UpdateKnowledge
|
||||
// 5. Counter must still be 4 (not 5).
|
||||
func TestUpdateKnowledge_DoesNotClobberPendingCounter(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
|
||||
ctx := context.Background()
|
||||
|
||||
id := insertProcessingKnowledge(t, db)
|
||||
_, err := repo.SetFinalizing(ctx, id, 5)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Step 2: caller A snapshots the row with counter=5 in memory.
|
||||
loaded, err := repo.GetKnowledgeByID(ctx, 1, id)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 5, loaded.PendingSubtasksCount)
|
||||
|
||||
// Step 3: an enrichment subtask decrements concurrently.
|
||||
_, _, err = repo.FinalizeSubtask(ctx, id)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Step 4: caller A persists an unrelated change. The in-memory copy
|
||||
// of PendingSubtasksCount is the STALE 5 — Save must NOT write it.
|
||||
loaded.Title = "renamed-after-stale-load"
|
||||
require.NoError(t, repo.UpdateKnowledge(ctx, loaded))
|
||||
|
||||
// Step 5: the live counter is still 4, not clobbered back to 5.
|
||||
status, count := reloadKnowledgeRow(t, db, id)
|
||||
assert.Equal(t, types.ParseStatusFinalizing, status)
|
||||
assert.Equal(t, 4, count,
|
||||
"UpdateKnowledge must omit pending_subtasks_count so a stale in-memory value cannot clobber atomic decrements")
|
||||
|
||||
// And the unrelated field WAS persisted.
|
||||
reloaded, err := repo.GetKnowledgeByID(ctx, 1, id)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "renamed-after-stale-load", reloaded.Title)
|
||||
}
|
||||
|
||||
// TestUpdateKnowledge_PendingCounterOmittedOnReset verifies the inverse
|
||||
// case the reparse paths rely on: even setting PendingSubtasksCount=0
|
||||
// in memory and calling UpdateKnowledge does NOT persist that value.
|
||||
// Reparse must use UpdateKnowledgeColumn explicitly.
|
||||
func TestUpdateKnowledge_PendingCounterOmittedOnReset(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
|
||||
ctx := context.Background()
|
||||
|
||||
id := insertProcessingKnowledge(t, db)
|
||||
_, err := repo.SetFinalizing(ctx, id, 7)
|
||||
require.NoError(t, err)
|
||||
|
||||
loaded, err := repo.GetKnowledgeByID(ctx, 1, id)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Caller tries to reset the counter via Save — this must be a no-op
|
||||
// for that column. The dedicated UpdateKnowledgeColumn is the only
|
||||
// path that actually writes pending_subtasks_count.
|
||||
loaded.PendingSubtasksCount = 0
|
||||
require.NoError(t, repo.UpdateKnowledge(ctx, loaded))
|
||||
|
||||
_, count := reloadKnowledgeRow(t, db, id)
|
||||
assert.Equal(t, 7, count, "UpdateKnowledge with PendingSubtasksCount=0 must NOT persist the reset")
|
||||
|
||||
// The explicit column write IS the supported path.
|
||||
require.NoError(t, repo.UpdateKnowledgeColumn(ctx, id, "pending_subtasks_count", 0))
|
||||
_, count = reloadKnowledgeRow(t, db, id)
|
||||
assert.Equal(t, 0, count)
|
||||
}
|
||||
|
||||
func TestUpdateActiveDeletingKnowledgeColumns_GuardsStateAndSoftDelete(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
|
||||
ctx := context.Background()
|
||||
|
||||
activeDeletingID := insertKnowledgeWithStatus(t, db, types.ParseStatusDeleting, false)
|
||||
activeCompletedID := insertKnowledgeWithStatus(t, db, types.ParseStatusCompleted, false)
|
||||
deletedDeletingID := insertKnowledgeWithStatus(t, db, types.ParseStatusDeleting, true)
|
||||
|
||||
require.NoError(
|
||||
t,
|
||||
db.Exec(
|
||||
"UPDATE knowledges SET knowledge_base_id = ? WHERE id IN ?",
|
||||
"delete-kb",
|
||||
[]string{activeDeletingID, activeCompletedID, deletedDeletingID},
|
||||
).Error,
|
||||
)
|
||||
for _, scope := range []struct {
|
||||
tenant uint64
|
||||
kb string
|
||||
}{{2, "delete-kb"}, {1, "other-kb"}, {0, "delete-kb"}, {1, ""}} {
|
||||
updated, err := repo.UpdateActiveDeletingKnowledgeColumns(
|
||||
ctx,
|
||||
scope.tenant,
|
||||
scope.kb,
|
||||
activeDeletingID,
|
||||
map[string]interface{}{"parse_status": types.ParseStatusFailed},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.False(t, updated)
|
||||
}
|
||||
|
||||
updated, err := repo.UpdateActiveDeletingKnowledgeColumns(
|
||||
ctx,
|
||||
1,
|
||||
"delete-kb",
|
||||
activeDeletingID,
|
||||
map[string]interface{}{
|
||||
"parse_status": types.ParseStatusFailed,
|
||||
"error_message": "delete task exhausted retries",
|
||||
},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, updated)
|
||||
|
||||
updated, err = repo.UpdateActiveDeletingKnowledgeColumns(
|
||||
ctx,
|
||||
1,
|
||||
"delete-kb",
|
||||
activeCompletedID,
|
||||
map[string]interface{}{
|
||||
"parse_status": types.ParseStatusFailed,
|
||||
},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, updated)
|
||||
|
||||
updated, err = repo.UpdateActiveDeletingKnowledgeColumns(
|
||||
ctx,
|
||||
1,
|
||||
"delete-kb",
|
||||
deletedDeletingID,
|
||||
map[string]interface{}{
|
||||
"parse_status": types.ParseStatusFailed,
|
||||
},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, updated)
|
||||
|
||||
status, _ := reloadKnowledgeRow(t, db, activeDeletingID)
|
||||
assert.Equal(t, types.ParseStatusFailed, status)
|
||||
status, _ = reloadKnowledgeRow(t, db, activeCompletedID)
|
||||
assert.Equal(t, types.ParseStatusCompleted, status)
|
||||
status, _ = reloadKnowledgeRow(t, db, deletedDeletingID)
|
||||
assert.Equal(t, types.ParseStatusDeleting, status)
|
||||
}
|
||||
|
||||
func TestCompleteProcessingWithoutSubtasks(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
status string
|
||||
deleted bool
|
||||
want bool
|
||||
}{
|
||||
{types.ParseStatusProcessing, false, true},
|
||||
{types.ParseStatusCancelled, false, false},
|
||||
{types.ParseStatusDeleting, false, false},
|
||||
{types.ParseStatusCompleted, false, false},
|
||||
{types.ParseStatusFinalizing, false, false},
|
||||
{types.ParseStatusProcessing, true, false},
|
||||
} {
|
||||
t.Run(tc.status+"/deleted="+fmt.Sprint(tc.deleted), func(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db)
|
||||
id := insertKnowledgeWithStatus(t, db, tc.status, tc.deleted)
|
||||
require.NoError(t, db.Exec(
|
||||
`UPDATE knowledges SET summary_status = 'pending', error_message = 'old error' WHERE id = ?`, id,
|
||||
).Error)
|
||||
completed, err := repo.CompleteProcessingWithoutSubtasks(context.Background(), id)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tc.want, completed)
|
||||
status, count := reloadKnowledgeRow(t, db, id)
|
||||
var summary string
|
||||
require.NoError(t, db.Raw(`SELECT summary_status FROM knowledges WHERE id = ?`, id).Scan(&summary).Error)
|
||||
if tc.want {
|
||||
require.Equal(t, types.ParseStatusCompleted, status)
|
||||
require.Zero(t, count)
|
||||
require.Equal(t, types.SummaryStatusNone, summary)
|
||||
require.Empty(t, reloadKnowledgeErrorMessage(t, db, id))
|
||||
completed, err = repo.CompleteProcessingWithoutSubtasks(context.Background(), id)
|
||||
require.NoError(t, err)
|
||||
require.False(t, completed, "duplicate delivery must not complete twice")
|
||||
} else {
|
||||
require.Equal(t, tc.status, status)
|
||||
require.Equal(t, types.SummaryStatusPending, summary)
|
||||
require.Equal(t, "old error", reloadKnowledgeErrorMessage(t, db, id))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// folderPathOf reads a row's stored folder_path directly so the assertions do
|
||||
// not depend on the list filters.
|
||||
func folderPathOf(t *testing.T, db *gorm.DB, id string) string {
|
||||
t.Helper()
|
||||
var path string
|
||||
require.NoError(t, db.Raw(`SELECT folder_path FROM knowledges WHERE id = ?`, id).Scan(&path).Error)
|
||||
return path
|
||||
}
|
||||
|
||||
func TestUpdateKnowledgeFolderPath(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
|
||||
ctx := context.Background()
|
||||
|
||||
const tenantID = uint64(1)
|
||||
kbID := uuid.New().String()
|
||||
otherKBID := uuid.New().String()
|
||||
|
||||
loose := insertKnowledgeInFolder(t, db, tenantID, kbID, "", "readme.md")
|
||||
filed := insertKnowledgeInFolder(t, db, tenantID, kbID, "docs", "intro.md")
|
||||
foreign := insertKnowledgeInFolder(t, db, tenantID, otherKBID, "docs", "other.md")
|
||||
|
||||
affected, err := repo.UpdateKnowledgeFolderPath(ctx, tenantID, kbID, []string{loose, filed}, "archive/2026")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(2), affected)
|
||||
assert.Equal(t, "archive/2026", folderPathOf(t, db, loose))
|
||||
assert.Equal(t, "archive/2026", folderPathOf(t, db, filed))
|
||||
|
||||
// Moving back out of every folder is expressed as the empty path.
|
||||
affected, err = repo.UpdateKnowledgeFolderPath(ctx, tenantID, kbID, []string{filed}, "")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(1), affected)
|
||||
assert.Equal(t, "", folderPathOf(t, db, filed))
|
||||
|
||||
// A row in another knowledge base is never touched, even when its ID is passed.
|
||||
affected, err = repo.UpdateKnowledgeFolderPath(ctx, tenantID, kbID, []string{foreign}, "leaked")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(0), affected)
|
||||
assert.Equal(t, "docs", folderPathOf(t, db, foreign))
|
||||
|
||||
affected, err = repo.UpdateKnowledgeFolderPath(ctx, tenantID, kbID, nil, "archive")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(0), affected)
|
||||
}
|
||||
|
||||
func TestRenameKnowledgeFolderPath(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
|
||||
ctx := context.Background()
|
||||
|
||||
const tenantID = uint64(1)
|
||||
kbID := uuid.New().String()
|
||||
|
||||
root := insertKnowledgeInFolder(t, db, tenantID, kbID, "", "readme.md")
|
||||
docs := insertKnowledgeInFolder(t, db, tenantID, kbID, "docs", "intro.md")
|
||||
spec := insertKnowledgeInFolder(t, db, tenantID, kbID, "docs/spec", "design.md")
|
||||
deep := insertKnowledgeInFolder(t, db, tenantID, kbID, "docs/spec/v2", "draft.md")
|
||||
sibling := insertKnowledgeInFolder(t, db, tenantID, kbID, "docsets", "unrelated.md")
|
||||
|
||||
// The folder and its whole subtree move; siblings whose name merely shares a
|
||||
// prefix ("docsets") must not be dragged along.
|
||||
affected, err := repo.RenameKnowledgeFolderPath(ctx, tenantID, kbID, "docs", "handbook")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(3), affected)
|
||||
assert.Equal(t, "handbook", folderPathOf(t, db, docs))
|
||||
assert.Equal(t, "handbook/spec", folderPathOf(t, db, spec))
|
||||
assert.Equal(t, "handbook/spec/v2", folderPathOf(t, db, deep))
|
||||
assert.Equal(t, "docsets", folderPathOf(t, db, sibling))
|
||||
assert.Equal(t, "", folderPathOf(t, db, root))
|
||||
|
||||
// Renaming a nested folder onto an existing one merges them.
|
||||
_, err = repo.RenameKnowledgeFolderPath(ctx, tenantID, kbID, "handbook/spec", "docsets")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "docsets", folderPathOf(t, db, spec))
|
||||
assert.Equal(t, "docsets/v2", folderPathOf(t, db, deep))
|
||||
assert.Equal(t, "docsets", folderPathOf(t, db, sibling))
|
||||
|
||||
// An unknown folder is a no-op rather than an error.
|
||||
affected, err = repo.RenameKnowledgeFolderPath(ctx, tenantID, kbID, "missing", "whatever")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(0), affected)
|
||||
|
||||
_, err = repo.RenameKnowledgeFolderPath(ctx, tenantID, kbID, "", "whatever")
|
||||
assert.Error(t, err, "renaming the root itself is meaningless and must be rejected")
|
||||
}
|
||||
|
||||
func TestRenameKnowledgeFolderPathUnderscoreInPath(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
|
||||
ctx := context.Background()
|
||||
|
||||
const tenantID = uint64(1)
|
||||
kbID := uuid.New().String()
|
||||
|
||||
parent := insertKnowledgeInFolder(t, db, tenantID, kbID, "my_docs", "intro.md")
|
||||
child := insertKnowledgeInFolder(t, db, tenantID, kbID, "my_docs/spec", "design.md")
|
||||
|
||||
affected, err := repo.RenameKnowledgeFolderPath(ctx, tenantID, kbID, "my_docs", "handbook")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(2), affected)
|
||||
assert.Equal(t, "handbook", folderPathOf(t, db, parent))
|
||||
assert.Equal(t, "handbook/spec", folderPathOf(t, db, child))
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// insertKnowledgeInFolder seeds a completed knowledge row stored in the given
|
||||
// folder so the folder filter and folder aggregation can be asserted.
|
||||
func insertKnowledgeInFolder(t *testing.T, db *gorm.DB, tenantID uint64, kbID, folderPath, fileName string) string {
|
||||
t.Helper()
|
||||
id := uuid.New().String()
|
||||
require.NoError(t, db.Exec(`
|
||||
INSERT INTO knowledges (id, tenant_id, knowledge_base_id, type, title, source, parse_status, file_name, folder_path)
|
||||
VALUES (?, ?, ?, 'file', ?, 'manual', 'completed', ?, ?)
|
||||
`, id, tenantID, kbID, fileName, fileName, folderPath).Error)
|
||||
return id
|
||||
}
|
||||
|
||||
func TestListPagedKnowledgeFolderScope(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
|
||||
ctx := context.Background()
|
||||
|
||||
const tenantID = uint64(1)
|
||||
kbID := uuid.New().String()
|
||||
|
||||
rootID := insertKnowledgeInFolder(t, db, tenantID, kbID, "", "readme.md")
|
||||
docsID := insertKnowledgeInFolder(t, db, tenantID, kbID, "docs", "intro.md")
|
||||
specID := insertKnowledgeInFolder(t, db, tenantID, kbID, "docs/spec", "design.md")
|
||||
otherID := insertKnowledgeInFolder(t, db, tenantID, kbID, "assets", "logo.png")
|
||||
|
||||
page := &types.Pagination{Page: 1, PageSize: 100}
|
||||
list := func(filter types.KnowledgeListFilter) ([]string, int64) {
|
||||
rows, total, err := repo.ListPagedKnowledgeByKnowledgeBaseID(ctx, tenantID, kbID, page, filter)
|
||||
require.NoError(t, err)
|
||||
ids := make([]string, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
ids = append(ids, row.ID)
|
||||
}
|
||||
return ids, total
|
||||
}
|
||||
|
||||
// No folder scope: the flat listing is unchanged, which keeps every existing
|
||||
// caller (and the "all documents" view) working.
|
||||
ids, total := list(types.KnowledgeListFilter{})
|
||||
assert.ElementsMatch(t, []string{rootID, docsID, specID, otherID}, ids)
|
||||
assert.Equal(t, int64(4), total)
|
||||
|
||||
// Exact scope with an empty path means "knowledge base root only".
|
||||
ids, total = list(types.KnowledgeListFilter{FolderScope: types.FolderScopeExact})
|
||||
assert.Equal(t, []string{rootID}, ids)
|
||||
assert.Equal(t, int64(1), total)
|
||||
|
||||
ids, total = list(types.KnowledgeListFilter{FolderPath: "docs", FolderScope: types.FolderScopeExact})
|
||||
assert.Equal(t, []string{docsID}, ids)
|
||||
assert.Equal(t, int64(1), total)
|
||||
|
||||
ids, total = list(types.KnowledgeListFilter{FolderPath: "docs", FolderScope: types.FolderScopeSubtree})
|
||||
assert.ElementsMatch(t, []string{docsID, specID}, ids)
|
||||
assert.Equal(t, int64(2), total)
|
||||
|
||||
// Subtree scope at the root spans the whole knowledge base.
|
||||
ids, _ = list(types.KnowledgeListFilter{FolderScope: types.FolderScopeSubtree})
|
||||
assert.ElementsMatch(t, []string{rootID, docsID, specID, otherID}, ids)
|
||||
|
||||
// Folder scope composes with the other filter dimensions.
|
||||
ids, _ = list(types.KnowledgeListFilter{
|
||||
FolderPath: "docs",
|
||||
FolderScope: types.FolderScopeSubtree,
|
||||
Keyword: "design",
|
||||
})
|
||||
assert.Equal(t, []string{specID}, ids)
|
||||
}
|
||||
|
||||
func TestListPagedKnowledgeFolderScopeUnderscoreInPath(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
|
||||
ctx := context.Background()
|
||||
|
||||
const tenantID = uint64(1)
|
||||
kbID := uuid.New().String()
|
||||
|
||||
parentID := insertKnowledgeInFolder(t, db, tenantID, kbID, "my_docs", "intro.md")
|
||||
childID := insertKnowledgeInFolder(t, db, tenantID, kbID, "my_docs/spec", "design.md")
|
||||
// A sibling whose name merely shares a prefix must not be swept into subtree scope.
|
||||
lookalikeID := insertKnowledgeInFolder(t, db, tenantID, kbID, "myXdocs/spec", "other.md")
|
||||
|
||||
page := &types.Pagination{Page: 1, PageSize: 100}
|
||||
rows, total, err := repo.ListPagedKnowledgeByKnowledgeBaseID(ctx, tenantID, kbID, page, types.KnowledgeListFilter{
|
||||
FolderPath: "my_docs",
|
||||
FolderScope: types.FolderScopeSubtree,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
ids := make([]string, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
ids = append(ids, row.ID)
|
||||
}
|
||||
assert.ElementsMatch(t, []string{parentID, childID}, ids)
|
||||
assert.Equal(t, int64(2), total)
|
||||
assert.NotContains(t, ids, lookalikeID)
|
||||
}
|
||||
|
||||
func TestListKnowledgeFolderCounts(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
|
||||
ctx := context.Background()
|
||||
|
||||
const tenantID = uint64(1)
|
||||
kbID := uuid.New().String()
|
||||
otherKBID := uuid.New().String()
|
||||
|
||||
insertKnowledgeInFolder(t, db, tenantID, kbID, "", "readme.md")
|
||||
insertKnowledgeInFolder(t, db, tenantID, kbID, "docs/spec", "design.md")
|
||||
insertKnowledgeInFolder(t, db, tenantID, kbID, "docs/spec", "api.md")
|
||||
insertKnowledgeInFolder(t, db, tenantID, otherKBID, "docs/spec", "other-kb.md")
|
||||
// Rows mid-deletion are excluded so the tree counts agree with the list.
|
||||
deleting := insertKnowledgeInFolder(t, db, tenantID, kbID, "docs", "vanishing.md")
|
||||
require.NoError(t, db.Exec(`UPDATE knowledges SET parse_status = ? WHERE id = ?`,
|
||||
types.ParseStatusDeleting, deleting).Error)
|
||||
|
||||
counts, err := repo.ListKnowledgeFolderCounts(ctx, tenantID, kbID)
|
||||
require.NoError(t, err)
|
||||
|
||||
byPath := map[string]int64{}
|
||||
for _, row := range counts {
|
||||
byPath[row.FolderPath] = row.Count
|
||||
}
|
||||
assert.Equal(t, map[string]int64{"": 1, "docs/spec": 2}, byPath)
|
||||
|
||||
tree := types.BuildKnowledgeFolderTree(counts)
|
||||
assert.Equal(t, int64(1), tree.RootDocumentCount)
|
||||
assert.Equal(t, int64(3), tree.TotalDocumentCount)
|
||||
require.Len(t, tree.Folders, 1)
|
||||
assert.Equal(t, "docs", tree.Folders[0].Path)
|
||||
assert.Equal(t, int64(2), tree.Folders[0].TotalCount)
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// insertKnowledgeInKB seeds a knowledge row in the given KB with the given
|
||||
// parse_status so we can assert the list filter's visibility rules.
|
||||
func insertKnowledgeInKB(t *testing.T, db *gorm.DB, tenantID uint64, kbID, status string) string {
|
||||
t.Helper()
|
||||
id := uuid.New().String()
|
||||
require.NoError(t, db.Exec(`
|
||||
INSERT INTO knowledges (id, tenant_id, knowledge_base_id, type, title, source, parse_status)
|
||||
VALUES (?, ?, ?, 'file', 'list-filter-test', 'manual', ?)
|
||||
`, id, tenantID, kbID, status).Error)
|
||||
return id
|
||||
}
|
||||
|
||||
// TestListPaged_ExcludesDeletingByDefault documents the fix for issue #2192:
|
||||
// a knowledge row that is mid-deletion (parse_status = 'deleting') must not
|
||||
// appear in the default document list, otherwise a successful async delete
|
||||
// keeps showing the entry until the row is physically gone. Rows in other
|
||||
// states (including the terminal 'failed' a stuck delete resolves to) stay
|
||||
// visible, and an explicit parse_status=deleting filter can still surface them.
|
||||
func TestListPaged_ExcludesDeletingByDefault(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
|
||||
ctx := context.Background()
|
||||
|
||||
const tenantID = uint64(1)
|
||||
kbID := uuid.New().String()
|
||||
|
||||
completedID := insertKnowledgeInKB(t, db, tenantID, kbID, "completed")
|
||||
failedID := insertKnowledgeInKB(t, db, tenantID, kbID, "failed")
|
||||
deletingID := insertKnowledgeInKB(t, db, tenantID, kbID, types.ParseStatusDeleting)
|
||||
|
||||
page := &types.Pagination{Page: 1, PageSize: 100}
|
||||
|
||||
// Default listing (no explicit parse_status): deleting rows are hidden.
|
||||
rows, total, err := repo.ListPagedKnowledgeByKnowledgeBaseID(
|
||||
ctx, tenantID, kbID, page, types.KnowledgeListFilter{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
ids := make([]string, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
ids = append(ids, r.ID)
|
||||
}
|
||||
assert.ElementsMatch(t, []string{completedID, failedID}, ids,
|
||||
"default list must include completed + failed but exclude deleting")
|
||||
assert.Equal(t, int64(2), total, "count must match the filtered rows")
|
||||
|
||||
// Explicit parse_status=deleting still surfaces the in-flight row so
|
||||
// operators / tooling can inspect stuck deletes.
|
||||
rows, total, err = repo.ListPagedKnowledgeByKnowledgeBaseID(
|
||||
ctx, tenantID, kbID, page,
|
||||
types.KnowledgeListFilter{ParseStatus: types.ParseStatusDeleting},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, rows, 1)
|
||||
assert.Equal(t, deletingID, rows[0].ID)
|
||||
assert.Equal(t, int64(1), total)
|
||||
}
|
||||
|
||||
// The deletion UI must use the exact-ID batch endpoint: a row missing from
|
||||
// the default list may only be hidden while cleanup is still in progress.
|
||||
func TestGetKnowledgeBatch_TracksDeletionUntilSoftDelete(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
|
||||
ctx := context.Background()
|
||||
kbID := uuid.New().String()
|
||||
id := insertKnowledgeInKB(t, db, 1, kbID, types.ParseStatusDeleting)
|
||||
otherTenantID := insertKnowledgeInKB(t, db, 2, kbID, types.ParseStatusDeleting)
|
||||
|
||||
rows, err := repo.GetKnowledgeBatch(ctx, 1, []string{id, otherTenantID})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, rows, 1)
|
||||
assert.Equal(t, id, rows[0].ID)
|
||||
assert.Equal(t, types.ParseStatusDeleting, rows[0].ParseStatus)
|
||||
|
||||
updated, err := repo.UpdateActiveDeletingKnowledgeColumns(ctx, 1, kbID, id, map[string]interface{}{
|
||||
"parse_status": types.ParseStatusFailed,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.True(t, updated)
|
||||
rows, err = repo.GetKnowledgeBatch(ctx, 1, []string{id})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, rows, 1)
|
||||
assert.Equal(t, types.ParseStatusFailed, rows[0].ParseStatus)
|
||||
|
||||
require.NoError(t, repo.DeleteKnowledgeList(ctx, 1, []string{id}))
|
||||
rows, err = repo.GetKnowledgeBatch(ctx, 1, []string{id})
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, rows)
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type knowledgeSortSeed struct {
|
||||
id string
|
||||
fileName string
|
||||
title string
|
||||
createdAt time.Time
|
||||
updatedAt time.Time
|
||||
}
|
||||
|
||||
func insertKnowledgeSortSeed(t *testing.T, db *gorm.DB, seed knowledgeSortSeed) {
|
||||
t.Helper()
|
||||
require.NoError(t, db.Exec(`
|
||||
INSERT INTO knowledges
|
||||
(id, tenant_id, knowledge_base_id, type, title, source, file_name, parse_status, created_at, updated_at)
|
||||
VALUES (?, 1, 'kb-sort', 'file', ?, 'manual', ?, 'completed', ?, ?)
|
||||
`, seed.id, seed.title, seed.fileName, seed.createdAt, seed.updatedAt).Error)
|
||||
}
|
||||
|
||||
func knowledgeIDs(rows []*types.Knowledge) []string {
|
||||
ids := make([]string, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
ids = append(ids, row.ID)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
func TestListPagedKnowledgeSortModes(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
|
||||
ctx := context.Background()
|
||||
|
||||
jan := time.Date(2024, time.January, 1, 8, 0, 0, 0, time.UTC)
|
||||
feb := time.Date(2024, time.February, 1, 8, 0, 0, 0, time.UTC)
|
||||
mar := time.Date(2024, time.March, 1, 8, 0, 0, 0, time.UTC)
|
||||
insertKnowledgeSortSeed(t, db, knowledgeSortSeed{
|
||||
id: "doc-a", fileName: "Zulu.txt", title: "Zulu", createdAt: jan, updatedAt: mar,
|
||||
})
|
||||
insertKnowledgeSortSeed(t, db, knowledgeSortSeed{
|
||||
id: "doc-b", fileName: "alpha.txt", title: "Alpha", createdAt: feb, updatedAt: jan,
|
||||
})
|
||||
// file_name 为空时,名称排序应使用前端同样会展示的 title。
|
||||
insertKnowledgeSortSeed(t, db, knowledgeSortSeed{
|
||||
id: "doc-c", fileName: "", title: "Bravo note", createdAt: mar, updatedAt: feb,
|
||||
})
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
filter types.KnowledgeListFilter
|
||||
want []string
|
||||
}{
|
||||
{
|
||||
name: "更新时间从新到旧",
|
||||
filter: types.KnowledgeListFilter{
|
||||
SortBy: types.KnowledgeListSortByUpdatedAt, SortOrder: types.KnowledgeListSortDescending,
|
||||
},
|
||||
want: []string{"doc-a", "doc-c", "doc-b"},
|
||||
},
|
||||
{
|
||||
name: "更新时间从旧到新",
|
||||
filter: types.KnowledgeListFilter{
|
||||
SortBy: types.KnowledgeListSortByUpdatedAt, SortOrder: types.KnowledgeListSortAscending,
|
||||
},
|
||||
want: []string{"doc-b", "doc-c", "doc-a"},
|
||||
},
|
||||
{
|
||||
name: "创建时间从新到旧",
|
||||
filter: types.KnowledgeListFilter{
|
||||
SortBy: types.KnowledgeListSortByCreatedAt, SortOrder: types.KnowledgeListSortDescending,
|
||||
},
|
||||
want: []string{"doc-c", "doc-b", "doc-a"},
|
||||
},
|
||||
{
|
||||
name: "创建时间从旧到新",
|
||||
filter: types.KnowledgeListFilter{
|
||||
SortBy: types.KnowledgeListSortByCreatedAt, SortOrder: types.KnowledgeListSortAscending,
|
||||
},
|
||||
want: []string{"doc-a", "doc-b", "doc-c"},
|
||||
},
|
||||
{
|
||||
name: "文件名称从 A 到 Z 且忽略大小写",
|
||||
filter: types.KnowledgeListFilter{
|
||||
SortBy: types.KnowledgeListSortByFileName, SortOrder: types.KnowledgeListSortAscending,
|
||||
},
|
||||
want: []string{"doc-b", "doc-c", "doc-a"},
|
||||
},
|
||||
{
|
||||
name: "文件名称从 Z 到 A 且忽略大小写",
|
||||
filter: types.KnowledgeListFilter{
|
||||
SortBy: types.KnowledgeListSortByFileName, SortOrder: types.KnowledgeListSortDescending,
|
||||
},
|
||||
want: []string{"doc-a", "doc-c", "doc-b"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
rows, total, err := repo.ListPagedKnowledgeByKnowledgeBaseID(
|
||||
ctx,
|
||||
1,
|
||||
"kb-sort",
|
||||
&types.Pagination{Page: 1, PageSize: 100},
|
||||
tt.filter,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(3), total)
|
||||
assert.Equal(t, tt.want, knowledgeIDs(rows))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestListPagedKnowledgeSortUsesStableIDTieBreaker(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
|
||||
sameTime := time.Date(2024, time.April, 1, 8, 0, 0, 0, time.UTC)
|
||||
|
||||
insertKnowledgeSortSeed(t, db, knowledgeSortSeed{
|
||||
id: "doc-b", fileName: "same.txt", title: "Same", createdAt: sameTime, updatedAt: sameTime,
|
||||
})
|
||||
insertKnowledgeSortSeed(t, db, knowledgeSortSeed{
|
||||
id: "doc-a", fileName: "same.txt", title: "Same", createdAt: sameTime, updatedAt: sameTime,
|
||||
})
|
||||
|
||||
rows, _, err := repo.ListPagedKnowledgeByKnowledgeBaseID(
|
||||
context.Background(),
|
||||
1,
|
||||
"kb-sort",
|
||||
&types.Pagination{Page: 1, PageSize: 100},
|
||||
types.KnowledgeListFilter{
|
||||
SortBy: types.KnowledgeListSortByFileName, SortOrder: types.KnowledgeListSortAscending,
|
||||
},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{"doc-a", "doc-b"}, knowledgeIDs(rows))
|
||||
|
||||
// 每页只取一条,确认相同排序值的文档跨页不会重复或遗漏。
|
||||
for page, wantID := range []string{"doc-a", "doc-b"} {
|
||||
rows, total, err := repo.ListPagedKnowledgeByKnowledgeBaseID(
|
||||
context.Background(), 1, "kb-sort",
|
||||
&types.Pagination{Page: page + 1, PageSize: 1},
|
||||
types.KnowledgeListFilter{
|
||||
SortBy: types.KnowledgeListSortByFileName, SortOrder: types.KnowledgeListSortAscending,
|
||||
},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(2), total)
|
||||
assert.Equal(t, []string{wantID}, knowledgeIDs(rows))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestFindByMetadataKeyPrefix verifies that FindByMetadataKeyPrefix returns only
|
||||
// knowledge items whose metadata["external_id"] starts with the given prefix.
|
||||
//
|
||||
// Setup: three rows in the same KB:
|
||||
// - "nodeA" — the parent document; must NOT be matched by prefix "nodeA#"
|
||||
// - "nodeA#file#x" — an attachment child; MUST be matched
|
||||
// - "nodeB" — a sibling document; must NOT be matched
|
||||
//
|
||||
// A fourth row in a different KB with a matching external_id is also inserted to
|
||||
// verify tenant/KB isolation.
|
||||
func TestFindByMetadataKeyPrefix(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
|
||||
ctx := context.Background()
|
||||
|
||||
const tenantID uint64 = 42
|
||||
kbID := uuid.New().String()
|
||||
otherKBID := uuid.New().String()
|
||||
|
||||
insertRow := func(tid uint64, kb, extID string) string {
|
||||
id := uuid.New().String()
|
||||
metadata := fmt.Sprintf(`{"external_id":%q}`, extID)
|
||||
require.NoError(t, db.Exec(`
|
||||
INSERT INTO knowledges
|
||||
(id, tenant_id, knowledge_base_id, type, title, source, parse_status, metadata)
|
||||
VALUES (?, ?, ?, 'document', ?, 'feishu', 'completed', ?)
|
||||
`, id, tid, kb, extID, metadata).Error)
|
||||
return id
|
||||
}
|
||||
|
||||
_ = insertRow(tenantID, kbID, "nodeA") // parent — must NOT match
|
||||
childID := insertRow(tenantID, kbID, "nodeA#file#x") // attachment child — MUST match
|
||||
_ = insertRow(tenantID, kbID, "nodeB") // sibling — must NOT match
|
||||
_ = insertRow(tenantID, otherKBID, "nodeA#file#y") // different KB — must be excluded
|
||||
|
||||
results, err := repo.FindByMetadataKeyPrefix(ctx, tenantID, kbID, "external_id", "nodeA#")
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Len(t, results, 1, "only the attachment child should match the prefix 'nodeA#'")
|
||||
assert.Equal(t, childID, results[0].ID)
|
||||
}
|
||||
|
||||
// TestFindByMetadataKeyPrefix_DeletedRowsExcluded verifies that soft-deleted rows
|
||||
// (deleted_at IS NOT NULL) are excluded from the prefix query.
|
||||
func TestFindByMetadataKeyPrefix_DeletedRowsExcluded(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
|
||||
ctx := context.Background()
|
||||
|
||||
const tenantID uint64 = 43
|
||||
kbID := uuid.New().String()
|
||||
|
||||
id := uuid.New().String()
|
||||
metadata := fmt.Sprintf(`{"external_id":%q}`, "nodeC#file#z")
|
||||
require.NoError(t, db.Exec(`
|
||||
INSERT INTO knowledges
|
||||
(id, tenant_id, knowledge_base_id, type, title, source, parse_status, metadata, deleted_at)
|
||||
VALUES (?, ?, ?, 'document', 'deleted-child', 'feishu', 'completed', ?, '2026-01-01 00:00:00')
|
||||
`, id, tenantID, kbID, metadata).Error)
|
||||
|
||||
results, err := repo.FindByMetadataKeyPrefix(ctx, tenantID, kbID, "external_id", "nodeC#")
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, results, "soft-deleted rows must not appear in prefix results")
|
||||
}
|
||||
|
||||
// TestFindByMetadataKeyPrefix_UnderscoreIsLiteral verifies that an underscore in
|
||||
// the prefix is treated as a literal character and does NOT act as a SQL LIKE
|
||||
// wildcard. Without escapeLikeKeyword applied to the prefix, a query for "ab_c#"
|
||||
// would also match "abXc#file#y" because '_' is a wildcard.
|
||||
func TestFindByMetadataKeyPrefix_UnderscoreIsLiteral(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
|
||||
ctx := context.Background()
|
||||
|
||||
const tenantID uint64 = 44
|
||||
kbID := uuid.New().String()
|
||||
|
||||
insertRow := func(extID string) string {
|
||||
id := uuid.New().String()
|
||||
metadata := fmt.Sprintf(`{"external_id":%q}`, extID)
|
||||
require.NoError(t, db.Exec(`
|
||||
INSERT INTO knowledges
|
||||
(id, tenant_id, knowledge_base_id, type, title, source, parse_status, metadata)
|
||||
VALUES (?, ?, ?, 'document', ?, 'feishu', 'completed', ?)
|
||||
`, id, tenantID, kbID, extID, metadata).Error)
|
||||
return id
|
||||
}
|
||||
|
||||
// The prefix we will search for is "ab_c#". Without escaping, '_' is a
|
||||
// wildcard that matches any single character, so "abXc#file#y" would also
|
||||
// be returned. With escaping it must NOT be returned.
|
||||
targetID := insertRow("ab_c#file#x") // literal underscore — MUST match
|
||||
_ = insertRow("abXc#file#y") // 'X' instead of '_' — must NOT match
|
||||
|
||||
results, err := repo.FindByMetadataKeyPrefix(ctx, tenantID, kbID, "external_id", "ab_c#")
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Len(t, results, 1, "underscore in prefix must be treated as literal: only 'ab_c#file#x' should match")
|
||||
assert.Equal(t, targetID, results[0].ID)
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestKnowledgeSourceSchemaAllowsObjectStorageURLs(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open("file:knowledge_source_schema?mode=memory&cache=shared"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatalf("open sqlite: %v", err)
|
||||
}
|
||||
sqlDB, err := db.DB()
|
||||
if err != nil {
|
||||
t.Fatalf("get sqlite handle: %v", err)
|
||||
}
|
||||
sqlDB.SetMaxOpenConns(1)
|
||||
if err := db.AutoMigrate(&types.Knowledge{}); err != nil {
|
||||
t.Fatalf("auto migrate knowledge: %v", err)
|
||||
}
|
||||
|
||||
var sourceType string
|
||||
rows, err := db.Raw("PRAGMA table_info(knowledges)").Rows()
|
||||
if err != nil {
|
||||
t.Fatalf("inspect knowledge schema: %v", err)
|
||||
}
|
||||
|
||||
for rows.Next() {
|
||||
var cid int
|
||||
var name, typ string
|
||||
var notNull int
|
||||
var defaultValue any
|
||||
var pk int
|
||||
if err := rows.Scan(&cid, &name, &typ, ¬Null, &defaultValue, &pk); err != nil {
|
||||
t.Fatalf("scan column info: %v", err)
|
||||
}
|
||||
if name == "source" {
|
||||
sourceType = strings.ToLower(typ)
|
||||
break
|
||||
}
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
t.Fatalf("close column info rows: %v", err)
|
||||
}
|
||||
if sourceType != "varchar(2048)" {
|
||||
t.Fatalf("knowledge source column type = %q, want varchar(2048)", sourceType)
|
||||
}
|
||||
|
||||
longURL := "https://example-bucket.cos.ap-beijing.myqcloud.com/test/" +
|
||||
strings.Repeat("encoded-path-segment-", 20) + ".docx"
|
||||
knowledge := &types.Knowledge{
|
||||
TenantID: 1,
|
||||
KnowledgeBaseID: "kb-1",
|
||||
Type: types.KnowledgeTypeManual,
|
||||
Title: "long source",
|
||||
Source: longURL,
|
||||
ParseStatus: types.ParseStatusPending,
|
||||
EnableStatus: "enabled",
|
||||
}
|
||||
if err := db.Create(knowledge).Error; err != nil {
|
||||
t.Fatalf("create knowledge with long source: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"academy/internal/common"
|
||||
"academy/internal/types"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
// KnowledgeSpanRepository persists the per-attempt span tree used by the
|
||||
// processing pipeline. Operations are deliberately narrow:
|
||||
//
|
||||
// - Upsert covers Begin/End/Fail/Skip — every state transition routes
|
||||
// through the same write so the row stays internally consistent.
|
||||
// - NextAttempt allocates a new attempt for re-parses without touching
|
||||
// historical rows. Old attempts stay queryable for post-mortem.
|
||||
// - ListByAttempt is the only read path; the handler builds the tree
|
||||
// in memory rather than recursing through the DB.
|
||||
type KnowledgeSpanRepository interface {
|
||||
Upsert(ctx context.Context, row *types.KnowledgeProcessingSpan) error
|
||||
NextAttempt(ctx context.Context, knowledgeID string) (int, error)
|
||||
LatestAttempt(ctx context.Context, knowledgeID string) (int, error)
|
||||
ListByAttempt(ctx context.Context, knowledgeID string, attempt int) ([]types.KnowledgeProcessingSpan, error)
|
||||
GetSpan(ctx context.Context, knowledgeID string, attempt int, spanID string) (*types.KnowledgeProcessingSpan, error)
|
||||
// CancelDescendants marks every descendant of a parent span as
|
||||
// "cancelled" with the given reason. Used by the tracker to
|
||||
// cascade an upstream failure across a stage's downstream subtree
|
||||
// without iterating in Go memory.
|
||||
CancelDescendants(ctx context.Context, knowledgeID string, attempt int, parentSpanID, reason string) (int64, error)
|
||||
// CancelAllOpenSpans flips every non-terminal (pending/running) span
|
||||
// for (knowledgeID, attempt) to "cancelled" in one statement,
|
||||
// regardless of tree position. Used by the user-cancel path where
|
||||
// fan-out stages (e.g. "多模态识别") flip themselves to done as soon
|
||||
// as they finish dispatching, while their async children are still
|
||||
// running — a tree walk that stops at terminal parents would miss
|
||||
// those orphan leaves.
|
||||
CancelAllOpenSpans(ctx context.Context, knowledgeID string, attempt int, errorCode, reason string) (int64, error)
|
||||
// CancelOpenSpansBeforeAttempt flips every pending/running span belonging to
|
||||
// an attempt strictly older than `attempt` to cancelled. Reparse calls it so a
|
||||
// superseded attempt cannot leave a "running" root behind.
|
||||
CancelOpenSpansBeforeAttempt(
|
||||
ctx context.Context, knowledgeID string, attempt int, errorCode, reason string,
|
||||
) (int64, error)
|
||||
// CancelOpenSpansByName flips pending/running rows with the given span
|
||||
// name for (knowledgeID, attempt). Used before re-opening a subspan
|
||||
// after asynq retry or server restart so the trace tree does not
|
||||
// accumulate duplicate postprocess.summary / question rows.
|
||||
CancelOpenSpansByName(ctx context.Context, knowledgeID string, attempt int, name, errorCode, reason string) (int64, error)
|
||||
// LastActivity returns each knowledge's most recent span write, across
|
||||
// attempts. Knowledge without spans is absent from the map.
|
||||
LastActivity(ctx context.Context, knowledgeIDs []string) (map[string]time.Time, error)
|
||||
}
|
||||
|
||||
type knowledgeSpanRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewKnowledgeSpanRepository wires the GORM-backed implementation.
|
||||
func NewKnowledgeSpanRepository(db *gorm.DB) KnowledgeSpanRepository {
|
||||
return &knowledgeSpanRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *knowledgeSpanRepository) Upsert(ctx context.Context, row *types.KnowledgeProcessingSpan) error {
|
||||
if row == nil || row.KnowledgeID == "" || row.SpanID == "" {
|
||||
return errors.New("knowledgeSpanRepository.Upsert: knowledge_id and span_id required")
|
||||
}
|
||||
if row.Attempt == 0 {
|
||||
row.Attempt = 1
|
||||
}
|
||||
// Error fields may originate from third-party parser/model responses.
|
||||
// Normalize them at the persistence boundary so SQLite/PostgreSQL and the
|
||||
// tracing API never receive malformed UTF-8.
|
||||
row.ErrorCode = common.CleanInvalidUTF8(row.ErrorCode)
|
||||
row.ErrorMessage = common.CleanInvalidUTF8(row.ErrorMessage)
|
||||
row.ErrorDetail = common.CleanInvalidUTF8(row.ErrorDetail)
|
||||
// We let GORM populate created_at/updated_at via the autoCreate /
|
||||
// autoUpdate tags. ON CONFLICT updates only the fields that may
|
||||
// transition between calls — name/kind/parent are immutable once
|
||||
// set so we don't list them in DoUpdates (saves a few bytes per
|
||||
// write, and any mismatch indicates a programming error).
|
||||
//
|
||||
// CRITICAL: input / output / metadata are CONTENT fields that
|
||||
// individual call sites only fill when they have something to set.
|
||||
// EndSpan e.g. only sets `output`; if we always listed `input` in
|
||||
// DoUpdates, the End call would clobber the input set by Begin with
|
||||
// NULL. Same for metadata. Build the DoUpdates list dynamically and
|
||||
// skip these three columns when the incoming row has nothing to
|
||||
// write — so "no value" preserves the existing column instead of
|
||||
// nuking it.
|
||||
cols := []string{
|
||||
"status",
|
||||
"error_code",
|
||||
"error_message",
|
||||
"error_detail",
|
||||
"started_at",
|
||||
"finished_at",
|
||||
"duration_ms",
|
||||
"updated_at",
|
||||
}
|
||||
if row.Input != nil {
|
||||
cols = append(cols, "input")
|
||||
}
|
||||
if row.Output != nil {
|
||||
cols = append(cols, "output")
|
||||
}
|
||||
if row.Metadata != nil {
|
||||
cols = append(cols, "metadata")
|
||||
}
|
||||
return r.db.WithContext(ctx).Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{
|
||||
{Name: "knowledge_id"},
|
||||
{Name: "attempt"},
|
||||
{Name: "span_id"},
|
||||
},
|
||||
DoUpdates: clause.AssignmentColumns(cols),
|
||||
}).Create(row).Error
|
||||
}
|
||||
|
||||
func (r *knowledgeSpanRepository) NextAttempt(ctx context.Context, knowledgeID string) (int, error) {
|
||||
var max int
|
||||
err := r.db.WithContext(ctx).Model(&types.KnowledgeProcessingSpan{}).
|
||||
Where("knowledge_id = ?", knowledgeID).
|
||||
Select("COALESCE(MAX(attempt), 0)").
|
||||
Row().Scan(&max)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return max + 1, nil
|
||||
}
|
||||
|
||||
func (r *knowledgeSpanRepository) LatestAttempt(ctx context.Context, knowledgeID string) (int, error) {
|
||||
var max int
|
||||
err := r.db.WithContext(ctx).Model(&types.KnowledgeProcessingSpan{}).
|
||||
Where("knowledge_id = ?", knowledgeID).
|
||||
Select("COALESCE(MAX(attempt), 0)").
|
||||
Row().Scan(&max)
|
||||
return max, err
|
||||
}
|
||||
|
||||
func (r *knowledgeSpanRepository) ListByAttempt(ctx context.Context, knowledgeID string, attempt int) ([]types.KnowledgeProcessingSpan, error) {
|
||||
if knowledgeID == "" {
|
||||
return nil, nil
|
||||
}
|
||||
var rows []types.KnowledgeProcessingSpan
|
||||
q := r.db.WithContext(ctx).Where("knowledge_id = ?", knowledgeID)
|
||||
if attempt > 0 {
|
||||
q = q.Where("attempt = ?", attempt)
|
||||
}
|
||||
// id ASC keeps the natural insertion order — useful for stable
|
||||
// rendering of fan-out subspans (e.g. multimodal.image[0..N] in
|
||||
// the order they were enqueued).
|
||||
err := q.Order("id ASC").Find(&rows).Error
|
||||
return rows, err
|
||||
}
|
||||
|
||||
func (r *knowledgeSpanRepository) GetSpan(ctx context.Context, knowledgeID string, attempt int, spanID string) (*types.KnowledgeProcessingSpan, error) {
|
||||
var row types.KnowledgeProcessingSpan
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("knowledge_id = ? AND attempt = ? AND span_id = ?", knowledgeID, attempt, spanID).
|
||||
Take(&row).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &row, nil
|
||||
}
|
||||
|
||||
// CancelDescendants performs an iterative SQL walk: each level we update
|
||||
// every row whose parent_span_id is in the previous level's span_id set,
|
||||
// flipping pending/running rows to cancelled. We bail when a level adds
|
||||
// zero rows (fixed point reached) or after a generous depth bound.
|
||||
//
|
||||
// Postgres-specific WITH RECURSIVE would be denser but harder to test on
|
||||
// the SQLite Lite backend. The iterative path stays portable.
|
||||
func (r *knowledgeSpanRepository) CancelDescendants(ctx context.Context, knowledgeID string, attempt int, parentSpanID, reason string) (int64, error) {
|
||||
reason = common.CleanInvalidUTF8(reason)
|
||||
frontier := []string{parentSpanID}
|
||||
var totalAffected int64
|
||||
for depth := 0; depth < 16 && len(frontier) > 0; depth++ {
|
||||
var nextFrontier []string
|
||||
// Find children of every span currently on the frontier
|
||||
// that are still in a non-terminal state — terminal rows
|
||||
// (done/failed/skipped/cancelled) are left as-is so the UI
|
||||
// can still see their original outcome.
|
||||
var children []types.KnowledgeProcessingSpan
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("knowledge_id = ? AND attempt = ? AND parent_span_id IN ? AND status IN ?",
|
||||
knowledgeID, attempt, frontier,
|
||||
[]string{types.SpanStatusPending, types.SpanStatusRunning}).
|
||||
Find(&children).Error
|
||||
if err != nil {
|
||||
return totalAffected, err
|
||||
}
|
||||
if len(children) == 0 {
|
||||
break
|
||||
}
|
||||
ids := make([]string, 0, len(children))
|
||||
for _, c := range children {
|
||||
ids = append(ids, c.SpanID)
|
||||
nextFrontier = append(nextFrontier, c.SpanID)
|
||||
}
|
||||
res := r.db.WithContext(ctx).Model(&types.KnowledgeProcessingSpan{}).
|
||||
Where("knowledge_id = ? AND attempt = ? AND span_id IN ?", knowledgeID, attempt, ids).
|
||||
Updates(map[string]any{
|
||||
"status": types.SpanStatusCancelled,
|
||||
"error_code": "UPSTREAM_FAILED",
|
||||
"error_message": reason,
|
||||
})
|
||||
if res.Error != nil {
|
||||
return totalAffected, res.Error
|
||||
}
|
||||
totalAffected += res.RowsAffected
|
||||
frontier = nextFrontier
|
||||
}
|
||||
return totalAffected, nil
|
||||
}
|
||||
|
||||
// CancelAllOpenSpans is the "abort the attempt" counterpart to
|
||||
// CancelDescendants. It avoids the BFS entirely so spans whose parent
|
||||
// is already terminal (typical for stage fan-outs that EndSpan as soon
|
||||
// as they finish dispatching async work) still get flipped to cancelled.
|
||||
// We deliberately do NOT touch finished_at / duration_ms here — the
|
||||
// span row remains observable in the trace tree with its original
|
||||
// start time and gets a cancelled status + reason, which is enough
|
||||
// for the UI to drop the running-bar styling.
|
||||
func (r *knowledgeSpanRepository) CancelAllOpenSpans(
|
||||
ctx context.Context, knowledgeID string, attempt int, errorCode, reason string,
|
||||
) (int64, error) {
|
||||
errorCode = common.CleanInvalidUTF8(errorCode)
|
||||
reason = common.CleanInvalidUTF8(reason)
|
||||
now := time.Now()
|
||||
updates := map[string]any{
|
||||
"status": types.SpanStatusCancelled,
|
||||
"error_code": errorCode,
|
||||
"error_message": reason,
|
||||
"finished_at": now,
|
||||
"updated_at": now,
|
||||
}
|
||||
res := r.db.WithContext(ctx).Model(&types.KnowledgeProcessingSpan{}).
|
||||
Where("knowledge_id = ? AND attempt = ? AND status IN ?",
|
||||
knowledgeID, attempt,
|
||||
[]string{types.SpanStatusPending, types.SpanStatusRunning}).
|
||||
Updates(updates)
|
||||
if res.Error != nil {
|
||||
return 0, res.Error
|
||||
}
|
||||
return res.RowsAffected, nil
|
||||
}
|
||||
|
||||
// CancelOpenSpansBeforeAttempt is CancelAllOpenSpans widened to every attempt
|
||||
// older than `attempt`. A reparse allocates attempt N+1 while attempt N may
|
||||
// still hold open spans (its worker died, or the row was failed without
|
||||
// finalizing); those would otherwise live forever.
|
||||
func (r *knowledgeSpanRepository) CancelOpenSpansBeforeAttempt(
|
||||
ctx context.Context, knowledgeID string, attempt int, errorCode, reason string,
|
||||
) (int64, error) {
|
||||
errorCode = common.CleanInvalidUTF8(errorCode)
|
||||
reason = common.CleanInvalidUTF8(reason)
|
||||
now := time.Now()
|
||||
res := r.db.WithContext(ctx).Model(&types.KnowledgeProcessingSpan{}).
|
||||
Where("knowledge_id = ? AND attempt < ? AND status IN ?",
|
||||
knowledgeID, attempt,
|
||||
[]string{types.SpanStatusPending, types.SpanStatusRunning}).
|
||||
Updates(map[string]any{
|
||||
"status": types.SpanStatusCancelled,
|
||||
"error_code": errorCode,
|
||||
"error_message": reason,
|
||||
"finished_at": now,
|
||||
"updated_at": now,
|
||||
})
|
||||
if res.Error != nil {
|
||||
return 0, res.Error
|
||||
}
|
||||
return res.RowsAffected, nil
|
||||
}
|
||||
|
||||
func (r *knowledgeSpanRepository) CancelOpenSpansByName(
|
||||
ctx context.Context, knowledgeID string, attempt int, name, errorCode, reason string,
|
||||
) (int64, error) {
|
||||
if knowledgeID == "" || attempt <= 0 || name == "" {
|
||||
return 0, nil
|
||||
}
|
||||
errorCode = common.CleanInvalidUTF8(errorCode)
|
||||
reason = common.CleanInvalidUTF8(reason)
|
||||
now := time.Now()
|
||||
res := r.db.WithContext(ctx).Model(&types.KnowledgeProcessingSpan{}).
|
||||
Where("knowledge_id = ? AND attempt = ? AND name = ? AND status IN ?",
|
||||
knowledgeID, attempt, name,
|
||||
[]string{types.SpanStatusPending, types.SpanStatusRunning}).
|
||||
Updates(map[string]any{
|
||||
"status": types.SpanStatusCancelled,
|
||||
"error_code": errorCode,
|
||||
"error_message": reason,
|
||||
"finished_at": now,
|
||||
"updated_at": now,
|
||||
})
|
||||
if res.Error != nil {
|
||||
return 0, res.Error
|
||||
}
|
||||
return res.RowsAffected, nil
|
||||
}
|
||||
|
||||
func (r *knowledgeSpanRepository) LastActivity(
|
||||
ctx context.Context, knowledgeIDs []string,
|
||||
) (map[string]time.Time, error) {
|
||||
out := make(map[string]time.Time, len(knowledgeIDs))
|
||||
if len(knowledgeIDs) == 0 {
|
||||
return out, nil
|
||||
}
|
||||
// MAX() comes back as a string on SQLite, so scan text and parse.
|
||||
var rows []struct {
|
||||
KnowledgeID string `gorm:"column:knowledge_id"`
|
||||
LastSeen string `gorm:"column:last_seen"`
|
||||
}
|
||||
if err := r.db.WithContext(ctx).
|
||||
Model(&types.KnowledgeProcessingSpan{}).
|
||||
Select("knowledge_id, MAX(updated_at) AS last_seen").
|
||||
Where("knowledge_id IN ?", knowledgeIDs).
|
||||
Group("knowledge_id").
|
||||
Scan(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, row := range rows {
|
||||
if t, ok := ParseAggregateTime(row.LastSeen); ok {
|
||||
out[row.KnowledgeID] = t
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ParseAggregateTime parses a timestamp read back through an SQL aggregate,
|
||||
// in the formats Postgres and SQLite emit.
|
||||
func ParseAggregateTime(s string) (time.Time, bool) {
|
||||
if s == "" {
|
||||
return time.Time{}, false
|
||||
}
|
||||
for _, layout := range []string{
|
||||
time.RFC3339Nano,
|
||||
time.RFC3339,
|
||||
"2006-01-02 15:04:05.999999999-07:00",
|
||||
"2006-01-02 15:04:05.999999999",
|
||||
"2006-01-02 15:04:05.999999",
|
||||
"2006-01-02 15:04:05",
|
||||
} {
|
||||
if t, err := time.Parse(layout, s); err == nil {
|
||||
return t, true
|
||||
}
|
||||
}
|
||||
return time.Time{}, false
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// spansTestDDL mirrors migration 000053 for SQLite — same column order
|
||||
// minus the JSONB type (SQLite stores JSON as TEXT, the JSONMap Scanner
|
||||
// handles the round trip transparently). Inlined for the same reason
|
||||
// knowledgebase_sqlite_test.go inlines its DDL: GORM AutoMigrate doesn't
|
||||
// reproduce our PostgreSQL-flavoured schema cleanly.
|
||||
const spansTestDDL = `
|
||||
CREATE TABLE IF NOT EXISTS knowledge_processing_spans (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
knowledge_id VARCHAR(64) NOT NULL,
|
||||
attempt INTEGER NOT NULL DEFAULT 1,
|
||||
span_id VARCHAR(64) NOT NULL,
|
||||
parent_span_id VARCHAR(64),
|
||||
name VARCHAR(255) NOT NULL,
|
||||
kind VARCHAR(16) NOT NULL,
|
||||
status VARCHAR(16) NOT NULL,
|
||||
input TEXT,
|
||||
output TEXT,
|
||||
metadata TEXT,
|
||||
error_code VARCHAR(64),
|
||||
error_message TEXT,
|
||||
error_detail TEXT,
|
||||
started_at DATETIME,
|
||||
finished_at DATETIME,
|
||||
duration_ms BIGINT,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE (knowledge_id, attempt, span_id)
|
||||
);
|
||||
`
|
||||
|
||||
func setupSpanTestRepo(t *testing.T) (KnowledgeSpanRepository, *gorm.DB) {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.Exec(spansTestDDL).Error)
|
||||
return NewKnowledgeSpanRepository(db), db
|
||||
}
|
||||
|
||||
// TestKnowledgeSpanRepo_UpsertAndList covers the round-trip: a Begin
|
||||
// followed by an End for the same (kid, attempt, span_id) updates the
|
||||
// existing row in place, leaving exactly one row queryable by
|
||||
// ListByAttempt with the latest state.
|
||||
func TestKnowledgeSpanRepo_UpsertAndList(t *testing.T) {
|
||||
repo, _ := setupSpanTestRepo(t)
|
||||
ctx := context.Background()
|
||||
kid := "kid-1"
|
||||
now := time.Now()
|
||||
row := &types.KnowledgeProcessingSpan{
|
||||
KnowledgeID: kid,
|
||||
Attempt: 1,
|
||||
SpanID: "span-A",
|
||||
Name: types.StageDocReader,
|
||||
Kind: types.SpanKindStage,
|
||||
Status: types.SpanStatusRunning,
|
||||
StartedAt: &now,
|
||||
}
|
||||
require.NoError(t, repo.Upsert(ctx, row))
|
||||
|
||||
// Second Upsert with same (kid, attempt, span_id) flips status and
|
||||
// sets finished_at — must overwrite, not insert a duplicate.
|
||||
finished := now.Add(2 * time.Second)
|
||||
row.Status = types.SpanStatusDone
|
||||
row.FinishedAt = &finished
|
||||
row.DurationMs = 2000
|
||||
require.NoError(t, repo.Upsert(ctx, row))
|
||||
|
||||
rows, err := repo.ListByAttempt(ctx, kid, 1)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, rows, 1, "Upsert must replace, not append")
|
||||
assert.Equal(t, types.SpanStatusDone, rows[0].Status)
|
||||
assert.Equal(t, int64(2000), rows[0].DurationMs)
|
||||
}
|
||||
|
||||
func TestKnowledgeSpanRepo_UpsertSanitizesErrorFields(t *testing.T) {
|
||||
repo, _ := setupSpanTestRepo(t)
|
||||
now := time.Now()
|
||||
invalid := "prefix " + string([]byte{0xef, 0xbc, 0x2e}) + " suffix"
|
||||
|
||||
require.NoError(t, repo.Upsert(context.Background(), &types.KnowledgeProcessingSpan{
|
||||
KnowledgeID: "kid-invalid-utf8",
|
||||
Attempt: 1,
|
||||
SpanID: "span-invalid",
|
||||
Name: types.StageDocReader,
|
||||
Kind: types.SpanKindStage,
|
||||
Status: types.SpanStatusFailed,
|
||||
ErrorCode: invalid,
|
||||
ErrorMessage: invalid,
|
||||
ErrorDetail: invalid,
|
||||
StartedAt: &now,
|
||||
}))
|
||||
|
||||
rows, err := repo.ListByAttempt(context.Background(), "kid-invalid-utf8", 1)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, rows, 1)
|
||||
for _, value := range []string{rows[0].ErrorCode, rows[0].ErrorMessage, rows[0].ErrorDetail} {
|
||||
if !utf8.ValidString(value) {
|
||||
t.Fatalf("persisted error field is invalid UTF-8: % x", []byte(value))
|
||||
}
|
||||
if value != "prefix . suffix" {
|
||||
t.Fatalf("persisted error field = %q, want %q", value, "prefix . suffix")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestKnowledgeSpanRepo_NextAttempt confirms that NextAttempt allocates
|
||||
// a fresh number per knowledge, isolating reparse history. Critical
|
||||
// because the API layer renders attempt history by this number.
|
||||
func TestKnowledgeSpanRepo_NextAttempt(t *testing.T) {
|
||||
repo, _ := setupSpanTestRepo(t)
|
||||
ctx := context.Background()
|
||||
kid := "kid-2"
|
||||
|
||||
a, err := repo.NextAttempt(ctx, kid)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 1, a, "first NextAttempt for fresh knowledge must be 1")
|
||||
|
||||
now := time.Now()
|
||||
require.NoError(t, repo.Upsert(ctx, &types.KnowledgeProcessingSpan{
|
||||
KnowledgeID: kid, Attempt: 1, SpanID: "root-1",
|
||||
Name: "knowledge_processing", Kind: types.SpanKindRoot,
|
||||
Status: types.SpanStatusRunning, StartedAt: &now,
|
||||
}))
|
||||
a, err = repo.NextAttempt(ctx, kid)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 2, a, "after one attempt exists, NextAttempt must be 2")
|
||||
|
||||
// Cross-knowledge isolation: a different kid stays at 1.
|
||||
other, err := repo.NextAttempt(ctx, "kid-other")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 1, other, "NextAttempt must scope to the knowledge_id")
|
||||
}
|
||||
|
||||
// TestKnowledgeSpanRepo_CancelDescendants verifies the cascade walk:
|
||||
// failing a stage cancels every pending/running descendant in its
|
||||
// subtree, while terminal states (done/skipped/failed) are left intact.
|
||||
func TestKnowledgeSpanRepo_CancelDescendants(t *testing.T) {
|
||||
repo, _ := setupSpanTestRepo(t)
|
||||
ctx := context.Background()
|
||||
kid := "kid-3"
|
||||
now := time.Now()
|
||||
|
||||
// Tree: chunking → embedding (running) → batch[0] (running)
|
||||
// → multimodal (running) → image[0] (done)
|
||||
for _, r := range []*types.KnowledgeProcessingSpan{
|
||||
{KnowledgeID: kid, Attempt: 1, SpanID: "chunking", Name: types.StageChunking, Kind: types.SpanKindStage, Status: types.SpanStatusRunning, StartedAt: &now},
|
||||
{KnowledgeID: kid, Attempt: 1, SpanID: "embedding", ParentSpanID: "chunking", Name: types.StageEmbedding, Kind: types.SpanKindStage, Status: types.SpanStatusRunning, StartedAt: &now},
|
||||
{KnowledgeID: kid, Attempt: 1, SpanID: "batch0", ParentSpanID: "embedding", Name: "embedding.batch[0]", Kind: types.SpanKindGeneration, Status: types.SpanStatusRunning, StartedAt: &now},
|
||||
{KnowledgeID: kid, Attempt: 1, SpanID: "multimodal", ParentSpanID: "chunking", Name: types.StageMultimodal, Kind: types.SpanKindStage, Status: types.SpanStatusRunning, StartedAt: &now},
|
||||
{KnowledgeID: kid, Attempt: 1, SpanID: "image0", ParentSpanID: "multimodal", Name: "multimodal.image[0]", Kind: types.SpanKindGeneration, Status: types.SpanStatusDone, StartedAt: &now},
|
||||
} {
|
||||
require.NoError(t, repo.Upsert(ctx, r))
|
||||
}
|
||||
|
||||
affected, err := repo.CancelDescendants(ctx, kid, 1, "chunking", "test reason")
|
||||
require.NoError(t, err)
|
||||
// Expected cancellations: embedding, batch0, multimodal (3 rows).
|
||||
// The done image0 is terminal and left alone.
|
||||
assert.Equal(t, int64(3), affected, "must cancel exactly the 3 pending/running descendants")
|
||||
|
||||
rows, err := repo.ListByAttempt(ctx, kid, 1)
|
||||
require.NoError(t, err)
|
||||
statusBy := map[string]string{}
|
||||
for _, r := range rows {
|
||||
statusBy[r.SpanID] = r.Status
|
||||
}
|
||||
assert.Equal(t, types.SpanStatusRunning, statusBy["chunking"], "the failed span itself stays untouched (FailSpan layer flips it)")
|
||||
assert.Equal(t, types.SpanStatusCancelled, statusBy["embedding"])
|
||||
assert.Equal(t, types.SpanStatusCancelled, statusBy["batch0"])
|
||||
assert.Equal(t, types.SpanStatusCancelled, statusBy["multimodal"])
|
||||
assert.Equal(t, types.SpanStatusDone, statusBy["image0"], "terminal states must not be touched")
|
||||
}
|
||||
|
||||
func TestKnowledgeSpanRepo_CancelOpenSpansByName(t *testing.T) {
|
||||
repo, _ := setupSpanTestRepo(t)
|
||||
ctx := context.Background()
|
||||
kid := "kid-supersede"
|
||||
now := time.Now()
|
||||
|
||||
for _, r := range []*types.KnowledgeProcessingSpan{
|
||||
{KnowledgeID: kid, Attempt: 1, SpanID: "sum-old", Name: "postprocess.summary", Kind: types.SpanKindSubSpan, Status: types.SpanStatusRunning, StartedAt: &now},
|
||||
{KnowledgeID: kid, Attempt: 1, SpanID: "sum-done", Name: "postprocess.summary", Kind: types.SpanKindSubSpan, Status: types.SpanStatusDone, StartedAt: &now},
|
||||
{KnowledgeID: kid, Attempt: 1, SpanID: "q-old", Name: "postprocess.question", Kind: types.SpanKindSubSpan, Status: types.SpanStatusRunning, StartedAt: &now},
|
||||
} {
|
||||
require.NoError(t, repo.Upsert(ctx, r))
|
||||
}
|
||||
|
||||
affected, err := repo.CancelOpenSpansByName(ctx, kid, 1, "postprocess.summary", "TASK_SUPERSEDED", "retry")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(1), affected)
|
||||
|
||||
rows, err := repo.ListByAttempt(ctx, kid, 1)
|
||||
require.NoError(t, err)
|
||||
statusBy := map[string]string{}
|
||||
for _, r := range rows {
|
||||
statusBy[r.SpanID] = r.Status
|
||||
}
|
||||
assert.Equal(t, types.SpanStatusCancelled, statusBy["sum-old"])
|
||||
assert.Equal(t, types.SpanStatusDone, statusBy["sum-done"])
|
||||
assert.Equal(t, types.SpanStatusRunning, statusBy["q-old"])
|
||||
}
|
||||
|
||||
func TestKnowledgeSpanRepo_CancelPathsSanitizeErrorFields(t *testing.T) {
|
||||
repo, _ := setupSpanTestRepo(t)
|
||||
ctx := context.Background()
|
||||
kid := "kid-cancel-invalid-utf8"
|
||||
now := time.Now()
|
||||
for _, r := range []*types.KnowledgeProcessingSpan{
|
||||
{KnowledgeID: kid, Attempt: 1, SpanID: "root", Name: "root", Kind: types.SpanKindRoot, Status: types.SpanStatusRunning, StartedAt: &now},
|
||||
{KnowledgeID: kid, Attempt: 1, SpanID: "descendant", ParentSpanID: "root", Name: "descendant", Kind: types.SpanKindSubSpan, Status: types.SpanStatusRunning, StartedAt: &now},
|
||||
{KnowledgeID: kid, Attempt: 1, SpanID: "bulk", Name: "bulk", Kind: types.SpanKindSubSpan, Status: types.SpanStatusRunning, StartedAt: &now},
|
||||
{KnowledgeID: kid, Attempt: 1, SpanID: "named", Name: "named", Kind: types.SpanKindSubSpan, Status: types.SpanStatusRunning, StartedAt: &now},
|
||||
} {
|
||||
require.NoError(t, repo.Upsert(ctx, r))
|
||||
}
|
||||
|
||||
invalidCode := "CODE " + string([]byte{0xef, 0xbc, 0x2e})
|
||||
invalidReason := "reason " + string([]byte{0xef, 0xbc, 0x2e})
|
||||
_, err := repo.CancelOpenSpansByName(ctx, kid, 1, "named", invalidCode, invalidReason)
|
||||
require.NoError(t, err)
|
||||
_, err = repo.CancelDescendants(ctx, kid, 1, "root", invalidReason)
|
||||
require.NoError(t, err)
|
||||
_, err = repo.CancelAllOpenSpans(ctx, kid, 1, invalidCode, invalidReason)
|
||||
require.NoError(t, err)
|
||||
|
||||
rows, err := repo.ListByAttempt(ctx, kid, 1)
|
||||
require.NoError(t, err)
|
||||
byID := make(map[string]types.KnowledgeProcessingSpan, len(rows))
|
||||
for _, row := range rows {
|
||||
byID[row.SpanID] = row
|
||||
}
|
||||
assert.Equal(t, "UPSTREAM_FAILED", byID["descendant"].ErrorCode)
|
||||
assert.Equal(t, "reason .", byID["descendant"].ErrorMessage)
|
||||
for _, id := range []string{"root", "bulk", "named"} {
|
||||
assert.Equal(t, "CODE .", byID[id].ErrorCode, id)
|
||||
assert.Equal(t, "reason .", byID[id].ErrorMessage, id)
|
||||
assert.True(t, utf8.ValidString(byID[id].ErrorCode), id)
|
||||
assert.True(t, utf8.ValidString(byID[id].ErrorMessage), id)
|
||||
}
|
||||
}
|
||||
|
||||
// TestKnowledgeSpanRepo_ListAttemptIsolation guarantees that different
|
||||
// attempts of the same knowledge stay queryable independently — the
|
||||
// foundation for the "show history" UI navigation (?attempt=N).
|
||||
func TestKnowledgeSpanRepo_ListAttemptIsolation(t *testing.T) {
|
||||
repo, _ := setupSpanTestRepo(t)
|
||||
ctx := context.Background()
|
||||
kid := "kid-history"
|
||||
now := time.Now()
|
||||
|
||||
for _, attempt := range []int{1, 2} {
|
||||
require.NoError(t, repo.Upsert(ctx, &types.KnowledgeProcessingSpan{
|
||||
KnowledgeID: kid, Attempt: attempt, SpanID: "root",
|
||||
Name: "knowledge_processing", Kind: types.SpanKindRoot,
|
||||
Status: types.SpanStatusDone, StartedAt: &now,
|
||||
}))
|
||||
}
|
||||
a1, err := repo.ListByAttempt(ctx, kid, 1)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, a1, 1)
|
||||
a2, err := repo.ListByAttempt(ctx, kid, 2)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, a2, 1)
|
||||
|
||||
all, err := repo.ListByAttempt(ctx, kid, 0)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, all, 2, "attempt=0 returns all attempts (used by housekeeping)")
|
||||
}
|
||||
|
||||
func TestKnowledgeSpanRepo_LastActivity(t *testing.T) {
|
||||
_, db := setupSpanTestRepo(t)
|
||||
repo := NewKnowledgeSpanRepository(db)
|
||||
ctx := context.Background()
|
||||
base := time.Date(2026, 9, 22, 10, 0, 0, 0, time.UTC)
|
||||
for i, at := range []time.Time{base, base.Add(7 * time.Minute), base.Add(3 * time.Minute)} {
|
||||
require.NoError(t, db.Exec(
|
||||
`INSERT INTO knowledge_processing_spans (knowledge_id, attempt, span_id, name, kind, status, updated_at)
|
||||
VALUES ('k-1', ?, ?, 'docreader', 'stage', 'running', ?)`, i+1, fmt.Sprintf("s-%d", i), at,
|
||||
).Error)
|
||||
}
|
||||
|
||||
got, err := repo.LastActivity(ctx, []string{"k-1", "k-none"})
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, got, "k-1")
|
||||
assert.True(t, got["k-1"].Equal(base.Add(7*time.Minute)), "got %s", got["k-1"])
|
||||
assert.NotContains(t, got, "k-none")
|
||||
|
||||
empty, err := repo.LastActivity(ctx, nil)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, empty)
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
// SetKnowledgeTags replaces all tags for a single knowledge entry.
|
||||
// It deletes existing relations and inserts new ones in a transaction.
|
||||
func (r *knowledgeRepository) SetKnowledgeTags(
|
||||
ctx context.Context,
|
||||
knowledgeID string,
|
||||
tagIDs []string,
|
||||
) error {
|
||||
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
// Delete all existing tag relations for this knowledge
|
||||
if err := tx.Where("knowledge_id = ?", knowledgeID).
|
||||
Delete(&types.KnowledgeTagRelation{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
// Insert new relations (skip empty and duplicate IDs)
|
||||
if len(tagIDs) == 0 {
|
||||
return nil
|
||||
}
|
||||
seen := make(map[string]struct{}, len(tagIDs))
|
||||
now := time.Now()
|
||||
relations := make([]types.KnowledgeTagRelation, 0, len(tagIDs))
|
||||
for _, tagID := range tagIDs {
|
||||
if tagID == "" {
|
||||
continue
|
||||
}
|
||||
if _, dup := seen[tagID]; dup {
|
||||
continue
|
||||
}
|
||||
seen[tagID] = struct{}{}
|
||||
relations = append(relations, types.KnowledgeTagRelation{
|
||||
KnowledgeID: knowledgeID,
|
||||
TagID: tagID,
|
||||
CreatedAt: now,
|
||||
})
|
||||
}
|
||||
if len(relations) == 0 {
|
||||
return nil
|
||||
}
|
||||
return tx.Create(&relations).Error
|
||||
})
|
||||
}
|
||||
|
||||
// AddKnowledgeTagRelations incrementally adds validated relations and never
|
||||
// removes existing manual tags. The composite primary key plus DO NOTHING
|
||||
// makes retries and duplicate deliveries idempotent.
|
||||
func (r *knowledgeRepository) AddKnowledgeTagRelations(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
kbID, knowledgeID string,
|
||||
tagIDs []string,
|
||||
) error {
|
||||
seen := make(map[string]struct{}, len(tagIDs))
|
||||
unique := make([]string, 0, len(tagIDs))
|
||||
for _, id := range tagIDs {
|
||||
if id == "" {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[id]; ok {
|
||||
continue
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
unique = append(unique, id)
|
||||
}
|
||||
if len(unique) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var knowledgeCount int64
|
||||
if err := tx.Model(&types.Knowledge{}).
|
||||
Where("id = ? AND tenant_id = ? AND knowledge_base_id = ? AND deleted_at IS NULL", knowledgeID, tenantID, kbID).
|
||||
Where("parse_status NOT IN ?", []string{
|
||||
types.ParseStatusCancelled,
|
||||
types.ParseStatusDeleting,
|
||||
types.ParseStatusFailed,
|
||||
}).
|
||||
Count(&knowledgeCount).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if knowledgeCount != 1 {
|
||||
return fmt.Errorf("knowledge %s does not belong to tenant %d and knowledge base %s", knowledgeID, tenantID, kbID)
|
||||
}
|
||||
|
||||
var tagCount int64
|
||||
if err := tx.Model(&types.KnowledgeTag{}).
|
||||
Where("tenant_id = ? AND knowledge_base_id = ? AND id IN ?", tenantID, kbID, unique).
|
||||
Count(&tagCount).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if tagCount != int64(len(unique)) {
|
||||
return fmt.Errorf("one or more tags do not belong to tenant %d and knowledge base %s", tenantID, kbID)
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
relations := make([]types.KnowledgeTagRelation, 0, len(unique))
|
||||
for _, tagID := range unique {
|
||||
relations = append(relations, types.KnowledgeTagRelation{
|
||||
KnowledgeID: knowledgeID,
|
||||
TagID: tagID,
|
||||
CreatedAt: now,
|
||||
})
|
||||
}
|
||||
return tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&relations).Error
|
||||
})
|
||||
}
|
||||
|
||||
// GetKnowledgeTags returns tags for multiple knowledge IDs.
|
||||
// The result is a map from knowledge ID to its tag list.
|
||||
func (r *knowledgeRepository) GetKnowledgeTags(
|
||||
ctx context.Context,
|
||||
knowledgeIDs []string,
|
||||
) (map[string][]*types.KnowledgeTag, error) {
|
||||
result := make(map[string][]*types.KnowledgeTag)
|
||||
if len(knowledgeIDs) == 0 {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Query relations and join with knowledge_tags to get full tag info
|
||||
type relationWithTag struct {
|
||||
KnowledgeID string `gorm:"column:knowledge_id"`
|
||||
types.KnowledgeTag
|
||||
}
|
||||
var rows []relationWithTag
|
||||
if err := r.db.WithContext(ctx).
|
||||
Table("knowledge_tag_relations AS ktr").
|
||||
Select("ktr.knowledge_id, kt.id, kt.seq_id, kt.tenant_id, kt.knowledge_base_id, kt.name, kt.color, kt.sort_order, kt.created_at, kt.updated_at").
|
||||
Joins("JOIN knowledge_tags AS kt ON ktr.tag_id = kt.id").
|
||||
Where("ktr.knowledge_id IN (?)", knowledgeIDs).
|
||||
Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, row := range rows {
|
||||
tag := row.KnowledgeTag
|
||||
result[row.KnowledgeID] = append(result[row.KnowledgeID], &tag)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// DeleteKnowledgeTagRelations deletes all tag relations for a knowledge entry.
|
||||
func (r *knowledgeRepository) DeleteKnowledgeTagRelations(
|
||||
ctx context.Context,
|
||||
knowledgeID string,
|
||||
) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Where("knowledge_id = ?", knowledgeID).
|
||||
Delete(&types.KnowledgeTagRelation{}).Error
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const knowledgeTagTestDDL = `
|
||||
CREATE TABLE IF NOT EXISTS knowledges (
|
||||
profile TEXT,
|
||||
id VARCHAR(36) PRIMARY KEY,
|
||||
tenant_id INTEGER NOT NULL,
|
||||
knowledge_base_id VARCHAR(36) NOT NULL,
|
||||
type VARCHAR(50) NOT NULL DEFAULT 'file',
|
||||
title VARCHAR(255) NOT NULL DEFAULT '',
|
||||
parse_status VARCHAR(50) NOT NULL DEFAULT 'completed',
|
||||
deleted_at DATETIME
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS knowledge_tags (
|
||||
id VARCHAR(36) PRIMARY KEY,
|
||||
seq_id INTEGER NOT NULL,
|
||||
tenant_id INTEGER NOT NULL,
|
||||
knowledge_base_id VARCHAR(36) NOT NULL,
|
||||
name VARCHAR(128) NOT NULL,
|
||||
color VARCHAR(32),
|
||||
sort_order INTEGER NOT NULL DEFAULT 0,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS knowledge_tag_relations (
|
||||
knowledge_id VARCHAR(36) NOT NULL,
|
||||
tag_id VARCHAR(36) NOT NULL,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (knowledge_id, tag_id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS chunks (
|
||||
id VARCHAR(36) PRIMARY KEY,
|
||||
tenant_id INTEGER NOT NULL,
|
||||
knowledge_base_id VARCHAR(36) NOT NULL,
|
||||
tag_id VARCHAR(36),
|
||||
deleted_at DATETIME
|
||||
);
|
||||
`
|
||||
|
||||
func setupKnowledgeTagTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db := setupKnowledgeTestDB(t)
|
||||
require.NoError(t, db.Exec(knowledgeTagTestDDL).Error)
|
||||
return db
|
||||
}
|
||||
|
||||
func seedKnowledgeTagFixture(t *testing.T, db *gorm.DB) (kbID, knowledgeID, tagA, tagB string) {
|
||||
t.Helper()
|
||||
kbID = uuid.New().String()
|
||||
knowledgeID = uuid.New().String()
|
||||
tagA = uuid.New().String()
|
||||
tagB = uuid.New().String()
|
||||
require.NoError(t, db.Exec(`
|
||||
INSERT INTO knowledges (id, tenant_id, knowledge_base_id, type, title, parse_status)
|
||||
VALUES (?, 1, ?, 'file', 'doc', 'completed')
|
||||
`, knowledgeID, kbID).Error)
|
||||
require.NoError(t, db.Exec(`
|
||||
INSERT INTO knowledge_tags (id, seq_id, tenant_id, knowledge_base_id, name)
|
||||
VALUES (?, 1, 1, ?, 'alpha'), (?, 2, 1, ?, 'beta')
|
||||
`, tagA, kbID, tagB, kbID).Error)
|
||||
return kbID, knowledgeID, tagA, tagB
|
||||
}
|
||||
|
||||
func TestSetKnowledgeTags_DedupesAndReplaces(t *testing.T) {
|
||||
db := setupKnowledgeTagTestDB(t)
|
||||
repo := &knowledgeRepository{db: db}
|
||||
_, knowledgeID, tagA, tagB := seedKnowledgeTagFixture(t, db)
|
||||
ctx := context.Background()
|
||||
|
||||
err := repo.SetKnowledgeTags(ctx, knowledgeID, []string{tagA, tagA, tagB})
|
||||
require.NoError(t, err)
|
||||
|
||||
var count int64
|
||||
require.NoError(t, db.Model(&types.KnowledgeTagRelation{}).
|
||||
Where("knowledge_id = ?", knowledgeID).Count(&count).Error)
|
||||
assert.Equal(t, int64(2), count)
|
||||
|
||||
err = repo.SetKnowledgeTags(ctx, knowledgeID, []string{tagB})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.Model(&types.KnowledgeTagRelation{}).
|
||||
Where("knowledge_id = ?", knowledgeID).Count(&count).Error)
|
||||
assert.Equal(t, int64(1), count)
|
||||
|
||||
err = repo.SetKnowledgeTags(ctx, knowledgeID, nil)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.Model(&types.KnowledgeTagRelation{}).
|
||||
Where("knowledge_id = ?", knowledgeID).Count(&count).Error)
|
||||
assert.Equal(t, int64(0), count)
|
||||
}
|
||||
|
||||
func TestAddKnowledgeTagRelations_IsIncrementalIdempotentAndScoped(t *testing.T) {
|
||||
db := setupKnowledgeTagTestDB(t)
|
||||
repo := &knowledgeRepository{db: db}
|
||||
kbID, knowledgeID, tagA, tagB := seedKnowledgeTagFixture(t, db)
|
||||
ctx := context.Background()
|
||||
|
||||
require.NoError(t, repo.SetKnowledgeTags(ctx, knowledgeID, []string{tagA}))
|
||||
require.NoError(t, repo.AddKnowledgeTagRelations(ctx, 1, kbID, knowledgeID, []string{tagA, tagB, tagB}))
|
||||
require.NoError(t, repo.AddKnowledgeTagRelations(ctx, 1, kbID, knowledgeID, []string{tagB}))
|
||||
|
||||
var relations []types.KnowledgeTagRelation
|
||||
require.NoError(t, db.Where("knowledge_id = ?", knowledgeID).Find(&relations).Error)
|
||||
assert.Len(t, relations, 2)
|
||||
|
||||
otherKBTag := uuid.New().String()
|
||||
require.NoError(t, db.Exec(`
|
||||
INSERT INTO knowledge_tags (id, seq_id, tenant_id, knowledge_base_id, name)
|
||||
VALUES (?, 3, 1, ?, 'other')
|
||||
`, otherKBTag, uuid.New().String()).Error)
|
||||
err := repo.AddKnowledgeTagRelations(ctx, 1, kbID, knowledgeID, []string{otherKBTag})
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func TestAddKnowledgeTagRelations_RejectsCancelledKnowledge(t *testing.T) {
|
||||
db := setupKnowledgeTagTestDB(t)
|
||||
repo := &knowledgeRepository{db: db}
|
||||
kbID, knowledgeID, _, tagB := seedKnowledgeTagFixture(t, db)
|
||||
require.NoError(t, db.Model(&types.Knowledge{}).
|
||||
Where("id = ?", knowledgeID).
|
||||
Update("parse_status", types.ParseStatusCancelled).Error)
|
||||
|
||||
err := repo.AddKnowledgeTagRelations(context.Background(), 1, kbID, knowledgeID, []string{tagB})
|
||||
require.Error(t, err)
|
||||
|
||||
var count int64
|
||||
require.NoError(t, db.Model(&types.KnowledgeTagRelation{}).
|
||||
Where("knowledge_id = ?", knowledgeID).
|
||||
Count(&count).Error)
|
||||
assert.Zero(t, count)
|
||||
}
|
||||
|
||||
func TestGetKnowledgeTags_ReturnsTagDetails(t *testing.T) {
|
||||
db := setupKnowledgeTagTestDB(t)
|
||||
repo := &knowledgeRepository{db: db}
|
||||
_, knowledgeID, tagA, tagB := seedKnowledgeTagFixture(t, db)
|
||||
ctx := context.Background()
|
||||
|
||||
require.NoError(t, repo.SetKnowledgeTags(ctx, knowledgeID, []string{tagA, tagB}))
|
||||
|
||||
tagMap, err := repo.GetKnowledgeTags(ctx, []string{knowledgeID})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, tagMap[knowledgeID], 2)
|
||||
|
||||
names := map[string]bool{}
|
||||
for _, tag := range tagMap[knowledgeID] {
|
||||
names[tag.Name] = true
|
||||
}
|
||||
assert.True(t, names["alpha"])
|
||||
assert.True(t, names["beta"])
|
||||
}
|
||||
|
||||
func TestDeleteKnowledgeTagRelations(t *testing.T) {
|
||||
db := setupKnowledgeTagTestDB(t)
|
||||
repo := &knowledgeRepository{db: db}
|
||||
_, knowledgeID, tagA, _ := seedKnowledgeTagFixture(t, db)
|
||||
ctx := context.Background()
|
||||
|
||||
require.NoError(t, repo.SetKnowledgeTags(ctx, knowledgeID, []string{tagA}))
|
||||
require.NoError(t, repo.DeleteKnowledgeTagRelations(ctx, knowledgeID))
|
||||
|
||||
var count int64
|
||||
require.NoError(t, db.Model(&types.KnowledgeTagRelation{}).
|
||||
Where("knowledge_id = ?", knowledgeID).Count(&count).Error)
|
||||
assert.Equal(t, int64(0), count)
|
||||
}
|
||||
|
||||
func TestApplyKnowledgeListFilter_TagIDsOrSemantics(t *testing.T) {
|
||||
db := setupKnowledgeTagTestDB(t)
|
||||
repo := &knowledgeRepository{db: db}
|
||||
ctx := context.Background()
|
||||
|
||||
kbID := uuid.New().String()
|
||||
docA := uuid.New().String()
|
||||
docB := uuid.New().String()
|
||||
docC := uuid.New().String()
|
||||
tagA := uuid.New().String()
|
||||
tagB := uuid.New().String()
|
||||
|
||||
for _, row := range []struct{ id, title string }{
|
||||
{docA, "a"}, {docB, "b"}, {docC, "c"},
|
||||
} {
|
||||
require.NoError(t, db.Exec(`
|
||||
INSERT INTO knowledges (id, tenant_id, knowledge_base_id, type, title, parse_status)
|
||||
VALUES (?, 1, ?, 'file', ?, 'completed')
|
||||
`, row.id, kbID, row.title).Error)
|
||||
}
|
||||
require.NoError(t, db.Exec(`
|
||||
INSERT INTO knowledge_tags (id, seq_id, tenant_id, knowledge_base_id, name)
|
||||
VALUES (?, 1, 1, ?, 't-a'), (?, 2, 1, ?, 't-b')
|
||||
`, tagA, kbID, tagB, kbID).Error)
|
||||
require.NoError(t, repo.SetKnowledgeTags(ctx, docA, []string{tagA}))
|
||||
require.NoError(t, repo.SetKnowledgeTags(ctx, docB, []string{tagB}))
|
||||
require.NoError(t, repo.SetKnowledgeTags(ctx, docC, []string{tagA, tagB}))
|
||||
|
||||
query := db.WithContext(ctx).Model(&types.Knowledge{}).
|
||||
Where("tenant_id = ? AND knowledge_base_id = ?", uint64(1), kbID)
|
||||
query = applyKnowledgeListFilter(query, types.KnowledgeListFilter{
|
||||
TagIDs: []string{tagA, tagB},
|
||||
})
|
||||
|
||||
var ids []string
|
||||
require.NoError(t, query.Pluck("id", &ids).Error)
|
||||
assert.ElementsMatch(t, []string{docA, docB, docC}, ids)
|
||||
}
|
||||
|
||||
func TestBatchCountReferences_ScopedToKnowledgeBase(t *testing.T) {
|
||||
db := setupKnowledgeTagTestDB(t)
|
||||
knowledgeRepo := &knowledgeRepository{db: db}
|
||||
tagRepo := &knowledgeTagRepository{db: db}
|
||||
ctx := context.Background()
|
||||
|
||||
kb1 := uuid.New().String()
|
||||
kb2 := uuid.New().String()
|
||||
doc1 := uuid.New().String()
|
||||
doc2 := uuid.New().String()
|
||||
tag1 := uuid.New().String()
|
||||
tag2 := uuid.New().String()
|
||||
|
||||
require.NoError(t, db.Exec(`
|
||||
INSERT INTO knowledges (id, tenant_id, knowledge_base_id, type, title, parse_status)
|
||||
VALUES (?, 1, ?, 'file', 'kb1-doc', 'completed'), (?, 1, ?, 'file', 'kb2-doc', 'completed')
|
||||
`, doc1, kb1, doc2, kb2).Error)
|
||||
require.NoError(t, db.Exec(`
|
||||
INSERT INTO knowledge_tags (id, seq_id, tenant_id, knowledge_base_id, name)
|
||||
VALUES (?, 1, 1, ?, 'tag-kb1'), (?, 2, 1, ?, 'tag-kb2')
|
||||
`, tag1, kb1, tag2, kb2).Error)
|
||||
require.NoError(t, knowledgeRepo.SetKnowledgeTags(ctx, doc1, []string{tag1}))
|
||||
// Stale relation: doc in kb2 still linked to tag1 (simulates pre-fix move bug)
|
||||
require.NoError(t, knowledgeRepo.SetKnowledgeTags(ctx, doc2, []string{tag1}))
|
||||
|
||||
counts, err := tagRepo.BatchCountReferences(ctx, 1, kb1, []string{tag1})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(1), counts[tag1].KnowledgeCount)
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// UpdateKnowledgeForTransfer is a compare-and-swap checkpoint. Full-row Save
|
||||
// could resurrect a deleted document or overwrite a concurrently moved row.
|
||||
// Accounting changes are committed with the checkpoint, making retry cleanup
|
||||
// safe even if the worker crashes between the database and queue operations.
|
||||
func (r *knowledgeRepository) UpdateKnowledgeForTransfer(ctx context.Context, before, after *types.Knowledge) error {
|
||||
if before == nil || after == nil || before.ID == "" || before.ID != after.ID || before.TenantID == 0 ||
|
||||
before.TenantID != after.TenantID {
|
||||
return fmt.Errorf("invalid knowledge transfer checkpoint")
|
||||
}
|
||||
// PostgreSQL persists timestamps at microsecond precision. Keep the returned
|
||||
// checkpoint identical to storage so the next CAS in this task can match it.
|
||||
after.UpdatedAt = time.Now().UTC().Truncate(time.Microsecond)
|
||||
var storedUpdatedAt time.Time
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
result := tx.Model(&types.Knowledge{}).
|
||||
Where("id = ? AND tenant_id = ? AND knowledge_base_id = ? AND parse_status = ? AND "+
|
||||
"updated_at = ?",
|
||||
before.ID,
|
||||
before.TenantID,
|
||||
before.KnowledgeBaseID,
|
||||
before.ParseStatus,
|
||||
before.UpdatedAt).
|
||||
Updates(map[string]any{
|
||||
"knowledge_base_id": after.KnowledgeBaseID, "parse_status": after.ParseStatus,
|
||||
"metadata": after.Metadata, "storage_size": after.StorageSize, "updated_at": after.UpdatedAt,
|
||||
"enable_status": after.EnableStatus, "embedding_model_id": after.EmbeddingModelID,
|
||||
"description": after.Description,
|
||||
"processed_at": after.ProcessedAt,
|
||||
"error_message": after.ErrorMessage,
|
||||
})
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected != 1 {
|
||||
return fmt.Errorf("knowledge changed during transfer")
|
||||
}
|
||||
delta := after.StorageSize - before.StorageSize
|
||||
if delta != 0 {
|
||||
result := tx.Model(&types.Tenant{}).Where("id = ?", before.TenantID).
|
||||
UpdateColumn("storage_used",
|
||||
gorm.Expr("CASE WHEN storage_used + ? < 0 THEN 0 ELSE storage_used + ? END",
|
||||
delta,
|
||||
delta))
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected != 1 {
|
||||
return fmt.Errorf("transfer tenant not found")
|
||||
}
|
||||
}
|
||||
var stored struct{ UpdatedAt time.Time }
|
||||
if err := tx.Model(&types.Knowledge{}).Select("updated_at").
|
||||
Where("id = ? AND tenant_id = ?", after.ID, after.TenantID).Take(&stored).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
storedUpdatedAt = stored.UpdatedAt
|
||||
return nil
|
||||
})
|
||||
if err == nil {
|
||||
after.UpdatedAt = storedUpdatedAt
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestTransferCheckpointReturnsStoredTimestampPrecision(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
// Emulate a database that stores fewer fractional digits than time.Now.
|
||||
require.NoError(t, db.Exec(`CREATE TRIGGER truncate_checkpoint_time AFTER UPDATE ON knowledges
|
||||
BEGIN UPDATE knowledges SET updated_at = strftime('%Y-%m-%d %H:%M:%S', NEW.updated_at) || '+00:00'
|
||||
WHERE id = NEW.id; END`).Error)
|
||||
row := &types.Knowledge{ID: "doc", TenantID: 7, KnowledgeBaseID: "source", ParseStatus: types.ParseStatusCompleted}
|
||||
require.NoError(t, db.Omit("custom_metadata").Create(row).Error)
|
||||
repo := NewKnowledgeRepository(db)
|
||||
before, err := repo.GetKnowledgeByID(context.Background(), 7, "doc")
|
||||
require.NoError(t, err)
|
||||
after := *before
|
||||
after.ParseStatus = types.ParseStatusProcessing
|
||||
require.NoError(t, repo.UpdateKnowledgeForTransfer(context.Background(), before, &after))
|
||||
require.Zero(t, after.UpdatedAt.Nanosecond())
|
||||
final := after
|
||||
final.KnowledgeBaseID = "target"
|
||||
final.ParseStatus = types.ParseStatusCompleted
|
||||
require.NoError(t, repo.UpdateKnowledgeForTransfer(context.Background(), &after, &final))
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var ErrKnowledgeBaseNotFound = errors.New("knowledge base not found")
|
||||
|
||||
// knowledgeBaseRepository implements the KnowledgeBaseRepository interface
|
||||
type knowledgeBaseRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewKnowledgeBaseRepository creates a new knowledge base repository
|
||||
func NewKnowledgeBaseRepository(db *gorm.DB) interfaces.KnowledgeBaseRepository {
|
||||
return &knowledgeBaseRepository{db: db}
|
||||
}
|
||||
|
||||
// CreateKnowledgeBase creates a new knowledge base
|
||||
func (r *knowledgeBaseRepository) CreateKnowledgeBase(ctx context.Context, kb *types.KnowledgeBase) error {
|
||||
return r.db.WithContext(ctx).Create(kb).Error
|
||||
}
|
||||
|
||||
// GetKnowledgeBaseByID gets a knowledge base by id (no tenant scope; caller must enforce isolation where needed)
|
||||
func (r *knowledgeBaseRepository) GetKnowledgeBaseByID(ctx context.Context, id string) (*types.KnowledgeBase, error) {
|
||||
var kb types.KnowledgeBase
|
||||
if err := r.db.WithContext(ctx).Where("id = ?", id).First(&kb).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrKnowledgeBaseNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &kb, nil
|
||||
}
|
||||
|
||||
// GetKnowledgeBaseByIDAndTenant gets a knowledge base by id only if it belongs to the given tenant (enforces tenant isolation)
|
||||
func (r *knowledgeBaseRepository) GetKnowledgeBaseByIDAndTenant(ctx context.Context, id string, tenantID uint64) (*types.KnowledgeBase, error) {
|
||||
var kb types.KnowledgeBase
|
||||
if err := r.db.WithContext(ctx).Where("id = ? AND tenant_id = ?", id, tenantID).First(&kb).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrKnowledgeBaseNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &kb, nil
|
||||
}
|
||||
|
||||
// GetKnowledgeBaseByIDs gets knowledge bases by multiple ids
|
||||
func (r *knowledgeBaseRepository) GetKnowledgeBaseByIDs(ctx context.Context, ids []string) ([]*types.KnowledgeBase, error) {
|
||||
if len(ids) == 0 {
|
||||
return []*types.KnowledgeBase{}, nil
|
||||
}
|
||||
var kbs []*types.KnowledgeBase
|
||||
if err := r.db.WithContext(ctx).Where("id IN ?", ids).Find(&kbs).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return kbs, nil
|
||||
}
|
||||
|
||||
// ListKnowledgeBases lists all knowledge bases
|
||||
func (r *knowledgeBaseRepository) ListKnowledgeBases(ctx context.Context) ([]*types.KnowledgeBase, error) {
|
||||
var kbs []*types.KnowledgeBase
|
||||
if err := r.db.WithContext(ctx).Find(&kbs).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return kbs, nil
|
||||
}
|
||||
|
||||
// ListKnowledgeBasesByTenantID lists all knowledge bases by tenant id.
|
||||
//
|
||||
// Ordering used to also include `is_pinned DESC, pinned_at DESC` so the
|
||||
// repository would return tenant-wide pinned rows first. That column is
|
||||
// no longer the source of truth (see migration 000050) — pin state is
|
||||
// now per (user, kb) and applied by the service layer after enrichment.
|
||||
// We keep `created_at DESC` here so callers that don't enrich (chat
|
||||
// pipeline, agent editor, IM commands) still get a stable ordering.
|
||||
func (r *knowledgeBaseRepository) ListKnowledgeBasesByTenantID(
|
||||
ctx context.Context, tenantID uint64,
|
||||
) ([]*types.KnowledgeBase, error) {
|
||||
var kbs []*types.KnowledgeBase
|
||||
if err := r.db.WithContext(ctx).Where("tenant_id = ? AND is_temporary = ?", tenantID, false).
|
||||
Order("created_at DESC").Find(&kbs).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return kbs, nil
|
||||
}
|
||||
|
||||
// userKBPinRow mirrors the user_kb_pins table. Kept local to the
|
||||
// repository because it never escapes the package; callers see the
|
||||
// higher-level map[kb_id]pinned_at returned by ListUserKBPinIDs.
|
||||
type userKBPinRow struct {
|
||||
TenantID uint64 `gorm:"column:tenant_id"`
|
||||
UserID string `gorm:"column:user_id"`
|
||||
KBID string `gorm:"column:kb_id"`
|
||||
PinnedAt time.Time `gorm:"column:pinned_at"`
|
||||
}
|
||||
|
||||
func (userKBPinRow) TableName() string { return "user_kb_pins" }
|
||||
|
||||
// SetUserKBPin upserts (pinned=true) or deletes (pinned=false) the row
|
||||
// for the given (tenant, user, kb) triple. The returned pinned_at is
|
||||
// nil when pinned=false; otherwise it carries the timestamp written
|
||||
// to the row (either the existing one if the row already existed, or
|
||||
// the current time on insert) so the caller can stamp the response
|
||||
// without a follow-up SELECT.
|
||||
func (r *knowledgeBaseRepository) SetUserKBPin(
|
||||
ctx context.Context, tenantID uint64, userID string, kbID string, pinned bool,
|
||||
) (*time.Time, error) {
|
||||
if userID == "" {
|
||||
return nil, errors.New("user_kb_pins: empty user_id")
|
||||
}
|
||||
if !pinned {
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND user_id = ? AND kb_id = ?", tenantID, userID, kbID).
|
||||
Delete(&userKBPinRow{}).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// Upsert with idempotent INSERT … ON CONFLICT DO NOTHING. We then
|
||||
// SELECT to learn whether an existing row's pinned_at survived (so
|
||||
// repeated calls return a stable timestamp instead of bumping it).
|
||||
row := userKBPinRow{
|
||||
TenantID: tenantID,
|
||||
UserID: userID,
|
||||
KBID: kbID,
|
||||
PinnedAt: time.Now(),
|
||||
}
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND user_id = ? AND kb_id = ?", tenantID, userID, kbID).
|
||||
Attrs(userKBPinRow{PinnedAt: row.PinnedAt}).
|
||||
FirstOrCreate(&row).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pa := row.PinnedAt
|
||||
return &pa, nil
|
||||
}
|
||||
|
||||
// ListUserKBPinIDs returns every KB id this user has personally pinned
|
||||
// in this tenant, mapped to its pinned_at. Returns an empty map (not
|
||||
// nil) when there are no pins, so callers can do `len(m) == 0` checks
|
||||
// without a nil guard.
|
||||
func (r *knowledgeBaseRepository) ListUserKBPinIDs(
|
||||
ctx context.Context, tenantID uint64, userID string,
|
||||
) (map[string]time.Time, error) {
|
||||
out := make(map[string]time.Time)
|
||||
if userID == "" {
|
||||
return out, nil
|
||||
}
|
||||
var rows []userKBPinRow
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND user_id = ?", tenantID, userID).
|
||||
Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, row := range rows {
|
||||
out[row.KBID] = row.PinnedAt
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// UpdateKnowledgeBase updates a knowledge base
|
||||
func (r *knowledgeBaseRepository) UpdateKnowledgeBase(ctx context.Context, kb *types.KnowledgeBase) error {
|
||||
return r.db.WithContext(ctx).Save(kb).Error
|
||||
}
|
||||
|
||||
// UpdateKnowledgeBaseGeneratedProfile writes the generated_profile column
|
||||
// only. The rest of the row is left untouched so a settings save that lands
|
||||
// while a profile is being generated is not overwritten by the worker.
|
||||
func (r *knowledgeBaseRepository) UpdateKnowledgeBaseGeneratedProfile(
|
||||
ctx context.Context, id string, profile *types.KnowledgeBaseProfile,
|
||||
) error {
|
||||
if id == "" {
|
||||
return errors.New("knowledge base ID cannot be empty")
|
||||
}
|
||||
var value interface{}
|
||||
if profile != nil {
|
||||
value = *profile
|
||||
}
|
||||
return r.db.WithContext(ctx).Model(&types.KnowledgeBase{}).
|
||||
Where("id = ?", id).
|
||||
Updates(map[string]interface{}{
|
||||
"generated_profile": value,
|
||||
"updated_at": time.Now(),
|
||||
}).Error
|
||||
}
|
||||
|
||||
// DeleteKnowledgeBase deletes a knowledge base
|
||||
func (r *knowledgeBaseRepository) DeleteKnowledgeBase(ctx context.Context, id string) error {
|
||||
return r.db.WithContext(ctx).Where("id = ?", id).Delete(&types.KnowledgeBase{}).Error
|
||||
}
|
||||
|
||||
// CountByVectorStoreID counts active knowledge bases that are bound to the
|
||||
// given vector store within a tenant scope.
|
||||
//
|
||||
// Soft-delete filter is applied automatically by GORM because KnowledgeBase
|
||||
// has a gorm.DeletedAt column — we deliberately do not add an explicit
|
||||
// `deleted_at IS NULL` predicate to keep the single source of truth on the
|
||||
// auto-scope.
|
||||
//
|
||||
// Pass db == nil to use the repository's default db handle; pass a *gorm.DB
|
||||
// bound to a transaction (e.g., from db.Transaction) to share the same
|
||||
// write-lock context as the caller. Query column order matches the
|
||||
// composite index idx_knowledge_bases_tenant_vector_store(tenant_id,
|
||||
// vector_store_id).
|
||||
func (r *knowledgeBaseRepository) CountByVectorStoreID(
|
||||
ctx context.Context, db *gorm.DB, tenantID uint64, storeID string,
|
||||
) (int64, error) {
|
||||
if db == nil {
|
||||
db = r.db
|
||||
}
|
||||
var count int64
|
||||
err := db.WithContext(ctx).
|
||||
Model(&types.KnowledgeBase{}).
|
||||
Where("tenant_id = ? AND vector_store_id = ?", tenantID, storeID).
|
||||
Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
// CountByModelID counts active knowledge bases that reference modelID in any
|
||||
// model-binding column (scalar fields or JSON config blobs).
|
||||
func (r *knowledgeBaseRepository) CountByModelID(
|
||||
ctx context.Context, tenantID uint64, modelID string,
|
||||
) (int64, error) {
|
||||
var count int64
|
||||
query := r.db.WithContext(ctx).
|
||||
Model(&types.KnowledgeBase{}).
|
||||
Where("tenant_id = ?", tenantID)
|
||||
query = scopeKnowledgeBasesByModelID(query, modelID)
|
||||
err := query.Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
// ListModelUsages returns active knowledge bases that reference modelID. It
|
||||
// selects only the columns needed to identify the resource and its bindings;
|
||||
// GORM's default scope excludes soft-deleted rows.
|
||||
func (r *knowledgeBaseRepository) ListModelUsages(
|
||||
ctx context.Context, tenantID uint64, modelID string,
|
||||
) ([]types.ModelUsageResource, error) {
|
||||
rows := make([]*types.KnowledgeBase, 0)
|
||||
query := r.db.WithContext(ctx).
|
||||
Model(&types.KnowledgeBase{}).
|
||||
Select(
|
||||
"id", "name", "embedding_model_id", "summary_model_id",
|
||||
"image_processing_config", "vlm_config", "asr_config", "wiki_config", "auto_tag_config",
|
||||
).
|
||||
Where("tenant_id = ?", tenantID)
|
||||
query = scopeKnowledgeBasesByModelID(query, modelID)
|
||||
if err := query.Order("name ASC, id ASC").Limit(types.ModelUsageListLimit).Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
usages := make([]types.ModelUsageResource, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
bindings := knowledgeBaseModelUsageBindings(row, modelID)
|
||||
if len(bindings) == 0 {
|
||||
continue
|
||||
}
|
||||
usages = append(usages, types.ModelUsageResource{
|
||||
ID: row.ID,
|
||||
Name: row.Name,
|
||||
Bindings: bindings,
|
||||
})
|
||||
}
|
||||
return usages, nil
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// knowledgeBasesTestDDL mirrors the `knowledge_bases` section of
|
||||
// migrations/sqlite/000000_init.up.sql. We inline the DDL here instead of
|
||||
// using GORM AutoMigrate because KnowledgeBase carries fields tagged with
|
||||
// `type:jsonb`, which AutoMigrate does not map cleanly onto SQLite.
|
||||
const knowledgeBasesTestDDL = `
|
||||
CREATE TABLE IF NOT EXISTS knowledge_bases (
|
||||
profile_config TEXT,
|
||||
generated_profile TEXT,
|
||||
id VARCHAR(36) PRIMARY KEY,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
description TEXT,
|
||||
tenant_id INTEGER NOT NULL,
|
||||
type VARCHAR(32) NOT NULL DEFAULT 'document',
|
||||
chunking_config TEXT NOT NULL DEFAULT '{}',
|
||||
image_processing_config TEXT NOT NULL DEFAULT '{}',
|
||||
embedding_model_id VARCHAR(64) NOT NULL,
|
||||
summary_model_id VARCHAR(64) NOT NULL,
|
||||
cos_config TEXT NOT NULL DEFAULT '{}',
|
||||
storage_provider_config TEXT DEFAULT NULL,
|
||||
vlm_config TEXT NOT NULL DEFAULT '{}',
|
||||
extract_config TEXT NULL DEFAULT NULL,
|
||||
faq_config TEXT,
|
||||
question_generation_config TEXT NULL,
|
||||
auto_tag_config TEXT NULL,
|
||||
is_temporary BOOLEAN NOT NULL DEFAULT 0,
|
||||
is_pinned INTEGER NOT NULL DEFAULT 0,
|
||||
pinned_at DATETIME NULL,
|
||||
asr_config TEXT,
|
||||
vector_store_id VARCHAR(36),
|
||||
storage_backend_id VARCHAR(36),
|
||||
wiki_config TEXT,
|
||||
indexing_strategy TEXT,
|
||||
creator_id VARCHAR(36),
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
deleted_at DATETIME
|
||||
);
|
||||
`
|
||||
|
||||
// setupKBTestDB creates an in-memory SQLite database containing the
|
||||
// knowledge_bases table with the vector_store_id column included, so that
|
||||
// tests can exercise the GORM behavior of the VectorStoreID field.
|
||||
func setupKBTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.Exec(knowledgeBasesTestDDL).Error)
|
||||
return db
|
||||
}
|
||||
|
||||
// makeKB builds a minimal KnowledgeBase suitable for insert. Only the columns
|
||||
// required by the schema above and any field we explicitly care about are set;
|
||||
// the rest are left at their Go zero values and serialize to "{}" via their
|
||||
// custom JSON valuers.
|
||||
func makeKB(vectorStoreID *string) *types.KnowledgeBase {
|
||||
return &types.KnowledgeBase{
|
||||
ID: uuid.New().String(),
|
||||
Name: "test-kb",
|
||||
TenantID: 1,
|
||||
EmbeddingModelID: "test-embed",
|
||||
SummaryModelID: "test-summary",
|
||||
VectorStoreID: vectorStoreID,
|
||||
}
|
||||
}
|
||||
|
||||
func kbStrPtr(s string) *string { return &s }
|
||||
|
||||
// reloadKB fetches the KnowledgeBase back from the database using its ID.
|
||||
func reloadKB(t *testing.T, db *gorm.DB, id string) types.KnowledgeBase {
|
||||
t.Helper()
|
||||
var got types.KnowledgeBase
|
||||
require.NoError(t, db.First(&got, "id = ?", id).Error)
|
||||
return got
|
||||
}
|
||||
|
||||
// TestKnowledgeBase_VectorStoreID_Save_Immutable verifies that db.Save(kb)
|
||||
// — which Academy's UpdateKnowledgeBase repository path uses today — does
|
||||
// NOT overwrite the vector_store_id column, thanks to the GORM
|
||||
// `<-:create` tag. This is the primary automated defense for the H1 review
|
||||
// finding (silent overwrite of the binding via full-struct UPDATE).
|
||||
func TestKnowledgeBase_VectorStoreID_Save_Immutable(t *testing.T) {
|
||||
db := setupKBTestDB(t)
|
||||
|
||||
original := makeKB(kbStrPtr("store-A"))
|
||||
require.NoError(t, db.Create(original).Error)
|
||||
|
||||
// Attempt to overwrite through the canonical Save() path.
|
||||
mutated := *original
|
||||
mutated.Name = "updated-name"
|
||||
mutated.VectorStoreID = kbStrPtr("store-B")
|
||||
require.NoError(t, db.Save(&mutated).Error)
|
||||
|
||||
reloaded := reloadKB(t, db, original.ID)
|
||||
|
||||
// Non-immutable fields must update.
|
||||
assert.Equal(t, "updated-name", reloaded.Name, "Name must update through Save")
|
||||
|
||||
// Immutable field must NOT update.
|
||||
require.NotNil(t, reloaded.VectorStoreID, "VectorStoreID must remain set to the original value")
|
||||
assert.Equal(t, "store-A", *reloaded.VectorStoreID,
|
||||
"db.Save must not overwrite vector_store_id (enforced by GORM `<-:create` tag)")
|
||||
}
|
||||
|
||||
// TestKnowledgeBase_VectorStoreID_Updates_Immutable verifies that
|
||||
// db.Updates(struct{...}) also honors `<-:create` and silently ignores the
|
||||
// vector_store_id column.
|
||||
func TestKnowledgeBase_VectorStoreID_Updates_Immutable(t *testing.T) {
|
||||
db := setupKBTestDB(t)
|
||||
|
||||
original := makeKB(kbStrPtr("store-A"))
|
||||
require.NoError(t, db.Create(original).Error)
|
||||
|
||||
// Partial struct update that includes vector_store_id must not take effect.
|
||||
err := db.Model(&types.KnowledgeBase{}).
|
||||
Where("id = ?", original.ID).
|
||||
Updates(types.KnowledgeBase{
|
||||
Name: "updated-name",
|
||||
VectorStoreID: kbStrPtr("store-B"),
|
||||
}).Error
|
||||
require.NoError(t, err)
|
||||
|
||||
reloaded := reloadKB(t, db, original.ID)
|
||||
|
||||
assert.Equal(t, "updated-name", reloaded.Name)
|
||||
require.NotNil(t, reloaded.VectorStoreID)
|
||||
assert.Equal(t, "store-A", *reloaded.VectorStoreID,
|
||||
"db.Updates must not overwrite vector_store_id (enforced by GORM `<-:create` tag)")
|
||||
}
|
||||
|
||||
// TestKnowledgeBase_VectorStoreID_Select_StillImmutable verifies that even
|
||||
// an explicit Select("vector_store_id").Updates(...) does NOT bypass the
|
||||
// `<-:create` tag. GORM's `<-:create` is strict: it withholds write
|
||||
// permission from every UPDATE path, including selective updates. This is
|
||||
// a stronger guarantee than a typical "column is protected unless you
|
||||
// opt in" scheme.
|
||||
//
|
||||
// The implication for Phase 4 (cross-store migration) is that ORM-level
|
||||
// updates cannot move bindings. Migration code must use raw SQL (db.Exec)
|
||||
// — see TestKnowledgeBase_VectorStoreID_RawSQL_EscapeHatch below.
|
||||
func TestKnowledgeBase_VectorStoreID_Select_StillImmutable(t *testing.T) {
|
||||
db := setupKBTestDB(t)
|
||||
|
||||
original := makeKB(kbStrPtr("store-A"))
|
||||
require.NoError(t, db.Create(original).Error)
|
||||
|
||||
err := db.Model(&types.KnowledgeBase{}).
|
||||
Where("id = ?", original.ID).
|
||||
Select("vector_store_id").
|
||||
Updates(map[string]interface{}{"vector_store_id": "store-B"}).Error
|
||||
require.NoError(t, err)
|
||||
|
||||
reloaded := reloadKB(t, db, original.ID)
|
||||
require.NotNil(t, reloaded.VectorStoreID)
|
||||
assert.Equal(t, "store-A", *reloaded.VectorStoreID,
|
||||
"Select(\"vector_store_id\").Updates must NOT bypass <-:create; ORM is fully locked")
|
||||
}
|
||||
|
||||
// TestKnowledgeBase_VectorStoreID_RawSQL_EscapeHatch documents that raw
|
||||
// SQL UPDATE bypasses the GORM tag system entirely, as expected. Phase 4
|
||||
// cross-store migration is the only sanctioned caller of this path, and
|
||||
// it must do so through a dedicated, narrowly-scoped repository method
|
||||
// rather than through general Save/Updates/Select flows.
|
||||
func TestKnowledgeBase_VectorStoreID_RawSQL_EscapeHatch(t *testing.T) {
|
||||
db := setupKBTestDB(t)
|
||||
|
||||
original := makeKB(kbStrPtr("store-A"))
|
||||
require.NoError(t, db.Create(original).Error)
|
||||
|
||||
require.NoError(t,
|
||||
db.Exec("UPDATE knowledge_bases SET vector_store_id = ? WHERE id = ?",
|
||||
"store-B", original.ID).Error)
|
||||
|
||||
reloaded := reloadKB(t, db, original.ID)
|
||||
require.NotNil(t, reloaded.VectorStoreID)
|
||||
assert.Equal(t, "store-B", *reloaded.VectorStoreID,
|
||||
"raw SQL UPDATE bypasses GORM tags; Phase 4 migration must use this path through a dedicated method")
|
||||
}
|
||||
|
||||
// TestKnowledgeBase_VectorStoreID_Roundtrip_Nil verifies that a nil
|
||||
// VectorStoreID is persisted as SQL NULL and loaded back as nil.
|
||||
func TestKnowledgeBase_VectorStoreID_Roundtrip_Nil(t *testing.T) {
|
||||
db := setupKBTestDB(t)
|
||||
|
||||
original := makeKB(nil)
|
||||
require.NoError(t, db.Create(original).Error)
|
||||
|
||||
reloaded := reloadKB(t, db, original.ID)
|
||||
assert.Nil(t, reloaded.VectorStoreID,
|
||||
"nil VectorStoreID must round-trip through the database as nil")
|
||||
|
||||
// Extra assurance: column is actually NULL, not an empty string.
|
||||
var nullCount int64
|
||||
require.NoError(t,
|
||||
db.Table("knowledge_bases").
|
||||
Where("id = ? AND vector_store_id IS NULL", original.ID).
|
||||
Count(&nullCount).Error)
|
||||
assert.Equal(t, int64(1), nullCount, "nil must be stored as SQL NULL")
|
||||
}
|
||||
|
||||
// TestKnowledgeBase_VectorStoreID_Roundtrip_Value verifies that a non-nil
|
||||
// VectorStoreID is persisted and loaded back with the same value.
|
||||
func TestKnowledgeBase_VectorStoreID_Roundtrip_Value(t *testing.T) {
|
||||
db := setupKBTestDB(t)
|
||||
|
||||
original := makeKB(kbStrPtr("store-uuid-42"))
|
||||
require.NoError(t, db.Create(original).Error)
|
||||
|
||||
reloaded := reloadKB(t, db, original.ID)
|
||||
require.NotNil(t, reloaded.VectorStoreID)
|
||||
assert.Equal(t, "store-uuid-42", *reloaded.VectorStoreID)
|
||||
}
|
||||
|
||||
// TestCountByVectorStoreID covers the binding-count helper used by the
|
||||
// VectorStore delete guard. Verifies tenant scoping, the GORM auto soft-delete
|
||||
// filter (no explicit `deleted_at IS NULL` literal in the query), and the
|
||||
// edge case where a row stores an empty-string vector_store_id (SQLite
|
||||
// treats "" and NULL differently — we want both excluded from a non-empty
|
||||
// storeID lookup).
|
||||
func TestCountByVectorStoreID(t *testing.T) {
|
||||
db := setupKBTestDB(t)
|
||||
repo := &knowledgeBaseRepository{db: db}
|
||||
ctx := t.Context()
|
||||
|
||||
// Tenant 1: two active rows bound to store-A, one row bound to store-B.
|
||||
kbA1 := makeKB(kbStrPtr("store-A"))
|
||||
kbA2 := makeKB(kbStrPtr("store-A"))
|
||||
kbB := makeKB(kbStrPtr("store-B"))
|
||||
require.NoError(t, db.Create(kbA1).Error)
|
||||
require.NoError(t, db.Create(kbA2).Error)
|
||||
require.NoError(t, db.Create(kbB).Error)
|
||||
|
||||
// Tenant 2: one row bound to store-A (must not count for tenant 1).
|
||||
kbCross := makeKB(kbStrPtr("store-A"))
|
||||
kbCross.TenantID = 2
|
||||
require.NoError(t, db.Create(kbCross).Error)
|
||||
|
||||
// Soft-deleted row bound to store-A (must not count under auto-scope).
|
||||
kbDeleted := makeKB(kbStrPtr("store-A"))
|
||||
require.NoError(t, db.Create(kbDeleted).Error)
|
||||
require.NoError(t, db.Delete(kbDeleted).Error)
|
||||
|
||||
// Row with empty-string vector_store_id (regression — sqlite quirk).
|
||||
kbEmpty := makeKB(kbStrPtr(""))
|
||||
require.NoError(t, db.Create(kbEmpty).Error)
|
||||
|
||||
t.Run("nil db handle uses default", func(t *testing.T) {
|
||||
count, err := repo.CountByVectorStoreID(ctx, nil, 1, "store-A")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(2), count, "tenant 1 has 2 active KBs on store-A")
|
||||
})
|
||||
|
||||
t.Run("explicit db handle works the same", func(t *testing.T) {
|
||||
count, err := repo.CountByVectorStoreID(ctx, db, 1, "store-A")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(2), count)
|
||||
})
|
||||
|
||||
t.Run("different store id", func(t *testing.T) {
|
||||
count, err := repo.CountByVectorStoreID(ctx, nil, 1, "store-B")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(1), count)
|
||||
})
|
||||
|
||||
t.Run("unknown store id returns zero", func(t *testing.T) {
|
||||
count, err := repo.CountByVectorStoreID(ctx, nil, 1, "store-XYZ")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(0), count)
|
||||
})
|
||||
|
||||
t.Run("different tenant", func(t *testing.T) {
|
||||
count, err := repo.CountByVectorStoreID(ctx, nil, 2, "store-A")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(1), count)
|
||||
})
|
||||
|
||||
t.Run("non-empty lookup does not match empty-string rows", func(t *testing.T) {
|
||||
count, err := repo.CountByVectorStoreID(ctx, nil, 1, "")
|
||||
require.NoError(t, err)
|
||||
// Only the empty-string-vsid row matches "" exactly (SQLite quirk —
|
||||
// "" is not NULL). The non-empty rows do not.
|
||||
assert.Equal(t, int64(1), count, "empty-string lookup matches only the empty row")
|
||||
})
|
||||
|
||||
t.Run("shared tx handle returns same result twice", func(t *testing.T) {
|
||||
err := db.Transaction(func(tx *gorm.DB) error {
|
||||
c1, err := repo.CountByVectorStoreID(ctx, tx, 1, "store-A")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c2, err := repo.CountByVectorStoreID(ctx, tx, 1, "store-A")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
assert.Equal(t, c1, c2, "two reads within the same tx must agree")
|
||||
assert.Equal(t, int64(2), c1)
|
||||
return nil
|
||||
})
|
||||
require.NoError(t, err)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// SQLite — the database behind the Lite build — has no default LIKE escape
|
||||
// character, while Postgres defaults to backslash. escapeLikeKeyword /
|
||||
// escapeLikePattern emit \% and \_ on the assumption that the pattern is
|
||||
// consumed by a predicate with an explicit ESCAPE clause; without one, SQLite
|
||||
// searches for a literal backslash and silently returns zero rows (and a zero
|
||||
// total) for any keyword containing %, _ or \.
|
||||
//
|
||||
// These tests pin that invariant at each fixed call site. Each case seeds a
|
||||
// row whose name/content contains the literal character plus a decoy row that
|
||||
// the same keyword would match if the character were still a wildcard, so a
|
||||
// missing ESCAPE fails on "no rows" and a missing escape fails on "extra row".
|
||||
|
||||
// likeEscapeTestDDL creates the join targets of the keyword searches that are
|
||||
// not part of the AutoMigrate set below.
|
||||
const likeEscapeTestDDL = `
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id VARCHAR(36) PRIMARY KEY,
|
||||
username VARCHAR(100) NOT NULL DEFAULT '',
|
||||
email VARCHAR(255) NOT NULL DEFAULT '',
|
||||
deleted_at DATETIME
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS im_channel_sessions (
|
||||
session_id VARCHAR(36),
|
||||
platform VARCHAR(32),
|
||||
chat_id VARCHAR(255),
|
||||
thread_id VARCHAR(255),
|
||||
user_id VARCHAR(64),
|
||||
agent_id VARCHAR(64),
|
||||
im_channel_id VARCHAR(64)
|
||||
);
|
||||
`
|
||||
|
||||
func setupLikeEscapeTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
dsn := "file:" + uuid.New().String() + "?mode=memory&cache=shared&_busy_timeout=5000"
|
||||
db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
sqlDB, err := db.DB()
|
||||
require.NoError(t, err)
|
||||
sqlDB.SetMaxOpenConns(1)
|
||||
t.Cleanup(func() { _ = sqlDB.Close() })
|
||||
|
||||
// The knowledges / knowledge_bases schemas are inlined by the existing
|
||||
// helpers (AutoMigrate does not map their jsonb columns onto SQLite).
|
||||
require.NoError(t, db.Exec(knowledgesTestDDL).Error)
|
||||
require.NoError(t, db.Exec(knowledgeBasesTestDDL).Error)
|
||||
require.NoError(t, db.Exec(likeEscapeTestDDL).Error)
|
||||
require.NoError(t, db.AutoMigrate(
|
||||
&types.KnowledgeTag{},
|
||||
&types.Chunk{},
|
||||
&types.Session{},
|
||||
&types.Tenant{},
|
||||
&types.TenantMember{},
|
||||
))
|
||||
return db
|
||||
}
|
||||
|
||||
func seedLikeEscapeKnowledgeBase(t *testing.T, db *gorm.DB, tenantID uint64, kbID string) {
|
||||
t.Helper()
|
||||
require.NoError(t, db.Exec(`
|
||||
INSERT INTO knowledge_bases (id, name, tenant_id, type, embedding_model_id, summary_model_id)
|
||||
VALUES (?, 'like-escape-kb', ?, 'document', 'test-embedding', 'test-summary')
|
||||
`, kbID, tenantID).Error)
|
||||
}
|
||||
|
||||
func seedLikeEscapeKnowledge(
|
||||
t *testing.T, db *gorm.DB, tenantID uint64, kbID, id, fileName, title string,
|
||||
) {
|
||||
t.Helper()
|
||||
require.NoError(t, db.Exec(`
|
||||
INSERT INTO knowledges (id, tenant_id, knowledge_base_id, type, title, file_name, source, parse_status)
|
||||
VALUES (?, ?, ?, 'file', ?, ?, 'manual', 'completed')
|
||||
`, id, tenantID, kbID, title, fileName).Error)
|
||||
}
|
||||
|
||||
func seedLikeEscapeKnowledgeSet(t *testing.T, db *gorm.DB, tenantID uint64, kbID string) (literalID string) {
|
||||
t.Helper()
|
||||
literalID = uuid.New().String()
|
||||
// Underscore: literal "IMG_2534" must not match "IMGx2534".
|
||||
seedLikeEscapeKnowledge(t, db, tenantID, kbID, literalID, "IMG_2534.png", "IMG_2534")
|
||||
seedLikeEscapeKnowledge(t, db, tenantID, kbID, uuid.New().String(), "IMGx2534.png", "IMGx2534")
|
||||
// Percent: literal "100%" must not match "1000".
|
||||
seedLikeEscapeKnowledge(t, db, tenantID, kbID, uuid.New().String(), "100% done.pdf", "100% done")
|
||||
seedLikeEscapeKnowledge(t, db, tenantID, kbID, uuid.New().String(), "1000 done.pdf", "1000 done")
|
||||
return literalID
|
||||
}
|
||||
|
||||
// Covers the document-list keyword filter in applyKnowledgeListFilter
|
||||
// (reused by the agent list_documents tool and the MCP retrieve tool).
|
||||
func TestListPagedKnowledgeKeywordTreatsLikeWildcardsLiterally(t *testing.T) {
|
||||
db := setupLikeEscapeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
|
||||
ctx := context.Background()
|
||||
const tenantID = uint64(1)
|
||||
kbID := uuid.New().String()
|
||||
seedLikeEscapeKnowledgeBase(t, db, tenantID, kbID)
|
||||
literalID := seedLikeEscapeKnowledgeSet(t, db, tenantID, kbID)
|
||||
page := &types.Pagination{Page: 1, PageSize: 50}
|
||||
|
||||
for _, keyword := range []string{"IMG_2534", "100%"} {
|
||||
rows, total, err := repo.ListPagedKnowledgeByKnowledgeBaseID(
|
||||
ctx, tenantID, kbID, page, types.KnowledgeListFilter{Keyword: keyword},
|
||||
)
|
||||
require.NoError(t, err, "keyword %q", keyword)
|
||||
require.Len(t, rows, 1, "keyword %q must match the literal row only", keyword)
|
||||
assert.Equal(t, int64(1), total, "keyword %q count", keyword)
|
||||
if keyword == "IMG_2534" {
|
||||
assert.Equal(t, literalID, rows[0].ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Covers SearchKnowledge.
|
||||
func TestSearchKnowledgeKeywordTreatsLikeWildcardsLiterally(t *testing.T) {
|
||||
db := setupLikeEscapeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
|
||||
ctx := context.Background()
|
||||
const tenantID = uint64(1)
|
||||
kbID := uuid.New().String()
|
||||
seedLikeEscapeKnowledgeBase(t, db, tenantID, kbID)
|
||||
literalID := seedLikeEscapeKnowledgeSet(t, db, tenantID, kbID)
|
||||
|
||||
rows, _, err := repo.SearchKnowledge(ctx, tenantID, "IMG_2534", 0, 10, nil)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, rows, 1, "underscore must match literally, not as a wildcard")
|
||||
assert.Equal(t, literalID, rows[0].ID)
|
||||
|
||||
rows, _, err = repo.SearchKnowledge(ctx, tenantID, "100%", 0, 10, nil)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, rows, 1, "percent must match literally, not as a wildcard")
|
||||
assert.Contains(t, rows[0].Title, "100%")
|
||||
}
|
||||
|
||||
// Covers SearchKnowledgeInScopes (GET /api/v1/knowledge/search).
|
||||
func TestSearchKnowledgeInScopesKeywordTreatsLikeWildcardsLiterally(t *testing.T) {
|
||||
db := setupLikeEscapeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
|
||||
ctx := context.Background()
|
||||
const tenantID = uint64(1)
|
||||
kbID := uuid.New().String()
|
||||
seedLikeEscapeKnowledgeBase(t, db, tenantID, kbID)
|
||||
literalID := seedLikeEscapeKnowledgeSet(t, db, tenantID, kbID)
|
||||
scopes := []types.KnowledgeSearchScope{{TenantID: tenantID, KBID: kbID}}
|
||||
|
||||
rows, hasMore, total, err := repo.SearchKnowledgeInScopes(ctx, scopes, "IMG_2534", 0, 10, nil)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, rows, 1, "underscore must match literally, not as a wildcard")
|
||||
assert.Equal(t, literalID, rows[0].ID)
|
||||
assert.False(t, hasMore)
|
||||
assert.Equal(t, int64(1), total)
|
||||
|
||||
rows, _, total, err = repo.SearchKnowledgeInScopes(ctx, scopes, "100%", 0, 10, nil)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, rows, 1, "percent must match literally, not as a wildcard")
|
||||
assert.Equal(t, int64(1), total)
|
||||
}
|
||||
|
||||
// Covers both the count and the data query of the tag search.
|
||||
func TestListTagsByKBKeywordTreatsLikeWildcardsLiterally(t *testing.T) {
|
||||
db := setupLikeEscapeTestDB(t)
|
||||
repo := NewKnowledgeTagRepository(db).(*knowledgeTagRepository)
|
||||
ctx := context.Background()
|
||||
const tenantID = uint64(1)
|
||||
kbID := uuid.New().String()
|
||||
|
||||
literalID := uuid.New().String()
|
||||
require.NoError(t, db.Create(&types.KnowledgeTag{
|
||||
ID: literalID, TenantID: tenantID, KnowledgeBaseID: kbID, Name: "v1_1",
|
||||
}).Error)
|
||||
require.NoError(t, db.Create(&types.KnowledgeTag{
|
||||
ID: uuid.New().String(), TenantID: tenantID, KnowledgeBaseID: kbID, Name: "v1x1",
|
||||
}).Error)
|
||||
|
||||
tags, total, err := repo.ListByKB(ctx, tenantID, kbID, &types.Pagination{Page: 1, PageSize: 50}, "v1_1")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, tags, 1, "underscore must match literally, not as a wildcard")
|
||||
assert.Equal(t, literalID, tags[0].ID)
|
||||
assert.Equal(t, int64(1), total, "the count query must use the same escape")
|
||||
}
|
||||
|
||||
// Covers both branches of SearchTenants (with and without a tenant id).
|
||||
func TestSearchTenantsKeywordTreatsLikeWildcardsLiterally(t *testing.T) {
|
||||
db := setupLikeEscapeTestDB(t)
|
||||
repo := NewTenantRepository(db).(*tenantRepository)
|
||||
ctx := context.Background()
|
||||
|
||||
literal := &types.Tenant{Name: "Acme_Prod", Description: "literal underscore", Status: "active"}
|
||||
require.NoError(t, db.Create(literal).Error)
|
||||
require.NoError(t, db.Create(&types.Tenant{
|
||||
Name: "AcmeXProd", Description: "wildcard decoy", Status: "active",
|
||||
}).Error)
|
||||
|
||||
// keyword-only branch (tenantID = 0).
|
||||
tenants, total, err := repo.SearchTenants(ctx, "Acme_Prod", 0, 1, 20)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, tenants, 1, "underscore must match literally, not as a wildcard")
|
||||
assert.Equal(t, literal.ID, tenants[0].ID)
|
||||
assert.Equal(t, int64(1), total)
|
||||
|
||||
// tenantID + keyword branch.
|
||||
tenants, total, err = repo.SearchTenants(ctx, "Acme_Prod", literal.ID, 1, 20)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, tenants, 1)
|
||||
assert.Equal(t, literal.ID, tenants[0].ID)
|
||||
assert.Equal(t, int64(1), total)
|
||||
}
|
||||
|
||||
// Covers both member-search paths (count and page) of the email/username join.
|
||||
func TestTenantMemberSearchTreatsLikeWildcardsLiterally(t *testing.T) {
|
||||
db := setupLikeEscapeTestDB(t)
|
||||
repo := NewTenantMemberRepository(db).(*tenantMemberRepository)
|
||||
ctx := context.Background()
|
||||
const tenantID = uint64(1)
|
||||
|
||||
seedMember := func(id, username, email string) {
|
||||
t.Helper()
|
||||
require.NoError(t, db.Exec(
|
||||
`INSERT INTO users (id, username, email) VALUES (?, ?, ?)`, id, username, email).Error)
|
||||
require.NoError(t, db.Create(&types.TenantMember{
|
||||
UserID: id, TenantID: tenantID, Role: types.TenantRoleContributor,
|
||||
Status: types.TenantMemberStatusActive,
|
||||
}).Error)
|
||||
}
|
||||
literalID := uuid.New().String()
|
||||
seedMember(literalID, "ann_bob", "ann_bob@example.com")
|
||||
seedMember(uuid.New().String(), "annxbob", "annxbob@example.com")
|
||||
|
||||
total, err := repo.CountFilteredByTenant(ctx, tenantID, "ann_bob")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(1), total, "underscore must match literally, not as a wildcard")
|
||||
|
||||
members, err := repo.ListPagedByTenant(ctx, tenantID, "ann_bob", 0, 20)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, members, 1)
|
||||
assert.Equal(t, literalID, members[0].UserID)
|
||||
}
|
||||
|
||||
// Covers the session sidebar keyword filter in QueryPaged.
|
||||
func TestSessionQueryPagedKeywordTreatsLikeWildcardsLiterally(t *testing.T) {
|
||||
db := setupLikeEscapeTestDB(t)
|
||||
repo := NewSessionRepository(db)
|
||||
ctx := context.Background()
|
||||
const tenantID = uint64(7)
|
||||
const userID = "web_user:alice"
|
||||
|
||||
literal := &types.Session{TenantID: tenantID, UserID: userID, Title: "Deploy_Plan v1"}
|
||||
require.NoError(t, db.Create(literal).Error)
|
||||
require.NoError(t, db.Create(&types.Session{
|
||||
TenantID: tenantID, UserID: userID, Title: "DeployXPlan v1",
|
||||
}).Error)
|
||||
|
||||
rows, total, err := repo.QueryPaged(ctx, &types.SessionListQuery{
|
||||
TenantID: tenantID, UserID: userID, Keyword: "Deploy_Plan", Page: 1, PageSize: 20,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, rows, 1, "underscore must match literally, not as a wildcard")
|
||||
assert.Equal(t, literal.ID, rows[0].ID)
|
||||
assert.Equal(t, int64(1), total, "the count query must use the same escape")
|
||||
}
|
||||
|
||||
// Covers the document chunk/Faq keyword filter, which previously did not
|
||||
// escape the keyword at all (so % and _ acted as wildcards).
|
||||
func TestListPagedChunksKeywordTreatsLikeWildcardsLiterally(t *testing.T) {
|
||||
db := setupLikeEscapeTestDB(t)
|
||||
repo := NewChunkRepository(db).(*chunkRepository)
|
||||
ctx := context.Background()
|
||||
const tenantID = uint64(1)
|
||||
knowledgeID := uuid.New().String()
|
||||
kbID := uuid.New().String()
|
||||
|
||||
literal := &types.Chunk{
|
||||
ID: uuid.New().String(), TenantID: tenantID, KnowledgeID: knowledgeID,
|
||||
KnowledgeBaseID: kbID, Content: "config v1_1 is active",
|
||||
ChunkType: types.ChunkTypeText, Status: int(types.ChunkStatusIndexed), IsEnabled: true,
|
||||
}
|
||||
require.NoError(t, db.Create(literal).Error)
|
||||
require.NoError(t, db.Create(&types.Chunk{
|
||||
ID: uuid.New().String(), TenantID: tenantID, KnowledgeID: knowledgeID,
|
||||
KnowledgeBaseID: kbID, Content: "config v1x1 is active",
|
||||
ChunkType: types.ChunkTypeText, Status: int(types.ChunkStatusIndexed), IsEnabled: true,
|
||||
}).Error)
|
||||
|
||||
chunks, total, err := repo.ListPagedChunksByKnowledgeID(
|
||||
ctx, tenantID, knowledgeID, &types.Pagination{Page: 1, PageSize: 50},
|
||||
[]types.ChunkType{types.ChunkTypeText}, nil, "v1_1", "", "",
|
||||
types.KnowledgeBaseTypeDocument, nil,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, chunks, 1, "underscore must match literally, not as a wildcard")
|
||||
assert.Equal(t, literal.ID, chunks[0].ID)
|
||||
assert.Equal(t, int64(1), total)
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type mcpEndpointRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewMCPEndpointRepository creates a GORM-backed MCP endpoint repository.
|
||||
func NewMCPEndpointRepository(db *gorm.DB) interfaces.MCPEndpointRepository {
|
||||
return &mcpEndpointRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *mcpEndpointRepository) Create(ctx context.Context, ep *types.MCPEndpoint) error {
|
||||
return r.db.WithContext(ctx).Create(ep).Error
|
||||
}
|
||||
|
||||
func (r *mcpEndpointRepository) GetByID(ctx context.Context, id string) (*types.MCPEndpoint, error) {
|
||||
var ep types.MCPEndpoint
|
||||
err := r.db.WithContext(ctx).Where("id = ?", id).First(&ep).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &ep, nil
|
||||
}
|
||||
|
||||
func (r *mcpEndpointRepository) GetByTokenHash(ctx context.Context, tokenHash string) (*types.MCPEndpoint, error) {
|
||||
if tokenHash == "" {
|
||||
return nil, nil
|
||||
}
|
||||
var ep types.MCPEndpoint
|
||||
err := r.db.WithContext(ctx).Where("token_hash = ?", tokenHash).First(&ep).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &ep, nil
|
||||
}
|
||||
|
||||
func (r *mcpEndpointRepository) ListByTenant(ctx context.Context, tenantID uint64) ([]*types.MCPEndpoint, error) {
|
||||
var rows []*types.MCPEndpoint
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ?", tenantID).
|
||||
Order("created_at DESC").
|
||||
Find(&rows).Error
|
||||
return rows, err
|
||||
}
|
||||
|
||||
func (r *mcpEndpointRepository) Update(ctx context.Context, ep *types.MCPEndpoint) error {
|
||||
return r.db.WithContext(ctx).Save(ep).Error
|
||||
}
|
||||
|
||||
func (r *mcpEndpointRepository) Delete(ctx context.Context, tenantID uint64, id string) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND id = ?", tenantID, id).
|
||||
Delete(&types.MCPEndpoint{}).Error
|
||||
}
|
||||
|
||||
func (r *mcpEndpointRepository) TouchLastUsed(ctx context.Context, id string) error {
|
||||
now := time.Now()
|
||||
return r.db.WithContext(ctx).
|
||||
Model(&types.MCPEndpoint{}).
|
||||
Where("id = ?", id).
|
||||
UpdateColumn("last_used_at", now).Error
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"academy/internal/types"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
func (r *mcpServiceRepository) GetMetadata(
|
||||
ctx context.Context,
|
||||
tenant uint64,
|
||||
service, principal string,
|
||||
) (*types.MCPMetadata, error) {
|
||||
var snapshot types.MCPMetadata
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND service_id = ? AND principal = ?", tenant, service, principal).
|
||||
First(&snapshot).
|
||||
Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &snapshot, nil
|
||||
}
|
||||
|
||||
func metadataToolCountExpr(db *gorm.DB) string {
|
||||
if db.Name() == "postgres" {
|
||||
return "jsonb_array_length(tools)"
|
||||
}
|
||||
return "json_array_length(tools)"
|
||||
}
|
||||
|
||||
func (r *mcpServiceRepository) ListMetadataSummaries(
|
||||
ctx context.Context,
|
||||
tenant uint64,
|
||||
principals []string,
|
||||
) ([]*types.MCPMetadataSummary, error) {
|
||||
if len(principals) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var rows []*types.MCPMetadataSummary
|
||||
err := r.db.WithContext(ctx).Model(&types.MCPMetadata{}).
|
||||
Select("service_id, principal, config_fingerprint, synced_at, server_name, "+
|
||||
metadataToolCountExpr(r.db)+" AS tool_count").
|
||||
Where("tenant_id = ? AND principal IN ?", tenant, principals).
|
||||
Find(&rows).Error
|
||||
return rows, err
|
||||
}
|
||||
|
||||
func (r *mcpServiceRepository) SaveMetadata(ctx context.Context, snapshot *types.MCPMetadata) error {
|
||||
return r.db.WithContext(ctx).Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "tenant_id"}, {Name: "service_id"}, {Name: "principal"}},
|
||||
DoUpdates: clause.AssignmentColumns(
|
||||
[]string{
|
||||
"config_fingerprint",
|
||||
"tools",
|
||||
"instructions",
|
||||
"server_name",
|
||||
"server_version",
|
||||
"server_description",
|
||||
"synced_at",
|
||||
},
|
||||
),
|
||||
// An older, slower refresh must not overwrite a newer refresh.
|
||||
Where: clause.Where{
|
||||
Exprs: []clause.Expression{clause.Expr{SQL: "mcp_metadata.synced_at <= excluded.synced_at"}},
|
||||
},
|
||||
}).Create(snapshot).Error
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestMCPMetadataPersistsCompleteScopedSnapshotsAndRejectsOlderWrites(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.AutoMigrate(&types.MCPMetadata{}))
|
||||
repo := &mcpServiceRepository{db: db}
|
||||
ctx := context.Background()
|
||||
newer := &types.MCPMetadata{
|
||||
TenantID: 1,
|
||||
ServiceID: "svc",
|
||||
Principal: "user:a",
|
||||
ConfigFingerprint: "new",
|
||||
SyncedAt: time.Now().UTC(),
|
||||
Instructions: "Server instructions",
|
||||
Tools: []*types.MCPTool{
|
||||
{
|
||||
Name: "查询",
|
||||
Description: "Full original description",
|
||||
InputSchema: json.RawMessage(
|
||||
`{"type":"object","oneOf":[{"required":["id"]}],` +
|
||||
`"properties":{"id":{"type":"string"}},"additionalProperties":false}`,
|
||||
),
|
||||
},
|
||||
},
|
||||
}
|
||||
require.NoError(t, repo.SaveMetadata(ctx, newer))
|
||||
older := *newer
|
||||
older.SyncedAt = newer.SyncedAt.Add(-time.Minute)
|
||||
older.Tools = []*types.MCPTool{}
|
||||
require.NoError(t, repo.SaveMetadata(ctx, &older))
|
||||
got, err := repo.GetMetadata(ctx, 1, "svc", "user:a")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, newer.Tools, got.Tools)
|
||||
require.Equal(t, newer.Instructions, got.Instructions)
|
||||
for _, key := range []struct {
|
||||
tenant uint64
|
||||
service, principal string
|
||||
}{{2, "svc", "user:a"}, {1, "svc", "user:b"}, {1, "another", "user:a"}} {
|
||||
missing, err := repo.GetMetadata(ctx, key.tenant, key.service, key.principal)
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, missing)
|
||||
}
|
||||
empty := *newer
|
||||
empty.SyncedAt = newer.SyncedAt.Add(time.Second)
|
||||
empty.Tools = []*types.MCPTool{}
|
||||
require.NoError(t, repo.SaveMetadata(ctx, &empty))
|
||||
got, err = repo.GetMetadata(ctx, 1, "svc", "user:a")
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, got.Tools, "successful empty directories retire removed tools")
|
||||
}
|
||||
|
||||
func TestListMetadataSummariesCountsToolsWithoutReturningPayloads(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.AutoMigrate(&types.MCPMetadata{}))
|
||||
repo := &mcpServiceRepository{db: db}
|
||||
ctx := context.Background()
|
||||
require.NoError(t, repo.SaveMetadata(ctx, &types.MCPMetadata{
|
||||
TenantID: 1,
|
||||
ServiceID: "svc",
|
||||
Principal: "",
|
||||
ConfigFingerprint: "fp",
|
||||
SyncedAt: time.Now().UTC(),
|
||||
Tools: []*types.MCPTool{
|
||||
{Name: "a", Description: "secret-sized description"},
|
||||
{Name: "b"},
|
||||
},
|
||||
}))
|
||||
require.NoError(t, repo.SaveMetadata(ctx, &types.MCPMetadata{
|
||||
TenantID: 1,
|
||||
ServiceID: "oauth",
|
||||
Principal: "user:a",
|
||||
SyncedAt: time.Now().UTC(),
|
||||
Tools: []*types.MCPTool{{Name: "only-a"}},
|
||||
}))
|
||||
rows, err := repo.ListMetadataSummaries(ctx, 1, []string{"", "user:a"})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, rows, 2)
|
||||
byID := map[string]*types.MCPMetadataSummary{}
|
||||
for _, row := range rows {
|
||||
byID[row.ServiceID] = row
|
||||
}
|
||||
require.Equal(t, 2, byID["svc"].ToolCount)
|
||||
require.Equal(t, 1, byID["oauth"].ToolCount)
|
||||
other, err := repo.ListMetadataSummaries(ctx, 1, []string{"user:b"})
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, other)
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
// mcpOAuthRepository implements interfaces.MCPOAuthRepository.
|
||||
type mcpOAuthRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewMCPOAuthRepository creates a new MCP OAuth repository.
|
||||
func NewMCPOAuthRepository(db *gorm.DB) interfaces.MCPOAuthRepository {
|
||||
return &mcpOAuthRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *mcpOAuthRepository) GetClient(
|
||||
ctx context.Context, tenantID uint64, serviceID string,
|
||||
) (*types.MCPOAuthClient, error) {
|
||||
var client types.MCPOAuthClient
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND service_id = ?", tenantID, serviceID).
|
||||
First(&client).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &client, nil
|
||||
}
|
||||
|
||||
func (r *mcpOAuthRepository) SaveClient(ctx context.Context, client *types.MCPOAuthClient) error {
|
||||
client.UpdatedAt = time.Now().UTC()
|
||||
return r.db.WithContext(ctx).
|
||||
Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "tenant_id"}, {Name: "service_id"}},
|
||||
DoUpdates: clause.AssignmentColumns([]string{"client_id", "client_secret", "redirect_uri", "updated_at"}),
|
||||
}).
|
||||
Create(client).Error
|
||||
}
|
||||
|
||||
func (r *mcpOAuthRepository) DeleteClient(ctx context.Context, tenantID uint64, serviceID string) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND service_id = ?", tenantID, serviceID).
|
||||
Delete(&types.MCPOAuthClient{}).Error
|
||||
}
|
||||
|
||||
func (r *mcpOAuthRepository) GetToken(
|
||||
ctx context.Context, tenantID uint64, userID, serviceID string,
|
||||
) (*types.MCPOAuthToken, error) {
|
||||
return r.GetTokenForPrincipal(ctx, tenantID, types.Principal{
|
||||
Type: types.PrincipalWebUser,
|
||||
ID: userID,
|
||||
}, serviceID)
|
||||
}
|
||||
|
||||
func (r *mcpOAuthRepository) GetTokenForPrincipal(
|
||||
ctx context.Context, tenantID uint64, principal types.Principal, serviceID string,
|
||||
) (*types.MCPOAuthToken, error) {
|
||||
principal = principal.Normalize()
|
||||
if !principal.Valid() {
|
||||
return nil, nil
|
||||
}
|
||||
var token types.MCPOAuthToken
|
||||
err := r.db.WithContext(ctx).
|
||||
Where(
|
||||
"tenant_id = ? AND principal_type = ? AND principal_id = ? AND service_id = ?",
|
||||
tenantID, principal.Type, principal.ID, serviceID,
|
||||
).
|
||||
First(&token).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &token, nil
|
||||
}
|
||||
|
||||
func (r *mcpOAuthRepository) SaveToken(ctx context.Context, token *types.MCPOAuthToken) error {
|
||||
if token.PrincipalType == "" || token.PrincipalID == "" {
|
||||
token.PrincipalType = types.PrincipalWebUser
|
||||
token.PrincipalID = token.UserID
|
||||
}
|
||||
return r.SaveTokenForPrincipal(ctx, token)
|
||||
}
|
||||
|
||||
func (r *mcpOAuthRepository) SaveTokenForPrincipal(ctx context.Context, token *types.MCPOAuthToken) error {
|
||||
if token.PrincipalType == "" || token.PrincipalID == "" {
|
||||
return fmt.Errorf("mcp oauth token requires principal_type and principal_id")
|
||||
}
|
||||
if token.UserID == "" {
|
||||
token.UserID = (types.Principal{Type: token.PrincipalType, ID: token.PrincipalID}).StorageID()
|
||||
}
|
||||
// Callers compute the expiry from the process clock, which may not be UTC.
|
||||
// Normalize it so the value is also stored as the right instant while the
|
||||
// columns are still naive TIMESTAMP, for example with AUTO_MIGRATE=false
|
||||
// before migration 000118 is applied.
|
||||
token.ExpiresAt = token.ExpiresAt.UTC()
|
||||
token.UpdatedAt = time.Now().UTC()
|
||||
return r.db.WithContext(ctx).
|
||||
Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{
|
||||
{Name: "tenant_id"},
|
||||
{Name: "principal_type"},
|
||||
{Name: "principal_id"},
|
||||
{Name: "service_id"},
|
||||
},
|
||||
DoUpdates: clause.AssignmentColumns([]string{
|
||||
"user_id", "access_token", "refresh_token", "token_type", "expires_at", "updated_at",
|
||||
}),
|
||||
}).
|
||||
Create(token).Error
|
||||
}
|
||||
|
||||
func (r *mcpOAuthRepository) DeleteToken(
|
||||
ctx context.Context, tenantID uint64, userID, serviceID string,
|
||||
) error {
|
||||
return r.DeleteTokenForPrincipal(ctx, tenantID, types.Principal{
|
||||
Type: types.PrincipalWebUser,
|
||||
ID: userID,
|
||||
}, serviceID)
|
||||
}
|
||||
|
||||
func (r *mcpOAuthRepository) DeleteTokenForPrincipal(
|
||||
ctx context.Context, tenantID uint64, principal types.Principal, serviceID string,
|
||||
) error {
|
||||
principal = principal.Normalize()
|
||||
if !principal.Valid() {
|
||||
return nil
|
||||
}
|
||||
return r.db.WithContext(ctx).
|
||||
Where(
|
||||
"tenant_id = ? AND principal_type = ? AND principal_id = ? AND service_id = ?",
|
||||
tenantID, principal.Type, principal.ID, serviceID,
|
||||
).
|
||||
Delete(&types.MCPOAuthToken{}).Error
|
||||
}
|
||||
|
||||
func (r *mcpOAuthRepository) TryAcquireTokenRefreshLease(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
principal types.Principal,
|
||||
serviceID, leaseID string,
|
||||
leaseUntil time.Time,
|
||||
) (bool, error) {
|
||||
principal = principal.Normalize()
|
||||
if !principal.Valid() || leaseID == "" {
|
||||
return false, nil
|
||||
}
|
||||
now := time.Now()
|
||||
result := r.db.WithContext(ctx).
|
||||
Model(&types.MCPOAuthToken{}).
|
||||
Where(
|
||||
"tenant_id = ? AND principal_type = ? AND principal_id = ? AND service_id = ?",
|
||||
tenantID, principal.Type, principal.ID, serviceID,
|
||||
).
|
||||
Where("refresh_lease_until IS NULL OR refresh_lease_until < ?", now).
|
||||
Updates(map[string]interface{}{
|
||||
"refresh_lease_id": leaseID,
|
||||
"refresh_lease_until": leaseUntil,
|
||||
})
|
||||
return result.RowsAffected == 1, result.Error
|
||||
}
|
||||
|
||||
func (r *mcpOAuthRepository) ReleaseTokenRefreshLease(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
principal types.Principal,
|
||||
serviceID, leaseID string,
|
||||
) error {
|
||||
principal = principal.Normalize()
|
||||
if !principal.Valid() || leaseID == "" {
|
||||
return nil
|
||||
}
|
||||
return r.db.WithContext(ctx).
|
||||
Model(&types.MCPOAuthToken{}).
|
||||
Where(
|
||||
"tenant_id = ? AND principal_type = ? AND principal_id = ? AND service_id = ? AND refresh_lease_id = ?",
|
||||
tenantID, principal.Type, principal.ID, serviceID, leaseID,
|
||||
).
|
||||
Updates(map[string]interface{}{
|
||||
"refresh_lease_id": "",
|
||||
"refresh_lease_until": nil,
|
||||
}).Error
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func newMCPOAuthTestRepo(t *testing.T) *mcpOAuthRepository {
|
||||
t.Helper()
|
||||
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.AutoMigrate(&types.MCPOAuthClient{}, &types.MCPOAuthToken{}))
|
||||
|
||||
return NewMCPOAuthRepository(db).(*mcpOAuthRepository)
|
||||
}
|
||||
|
||||
func TestMCPOAuthRepositoryTokenForPrincipalIsolated(t *testing.T) {
|
||||
repo := newMCPOAuthTestRepo(t)
|
||||
ctx := context.Background()
|
||||
expiresAt := time.Now().Add(time.Hour).UTC()
|
||||
|
||||
webPrincipal := types.Principal{Type: types.PrincipalWebUser, ID: "u1"}
|
||||
apiPrincipal := types.Principal{Type: types.PrincipalAPIExternalUser, ID: "7:external-u1"}
|
||||
|
||||
require.NoError(t, repo.SaveTokenForPrincipal(ctx, &types.MCPOAuthToken{
|
||||
TenantID: 7,
|
||||
UserID: webPrincipal.StorageID(),
|
||||
PrincipalType: webPrincipal.Type,
|
||||
PrincipalID: webPrincipal.ID,
|
||||
ServiceID: "svc1",
|
||||
AccessToken: "web-token",
|
||||
RefreshToken: "web-refresh",
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: expiresAt,
|
||||
}))
|
||||
require.NoError(t, repo.SaveTokenForPrincipal(ctx, &types.MCPOAuthToken{
|
||||
TenantID: 7,
|
||||
UserID: apiPrincipal.StorageID(),
|
||||
PrincipalType: apiPrincipal.Type,
|
||||
PrincipalID: apiPrincipal.ID,
|
||||
ServiceID: "svc1",
|
||||
AccessToken: "api-token",
|
||||
RefreshToken: "api-refresh",
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: expiresAt,
|
||||
}))
|
||||
|
||||
webToken, err := repo.GetTokenForPrincipal(ctx, 7, webPrincipal, "svc1")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "web-token", webToken.AccessToken)
|
||||
|
||||
apiToken, err := repo.GetTokenForPrincipal(ctx, 7, apiPrincipal, "svc1")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "api-token", apiToken.AccessToken)
|
||||
}
|
||||
|
||||
func TestMCPOAuthRepositoryLegacyUserTokenUsesWebPrincipal(t *testing.T) {
|
||||
repo := newMCPOAuthTestRepo(t)
|
||||
ctx := context.Background()
|
||||
|
||||
require.NoError(t, repo.SaveToken(ctx, &types.MCPOAuthToken{
|
||||
TenantID: 7,
|
||||
UserID: "u1",
|
||||
ServiceID: "svc1",
|
||||
AccessToken: "legacy-token",
|
||||
RefreshToken: "legacy-refresh",
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: time.Now().Add(time.Hour).UTC(),
|
||||
}))
|
||||
|
||||
token, err := repo.GetTokenForPrincipal(ctx, 7, types.Principal{Type: types.PrincipalWebUser, ID: "u1"}, "svc1")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "legacy-token", token.AccessToken)
|
||||
}
|
||||
|
||||
func TestMCPOAuthRepositoryRefreshLeaseHasSingleOwner(t *testing.T) {
|
||||
repo := newMCPOAuthTestRepo(t)
|
||||
ctx := context.Background()
|
||||
principal := types.Principal{Type: types.PrincipalWebUser, ID: "u1"}
|
||||
require.NoError(t, repo.SaveTokenForPrincipal(ctx, &types.MCPOAuthToken{
|
||||
TenantID: 7,
|
||||
UserID: principal.StorageID(),
|
||||
PrincipalType: principal.Type,
|
||||
PrincipalID: principal.ID,
|
||||
ServiceID: "svc1",
|
||||
AccessToken: "access",
|
||||
RefreshToken: "refresh",
|
||||
ExpiresAt: time.Now().Add(-time.Minute),
|
||||
}))
|
||||
|
||||
first, err := repo.TryAcquireTokenRefreshLease(
|
||||
ctx, 7, principal, "svc1", "lease-1", time.Now().Add(time.Minute),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.True(t, first)
|
||||
|
||||
second, err := repo.TryAcquireTokenRefreshLease(
|
||||
ctx, 7, principal, "svc1", "lease-2", time.Now().Add(time.Minute),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.False(t, second)
|
||||
|
||||
// A non-owner cannot release the current owner's lease.
|
||||
require.NoError(t, repo.ReleaseTokenRefreshLease(ctx, 7, principal, "svc1", "lease-2"))
|
||||
second, err = repo.TryAcquireTokenRefreshLease(
|
||||
ctx, 7, principal, "svc1", "lease-2", time.Now().Add(time.Minute),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.False(t, second)
|
||||
|
||||
require.NoError(t, repo.ReleaseTokenRefreshLease(ctx, 7, principal, "svc1", "lease-1"))
|
||||
second, err = repo.TryAcquireTokenRefreshLease(
|
||||
ctx, 7, principal, "svc1", "lease-2", time.Now().Add(time.Minute),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.True(t, second)
|
||||
}
|
||||
|
||||
func TestMCPOAuthRepositoryStoresTokenTimesInUTC(t *testing.T) {
|
||||
repo := newMCPOAuthTestRepo(t)
|
||||
ctx := context.Background()
|
||||
// Expiries are computed from the process clock, which runs in the
|
||||
// deployment's local zone rather than UTC.
|
||||
local := time.FixedZone("UTC+9", 9*60*60)
|
||||
expiresAt := time.Date(2026, 10, 12, 21, 3, 32, 0, local)
|
||||
principal := types.Principal{Type: types.PrincipalAPIExternalUser, ID: "7:external-u1"}
|
||||
|
||||
require.NoError(t, repo.SaveTokenForPrincipal(ctx, &types.MCPOAuthToken{
|
||||
TenantID: 7,
|
||||
PrincipalType: principal.Type,
|
||||
PrincipalID: principal.ID,
|
||||
ServiceID: "svc1",
|
||||
AccessToken: "token",
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: expiresAt,
|
||||
}))
|
||||
|
||||
loaded, err := repo.GetTokenForPrincipal(ctx, 7, principal, "svc1")
|
||||
require.NoError(t, err)
|
||||
require.True(t, loaded.ExpiresAt.Equal(expiresAt), "expiry %s, want %s", loaded.ExpiresAt, expiresAt)
|
||||
require.Equal(t, time.UTC, loaded.ExpiresAt.Location())
|
||||
require.Equal(t, time.UTC, loaded.UpdatedAt.Location())
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// mcpServiceRepository implements the MCPServiceRepository interface
|
||||
type mcpServiceRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewMCPServiceRepository creates a new MCP service repository
|
||||
func NewMCPServiceRepository(db *gorm.DB) interfaces.MCPServiceRepository {
|
||||
return &mcpServiceRepository{db: db}
|
||||
}
|
||||
|
||||
// Create creates a new MCP service
|
||||
func (r *mcpServiceRepository) Create(ctx context.Context, service *types.MCPService) error {
|
||||
return r.db.WithContext(ctx).Create(service).Error
|
||||
}
|
||||
|
||||
// GetByID retrieves an MCP service by ID and tenant ID
|
||||
// Builtin MCP services are visible to all tenants
|
||||
func (r *mcpServiceRepository) GetByID(ctx context.Context, tenantID uint64, id string) (*types.MCPService, error) {
|
||||
var service types.MCPService
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("id = ?", id).
|
||||
Where("tenant_id = ? OR is_builtin = true", tenantID).
|
||||
First(&service).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &service, nil
|
||||
}
|
||||
|
||||
// List retrieves all MCP services for a tenant
|
||||
// Includes builtin MCP services visible to all tenants
|
||||
func (r *mcpServiceRepository) List(ctx context.Context, tenantID uint64) ([]*types.MCPService, error) {
|
||||
var services []*types.MCPService
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? OR is_builtin = true", tenantID).
|
||||
Order("created_at DESC").
|
||||
Find(&services).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return services, nil
|
||||
}
|
||||
|
||||
// ListEnabled retrieves all enabled MCP services for a tenant
|
||||
// Includes enabled builtin MCP services visible to all tenants
|
||||
func (r *mcpServiceRepository) ListEnabled(ctx context.Context, tenantID uint64) ([]*types.MCPService, error) {
|
||||
var services []*types.MCPService
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("(tenant_id = ? OR is_builtin = true) AND enabled = ?", tenantID, true).
|
||||
Order("created_at DESC").
|
||||
Find(&services).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return services, nil
|
||||
}
|
||||
|
||||
// ListByIDs retrieves MCP services by multiple IDs for a tenant
|
||||
// Includes builtin MCP services visible to all tenants
|
||||
func (r *mcpServiceRepository) ListByIDs(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
ids []string,
|
||||
) ([]*types.MCPService, error) {
|
||||
if len(ids) == 0 {
|
||||
return []*types.MCPService{}, nil
|
||||
}
|
||||
|
||||
var services []*types.MCPService
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("(tenant_id = ? OR is_builtin = true) AND id IN ?", tenantID, ids).
|
||||
Find(&services).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return services, nil
|
||||
}
|
||||
|
||||
// Update updates an MCP service
|
||||
func (r *mcpServiceRepository) Update(ctx context.Context, service *types.MCPService) error {
|
||||
// Build update map with only non-zero fields (except enabled which should always be updated if set)
|
||||
updateMap := make(map[string]interface{})
|
||||
updateMap["updated_at"] = service.UpdatedAt
|
||||
|
||||
// Always include enabled field if it's being updated (service layer ensures it's set correctly)
|
||||
updateMap["enabled"] = service.Enabled
|
||||
|
||||
if service.Name != "" {
|
||||
updateMap["name"] = service.Name
|
||||
}
|
||||
// Description can be empty, so we check if it's different from existing
|
||||
// For now, we'll always update it if provided
|
||||
updateMap["description"] = service.Description
|
||||
updateMap["usage_instructions"] = service.UsageInstructions
|
||||
|
||||
if service.TransportType != "" {
|
||||
updateMap["transport_type"] = service.TransportType
|
||||
}
|
||||
if service.URL != nil {
|
||||
updateMap["url"] = *service.URL
|
||||
}
|
||||
if service.StdioConfig != nil {
|
||||
updateMap["stdio_config"] = service.StdioConfig
|
||||
}
|
||||
if service.EnvVars != nil {
|
||||
updateMap["env_vars"] = service.EnvVars
|
||||
}
|
||||
if service.Headers != nil {
|
||||
updateMap["headers"] = service.Headers
|
||||
}
|
||||
if service.AuthConfig != nil {
|
||||
updateMap["auth_config"] = service.AuthConfig
|
||||
}
|
||||
if service.AdvancedConfig != nil {
|
||||
updateMap["advanced_config"] = service.AdvancedConfig
|
||||
}
|
||||
|
||||
return r.db.WithContext(ctx).
|
||||
Model(&types.MCPService{}).
|
||||
Where("id = ? AND tenant_id = ?", service.ID, service.TenantID).
|
||||
Updates(updateMap).Error
|
||||
}
|
||||
|
||||
// Delete deletes an MCP service (soft delete)
|
||||
func (r *mcpServiceRepository) Delete(ctx context.Context, tenantID uint64, id string) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Where("id = ? AND tenant_id = ?", id, tenantID).
|
||||
Delete(&types.MCPService{}).Error
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestCreateMCPServicePreservesEnabledState(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
enabled bool
|
||||
}{
|
||||
{name: "disabled", enabled: false},
|
||||
{name: "enabled", enabled: true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
sqlDB, err := db.DB()
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = sqlDB.Close() })
|
||||
require.NoError(t, db.AutoMigrate(&types.MCPService{}))
|
||||
repo := &mcpServiceRepository{db: db}
|
||||
service := &types.MCPService{
|
||||
TenantID: 1,
|
||||
Name: "test",
|
||||
Enabled: tc.enabled,
|
||||
TransportType: types.MCPTransportSSE,
|
||||
}
|
||||
require.NoError(t, repo.Create(context.Background(), service))
|
||||
require.Equal(t, tc.enabled, service.Enabled)
|
||||
stored, err := repo.GetByID(context.Background(), 1, service.ID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tc.enabled, stored.Enabled)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
// MCPToolApprovalRepository implements interfaces.MCPToolApprovalRepository.
|
||||
type MCPToolApprovalRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewMCPToolApprovalRepository creates a repository backed by GORM.
|
||||
func NewMCPToolApprovalRepository(db *gorm.DB) interfaces.MCPToolApprovalRepository {
|
||||
return &MCPToolApprovalRepository{db: db}
|
||||
}
|
||||
|
||||
// ListByService returns all stored approval rows for an MCP service (may be empty).
|
||||
func (r *MCPToolApprovalRepository) ListByService(ctx context.Context, tenantID uint64, serviceID string) ([]*types.MCPToolApproval, error) {
|
||||
var rows []*types.MCPToolApproval
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND service_id = ?", tenantID, serviceID).
|
||||
Order("tool_name ASC").
|
||||
Find(&rows).Error
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list mcp tool approvals: %w", err)
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// Get returns the stored policy of a tool, or nil when it has none.
|
||||
func (r *MCPToolApprovalRepository) Get(
|
||||
ctx context.Context, tenantID uint64, serviceID, toolName string,
|
||||
) (*types.MCPToolApproval, error) {
|
||||
var row types.MCPToolApproval
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND service_id = ? AND tool_name = ?", tenantID, serviceID, toolName).
|
||||
First(&row).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get mcp tool policy: %w", err)
|
||||
}
|
||||
return &row, nil
|
||||
}
|
||||
|
||||
// IsRequired returns true when a row exists with require_approval = true.
|
||||
func (r *MCPToolApprovalRepository) IsRequired(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error) {
|
||||
var row types.MCPToolApproval
|
||||
err := r.db.WithContext(ctx).
|
||||
Select("require_approval").
|
||||
Where("tenant_id = ? AND service_id = ? AND tool_name = ?", tenantID, serviceID, toolName).
|
||||
First(&row).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("get mcp tool approval: %w", err)
|
||||
}
|
||||
return row.RequireApproval, nil
|
||||
}
|
||||
|
||||
// IsEnabled returns true when a tool has no stored policy row. This preserves
|
||||
// the historical behaviour for tools discovered before per-tool settings.
|
||||
func (r *MCPToolApprovalRepository) IsEnabled(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error) {
|
||||
var row types.MCPToolApproval
|
||||
err := r.db.WithContext(ctx).
|
||||
Select("enabled").
|
||||
Where("tenant_id = ? AND service_id = ? AND tool_name = ?", tenantID, serviceID, toolName).
|
||||
First(&row).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return true, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("get mcp tool enabled state: %w", err)
|
||||
}
|
||||
return row.Enabled, nil
|
||||
}
|
||||
|
||||
// riskRankSQL ranks a risk column as policy.Risk.Above does; unknown and
|
||||
// empty risks rank lowest.
|
||||
func riskRankSQL(column string) string {
|
||||
return "(CASE " + column +
|
||||
" WHEN 'read' THEN 1 WHEN 'probe' THEN 2 WHEN 'write' THEN 3 WHEN 'destructive' THEN 4 ELSE 0 END)"
|
||||
}
|
||||
|
||||
// UpsertPolicy creates or updates only the supplied policy columns.
|
||||
// ObservedRisk only ever raises the stored value.
|
||||
// Concurrent patches of different fields cannot clobber each other because
|
||||
// ON CONFLICT updates omit unchanged columns. A first insert uses
|
||||
// require_approval=false and enabled=true for any field the patch omits.
|
||||
func (r *MCPToolApprovalRepository) UpsertPolicy(
|
||||
ctx context.Context, tenantID uint64, serviceID, toolName string, patch types.MCPToolPolicyPatch,
|
||||
) error {
|
||||
if serviceID == "" || toolName == "" {
|
||||
return errors.New("service_id and tool_name are required")
|
||||
}
|
||||
if patch.RequireApproval == nil && patch.Enabled == nil && patch.Risk == nil && patch.ObservedRisk == nil {
|
||||
return errors.New("an MCP tool policy field is required")
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
requireApproval := false
|
||||
if patch.RequireApproval != nil {
|
||||
requireApproval = *patch.RequireApproval
|
||||
}
|
||||
enabled := true
|
||||
if patch.Enabled != nil {
|
||||
enabled = *patch.Enabled
|
||||
}
|
||||
|
||||
updates := map[string]interface{}{"updated_at": now}
|
||||
if patch.RequireApproval != nil {
|
||||
updates["require_approval"] = *patch.RequireApproval
|
||||
}
|
||||
if patch.Enabled != nil {
|
||||
updates["enabled"] = *patch.Enabled
|
||||
}
|
||||
risk, observed := "", ""
|
||||
if patch.Risk != nil {
|
||||
risk = *patch.Risk
|
||||
updates["risk"] = risk
|
||||
}
|
||||
if patch.ObservedRisk != nil {
|
||||
observed = *patch.ObservedRisk
|
||||
// Compare in the statement itself: a concurrent lower observation
|
||||
// read before this one landed must not overwrite it.
|
||||
updates["observed_risk"] = gorm.Expr(
|
||||
"CASE WHEN " + riskRankSQL("excluded.observed_risk") + " > " +
|
||||
riskRankSQL("mcp_tool_approvals.observed_risk") +
|
||||
" THEN excluded.observed_risk ELSE mcp_tool_approvals.observed_risk END")
|
||||
}
|
||||
|
||||
row := map[string]interface{}{
|
||||
"id": uuid.New().String(),
|
||||
"tenant_id": tenantID,
|
||||
"service_id": serviceID,
|
||||
"tool_name": toolName,
|
||||
"require_approval": requireApproval,
|
||||
"enabled": enabled,
|
||||
"risk": risk,
|
||||
"observed_risk": observed,
|
||||
"created_at": now,
|
||||
"updated_at": now,
|
||||
}
|
||||
// Create via map so enabled=false is persisted. GORM struct inserts omit
|
||||
// bool zero values when the field has a default tag.
|
||||
err := r.db.WithContext(ctx).Model(&types.MCPToolApproval{}).Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{
|
||||
{Name: "tenant_id"},
|
||||
{Name: "service_id"},
|
||||
{Name: "tool_name"},
|
||||
},
|
||||
DoUpdates: clause.Assignments(updates),
|
||||
}).Create(row).Error
|
||||
if err != nil {
|
||||
return fmt.Errorf("upsert mcp tool policy: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func newMCPToolApprovalTestRepo(t *testing.T) interfaces.MCPToolApprovalRepository {
|
||||
t.Helper()
|
||||
dsn := "file:" + uuid.NewString() + "?mode=memory&cache=shared&_busy_timeout=5000"
|
||||
db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
sqlDB, err := db.DB()
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { require.NoError(t, sqlDB.Close()) })
|
||||
// Match the production SQLite pool: concurrent callers share one connection.
|
||||
// A busy timeout cannot resolve shared-cache SQLITE_LOCKED table conflicts.
|
||||
sqlDB.SetMaxOpenConns(1)
|
||||
require.NoError(t, db.AutoMigrate(&types.MCPToolApproval{}))
|
||||
return NewMCPToolApprovalRepository(db)
|
||||
}
|
||||
|
||||
func boolPtr(v bool) *bool { return &v }
|
||||
|
||||
func TestMCPToolApprovalIsEnabledDefaultsTrue(t *testing.T) {
|
||||
repo := newMCPToolApprovalTestRepo(t)
|
||||
ctx := context.Background()
|
||||
|
||||
enabled, err := repo.IsEnabled(ctx, 1, "svc", "tool")
|
||||
require.NoError(t, err)
|
||||
require.True(t, enabled)
|
||||
|
||||
required, err := repo.IsRequired(ctx, 1, "svc", "tool")
|
||||
require.NoError(t, err)
|
||||
require.False(t, required)
|
||||
}
|
||||
|
||||
func TestMCPToolApprovalUpsertPolicyInsertDefaults(t *testing.T) {
|
||||
repo := newMCPToolApprovalTestRepo(t)
|
||||
ctx := context.Background()
|
||||
|
||||
require.NoError(t, repo.UpsertPolicy(ctx, 1, "svc", "only-require", types.MCPToolPolicyPatch{
|
||||
RequireApproval: boolPtr(true),
|
||||
}))
|
||||
enabled, err := repo.IsEnabled(ctx, 1, "svc", "only-require")
|
||||
require.NoError(t, err)
|
||||
require.True(t, enabled, "new rows must stay enabled when only approval is set")
|
||||
required, err := repo.IsRequired(ctx, 1, "svc", "only-require")
|
||||
require.NoError(t, err)
|
||||
require.True(t, required)
|
||||
|
||||
require.NoError(t, repo.UpsertPolicy(ctx, 1, "svc", "only-enabled", types.MCPToolPolicyPatch{
|
||||
Enabled: boolPtr(false),
|
||||
}))
|
||||
enabled, err = repo.IsEnabled(ctx, 1, "svc", "only-enabled")
|
||||
require.NoError(t, err)
|
||||
require.False(t, enabled)
|
||||
required, err = repo.IsRequired(ctx, 1, "svc", "only-enabled")
|
||||
require.NoError(t, err)
|
||||
require.False(t, required, "new rows must keep require_approval=false when only enabled is set")
|
||||
}
|
||||
|
||||
func TestMCPToolApprovalUpsertPolicyPreservesOtherColumn(t *testing.T) {
|
||||
repo := newMCPToolApprovalTestRepo(t)
|
||||
ctx := context.Background()
|
||||
|
||||
require.NoError(t, repo.UpsertPolicy(ctx, 1, "svc", "tool", types.MCPToolPolicyPatch{
|
||||
Enabled: boolPtr(false),
|
||||
}))
|
||||
require.NoError(t, repo.UpsertPolicy(ctx, 1, "svc", "tool", types.MCPToolPolicyPatch{
|
||||
RequireApproval: boolPtr(true),
|
||||
}))
|
||||
|
||||
enabled, err := repo.IsEnabled(ctx, 1, "svc", "tool")
|
||||
require.NoError(t, err)
|
||||
require.False(t, enabled, "approval patch must not re-enable a disabled tool")
|
||||
required, err := repo.IsRequired(ctx, 1, "svc", "tool")
|
||||
require.NoError(t, err)
|
||||
require.True(t, required)
|
||||
|
||||
require.NoError(t, repo.UpsertPolicy(ctx, 1, "svc", "tool", types.MCPToolPolicyPatch{
|
||||
Enabled: boolPtr(true),
|
||||
}))
|
||||
required, err = repo.IsRequired(ctx, 1, "svc", "tool")
|
||||
require.NoError(t, err)
|
||||
require.True(t, required, "enabled patch must not clear require_approval")
|
||||
}
|
||||
|
||||
func TestMCPToolApprovalConcurrentColumnPatches(t *testing.T) {
|
||||
repo := newMCPToolApprovalTestRepo(t)
|
||||
ctx := context.Background()
|
||||
require.NoError(t, repo.UpsertPolicy(ctx, 1, "svc", "tool", types.MCPToolPolicyPatch{
|
||||
RequireApproval: boolPtr(false),
|
||||
Enabled: boolPtr(true),
|
||||
}))
|
||||
|
||||
var wg sync.WaitGroup
|
||||
errs := make(chan error, 2)
|
||||
start := make(chan struct{})
|
||||
wg.Add(2)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
errs <- repo.UpsertPolicy(ctx, 1, "svc", "tool", types.MCPToolPolicyPatch{Enabled: boolPtr(false)})
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
errs <- repo.UpsertPolicy(ctx, 1, "svc", "tool", types.MCPToolPolicyPatch{RequireApproval: boolPtr(true)})
|
||||
}()
|
||||
close(start)
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
for err := range errs {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
enabled, err := repo.IsEnabled(ctx, 1, "svc", "tool")
|
||||
require.NoError(t, err)
|
||||
require.False(t, enabled)
|
||||
required, err := repo.IsRequired(ctx, 1, "svc", "tool")
|
||||
require.NoError(t, err)
|
||||
require.True(t, required)
|
||||
}
|
||||
|
||||
func TestMCPToolApprovalObservedRiskOnlyRises(t *testing.T) {
|
||||
repo := newMCPToolApprovalTestRepo(t)
|
||||
ctx := context.Background()
|
||||
observe := func(risk string) string {
|
||||
require.NoError(t, repo.UpsertPolicy(ctx, 1, "svc", "tool", types.MCPToolPolicyPatch{ObservedRisk: &risk}))
|
||||
row, err := repo.Get(ctx, 1, "svc", "tool")
|
||||
require.NoError(t, err)
|
||||
return row.ObservedRisk
|
||||
}
|
||||
require.Equal(t, "read", observe("read"), "the first observation is recorded")
|
||||
require.Equal(t, "write", observe("write"))
|
||||
require.Equal(t, "write", observe("read"), "a stale lower observation does not lower it")
|
||||
require.Equal(t, "write", observe("probe"))
|
||||
require.Equal(t, "destructive", observe("destructive"))
|
||||
}
|
||||
|
||||
func TestMCPToolApprovalConcurrentObservationsKeepTheHighest(t *testing.T) {
|
||||
repo := newMCPToolApprovalTestRepo(t)
|
||||
ctx := context.Background()
|
||||
var wg sync.WaitGroup
|
||||
start := make(chan struct{})
|
||||
errs := make(chan error, 20)
|
||||
for i := range 20 {
|
||||
risk := "read"
|
||||
if i == 7 {
|
||||
risk = "write"
|
||||
}
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
errs <- repo.UpsertPolicy(ctx, 1, "svc", "tool", types.MCPToolPolicyPatch{ObservedRisk: &risk})
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
for err := range errs {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
row, err := repo.Get(ctx, 1, "svc", "tool")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "write", row.ObservedRisk)
|
||||
}
|
||||
@@ -0,0 +1,987 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type memoryRepository struct {
|
||||
db *gorm.DB
|
||||
// Whether the database can rank vectors itself. Probed once, on first use,
|
||||
// because it depends on a migration that is conditional on pgvector being
|
||||
// installed and so cannot be decided from the dialect alone.
|
||||
vectorOnce sync.Once
|
||||
vectorColumn bool
|
||||
}
|
||||
|
||||
// NewMemoryRepository creates the long-term memory repository.
|
||||
func NewMemoryRepository(db *gorm.DB) interfaces.MemoryRepository {
|
||||
return &memoryRepository{db: db}
|
||||
}
|
||||
|
||||
// scoped starts every query already filtered by workspace and subject. All
|
||||
// reads and writes go through it so a missing scope predicate is impossible.
|
||||
func (r *memoryRepository) scoped(ctx context.Context, scope interfaces.MemoryScope) *gorm.DB {
|
||||
return r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND subject_id = ?", scope.TenantID, scope.SubjectID)
|
||||
}
|
||||
|
||||
func (r *memoryRepository) GetSubject(
|
||||
ctx context.Context, scope interfaces.MemoryScope,
|
||||
) (*types.MemorySubject, error) {
|
||||
var subject types.MemorySubject
|
||||
err := r.scoped(ctx, scope).First(&subject).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &subject, nil
|
||||
}
|
||||
|
||||
func (r *memoryRepository) EnsureSubject(
|
||||
ctx context.Context, scope interfaces.MemoryScope,
|
||||
) (*types.MemorySubject, error) {
|
||||
subject := &types.MemorySubject{
|
||||
ID: uuid.New().String(),
|
||||
TenantID: scope.TenantID,
|
||||
SubjectID: scope.SubjectID,
|
||||
Enabled: true,
|
||||
}
|
||||
// DoNothing plus a re-read keeps concurrent first turns from racing into a
|
||||
// unique-violation. The insert is a no-op whenever the row already exists.
|
||||
err := r.db.WithContext(ctx).
|
||||
Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "tenant_id"}, {Name: "subject_id"}},
|
||||
DoNothing: true,
|
||||
}).
|
||||
Create(subject).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
existing, err := r.GetSubject(ctx, scope)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if existing == nil {
|
||||
return nil, errors.New("memory subject vanished after upsert")
|
||||
}
|
||||
return existing, nil
|
||||
}
|
||||
|
||||
func (r *memoryRepository) UpdateSubjectEnabled(
|
||||
ctx context.Context, scope interfaces.MemoryScope, enabled bool,
|
||||
) error {
|
||||
if _, err := r.EnsureSubject(ctx, scope); err != nil {
|
||||
return err
|
||||
}
|
||||
return r.scoped(ctx, scope).
|
||||
Model(&types.MemorySubject{}).
|
||||
Updates(map[string]interface{}{"enabled": enabled, "updated_at": time.Now()}).Error
|
||||
}
|
||||
|
||||
func (r *memoryRepository) UpdateSubjectBlock(
|
||||
ctx context.Context, scope interfaces.MemoryScope, block string, itemCount int,
|
||||
) error {
|
||||
now := time.Now()
|
||||
return r.scoped(ctx, scope).
|
||||
Model(&types.MemorySubject{}).
|
||||
Updates(map[string]interface{}{
|
||||
"block_text": block,
|
||||
"block_updated_at": now,
|
||||
"item_count": itemCount,
|
||||
"updated_at": now,
|
||||
}).Error
|
||||
}
|
||||
|
||||
func (r *memoryRepository) CreateItem(ctx context.Context, item *types.MemoryItem) error {
|
||||
if item.ID == "" {
|
||||
item.ID = uuid.New().String()
|
||||
}
|
||||
if item.ValidFrom.IsZero() {
|
||||
item.ValidFrom = time.Now()
|
||||
}
|
||||
if item.Status == "" {
|
||||
item.Status = types.MemoryStatusActive
|
||||
}
|
||||
return r.db.WithContext(ctx).Create(item).Error
|
||||
}
|
||||
|
||||
func (r *memoryRepository) GetItem(
|
||||
ctx context.Context, scope interfaces.MemoryScope, id string,
|
||||
) (*types.MemoryItem, error) {
|
||||
var item types.MemoryItem
|
||||
err := r.scoped(ctx, scope).Where("id = ?", id).First(&item).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &item, nil
|
||||
}
|
||||
|
||||
// notExpired excludes items whose usefulness has a stated end. Applying it in
|
||||
// the query rather than after the fact means an expired task cannot slip into
|
||||
// a prompt through a code path that forgot to filter.
|
||||
func notExpired(query *gorm.DB) *gorm.DB {
|
||||
return query.Where("expires_at IS NULL OR expires_at > ?", time.Now())
|
||||
}
|
||||
|
||||
func (r *memoryRepository) ListActiveByKinds(
|
||||
ctx context.Context, scope interfaces.MemoryScope, kinds []string, limit int,
|
||||
) ([]*types.MemoryItem, error) {
|
||||
if len(kinds) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var items []*types.MemoryItem
|
||||
query := notExpired(r.scoped(ctx, scope).
|
||||
Where("status = ?", types.MemoryStatusActive).
|
||||
Where("kind IN ?", kinds)).
|
||||
Order("importance DESC, valid_from DESC")
|
||||
if limit > 0 {
|
||||
query = query.Limit(limit)
|
||||
}
|
||||
if err := query.Find(&items).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
// ListActiveResident returns what the resident block is built from.
|
||||
//
|
||||
// Standing traits qualify by kind. An explicitly requested memory qualifies
|
||||
// regardless of kind: the user said "remember this", and making that depend on
|
||||
// their later question happening to share words with it is the fastest way to
|
||||
// lose their trust in the feature.
|
||||
func (r *memoryRepository) ListActiveResident(
|
||||
ctx context.Context, scope interfaces.MemoryScope, limit int,
|
||||
) ([]*types.MemoryItem, error) {
|
||||
var items []*types.MemoryItem
|
||||
query := notExpired(r.scoped(ctx, scope).
|
||||
Where("status = ?", types.MemoryStatusActive).
|
||||
Where("kind IN ? OR origin = ?",
|
||||
types.ResidentMemoryKinds,
|
||||
types.MemoryOriginExplicit)).
|
||||
Order("importance DESC, valid_from DESC")
|
||||
if limit > 0 {
|
||||
query = query.Limit(limit)
|
||||
}
|
||||
if err := query.Find(&items).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func (r *memoryRepository) ListItems(
|
||||
ctx context.Context, scope interfaces.MemoryScope, status string, limit, offset int,
|
||||
) ([]*types.MemoryItem, int64, error) {
|
||||
query := r.scoped(ctx, scope).Model(&types.MemoryItem{})
|
||||
if status != "" {
|
||||
query = query.Where("status = ?", status)
|
||||
}
|
||||
var total int64
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if limit <= 0 {
|
||||
limit = 50
|
||||
}
|
||||
var items []*types.MemoryItem
|
||||
// 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
|
||||
}
|
||||
return items, total, nil
|
||||
}
|
||||
|
||||
// ListLive returns the items of one kind that the user can currently see:
|
||||
// in use, plus proposed and awaiting their decision. Deduplication has to
|
||||
// consider both, or confirming a proposal can leave a duplicate behind.
|
||||
func (r *memoryRepository) ListLive(
|
||||
ctx context.Context, scope interfaces.MemoryScope, kind string, limit int,
|
||||
) ([]*types.MemoryItem, error) {
|
||||
var items []*types.MemoryItem
|
||||
query := notExpired(r.scoped(ctx, scope).
|
||||
Where("status IN ?", []string{types.MemoryStatusActive, types.MemoryStatusPending}).
|
||||
Where("kind = ?", kind)).
|
||||
Order("importance DESC, valid_from DESC")
|
||||
if limit > 0 {
|
||||
query = query.Limit(limit)
|
||||
}
|
||||
if err := query.Find(&items).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func (r *memoryRepository) FindActiveByKey(
|
||||
ctx context.Context, scope interfaces.MemoryScope, normalizedKey string,
|
||||
) (*types.MemoryItem, error) {
|
||||
if normalizedKey == "" {
|
||||
return nil, nil
|
||||
}
|
||||
var item types.MemoryItem
|
||||
// Pending counts as live here. A memory awaiting confirmation is one the
|
||||
// user can already see, and ignoring it meant every re-derivation of the
|
||||
// same inference stacked another copy in their review list.
|
||||
err := r.scoped(ctx, scope).
|
||||
Where("status IN ? AND normalized_key = ?",
|
||||
[]string{types.MemoryStatusActive, types.MemoryStatusPending}, normalizedKey).
|
||||
Order("valid_from DESC").
|
||||
First(&item).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &item, nil
|
||||
}
|
||||
|
||||
func (r *memoryRepository) UpdateItemContent(
|
||||
ctx context.Context, scope interfaces.MemoryScope, id, content, normalizedKey string, importance int,
|
||||
) error {
|
||||
return r.withSubject(ctx, scope, func(tx *gorm.DB, _ *types.MemorySubject) error {
|
||||
var current types.MemoryItem
|
||||
if err := tx.Where("tenant_id = ? AND subject_id = ? AND id = ?", scope.TenantID, scope.SubjectID, id).First(¤t).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if current.Content != content {
|
||||
if err := tx.Where("tenant_id = ? AND subject_id = ? AND item_id = ?", scope.TenantID, scope.SubjectID, id).Delete(&types.MemoryItemEmbedding{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
// Editing a confirmed fact invalidates proposals based on its old wording.
|
||||
if err := tx.Model(&types.MemoryItem{}).
|
||||
Where("tenant_id = ? AND subject_id = ? AND replaces_id = ? AND status = ?",
|
||||
scope.TenantID, scope.SubjectID, id, types.MemoryStatusPending).
|
||||
Updates(map[string]interface{}{"status": types.MemoryStatusSuperseded, "invalid_at": time.Now(), "superseded_by": id}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Model(¤t).Updates(map[string]interface{}{
|
||||
"content": content, "normalized_key": normalizedKey, "importance": importance,
|
||||
"origin": types.MemoryOriginManual, "updated_at": time.Now(),
|
||||
}).Error
|
||||
})
|
||||
}
|
||||
|
||||
func (r *memoryRepository) SupersedeItem(
|
||||
ctx context.Context, scope interfaces.MemoryScope, id, supersededBy string,
|
||||
) error {
|
||||
return r.withSubject(ctx, scope, func(tx *gorm.DB, _ *types.MemorySubject) error {
|
||||
return tx.Model(&types.MemoryItem{}).
|
||||
Where("tenant_id = ? AND subject_id = ? AND ((id = ? AND status = ?) OR (replaces_id = ? AND status = ?))",
|
||||
scope.TenantID, scope.SubjectID, id, types.MemoryStatusActive, id, types.MemoryStatusPending).
|
||||
Updates(map[string]interface{}{
|
||||
"status": types.MemoryStatusSuperseded, "invalid_at": time.Now(),
|
||||
"superseded_by": supersededBy, "updated_at": time.Now(),
|
||||
}).Error
|
||||
})
|
||||
}
|
||||
|
||||
func (r *memoryRepository) DeleteItem(
|
||||
ctx context.Context, scope interfaces.MemoryScope, id string,
|
||||
) error {
|
||||
return r.withSubject(ctx, scope, func(tx *gorm.DB, _ *types.MemorySubject) error {
|
||||
if err := tx.Model(&types.MemoryItem{}).
|
||||
Where("tenant_id = ? AND subject_id = ? AND replaces_id = ? AND status = ?",
|
||||
scope.TenantID, scope.SubjectID, id, types.MemoryStatusPending).
|
||||
Updates(map[string]interface{}{
|
||||
"status": types.MemoryStatusSuperseded, "invalid_at": time.Now(),
|
||||
}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Where("tenant_id = ? AND subject_id = ? AND item_id = ?", scope.TenantID, scope.SubjectID, id).
|
||||
Delete(&types.MemoryItemEmbedding{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Where("tenant_id = ? AND subject_id = ? AND id = ?", scope.TenantID, scope.SubjectID, id).
|
||||
Delete(&types.MemoryItem{}).Error
|
||||
})
|
||||
}
|
||||
|
||||
func (r *memoryRepository) DeleteAll(
|
||||
ctx context.Context, scope interfaces.MemoryScope,
|
||||
) (int64, error) {
|
||||
result := r.scoped(ctx, scope).Delete(&types.MemoryItem{})
|
||||
return result.RowsAffected, result.Error
|
||||
}
|
||||
|
||||
func (r *memoryRepository) TouchUsed(
|
||||
ctx context.Context, scope interfaces.MemoryScope, ids []string,
|
||||
) error {
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
return r.scoped(ctx, scope).
|
||||
Model(&types.MemoryItem{}).
|
||||
Where("id IN ?", ids).
|
||||
Updates(map[string]interface{}{
|
||||
"last_used_at": time.Now(),
|
||||
"use_count": gorm.Expr("use_count + 1"),
|
||||
}).Error
|
||||
}
|
||||
|
||||
// ArchiveLowestRanked keeps the `keep` best active items and archives the
|
||||
// rest. Ranking is importance first, then recency of use, then recency of
|
||||
// creation — no decay curve, because a half-life that silently buries a
|
||||
// correct memory is worse than a hard cap the user can see in the list.
|
||||
func (r *memoryRepository) ArchiveLowestRanked(
|
||||
ctx context.Context, scope interfaces.MemoryScope, keep int,
|
||||
) (int64, error) {
|
||||
if keep <= 0 {
|
||||
return 0, nil
|
||||
}
|
||||
var survivors []string
|
||||
err := r.scoped(ctx, scope).
|
||||
Model(&types.MemoryItem{}).
|
||||
Where("status = ?", types.MemoryStatusActive).
|
||||
Order("importance DESC, COALESCE(last_used_at, valid_from) DESC, valid_from DESC").
|
||||
Limit(keep).
|
||||
Pluck("id", &survivors).Error
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
query := r.scoped(ctx, scope).
|
||||
Model(&types.MemoryItem{}).
|
||||
Where("status = ?", types.MemoryStatusActive)
|
||||
if len(survivors) > 0 {
|
||||
query = query.Where("id NOT IN ?", survivors)
|
||||
}
|
||||
result := query.Updates(map[string]interface{}{
|
||||
"status": types.MemoryStatusArchived,
|
||||
"updated_at": time.Now(),
|
||||
})
|
||||
return result.RowsAffected, result.Error
|
||||
}
|
||||
|
||||
func (r *memoryRepository) AddTombstone(
|
||||
ctx context.Context, scope interfaces.MemoryScope, topic, fingerprint, sourceMessageID string,
|
||||
) error {
|
||||
if fingerprint == "" {
|
||||
return nil
|
||||
}
|
||||
tombstone := &types.MemoryTombstone{
|
||||
ID: uuid.New().String(),
|
||||
TenantID: scope.TenantID,
|
||||
SubjectID: scope.SubjectID,
|
||||
Topic: topic,
|
||||
Fingerprint: fingerprint,
|
||||
SourceMessageID: sourceMessageID,
|
||||
}
|
||||
err := r.db.WithContext(ctx).
|
||||
Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{
|
||||
{Name: "tenant_id"}, {Name: "subject_id"}, {Name: "fingerprint"},
|
||||
},
|
||||
DoNothing: true,
|
||||
}).
|
||||
Create(tombstone).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return r.trimTombstones(ctx, scope)
|
||||
}
|
||||
|
||||
// trimTombstones keeps the list bounded. A rejection from long ago matters less
|
||||
// than this table growing without limit.
|
||||
func (r *memoryRepository) trimTombstones(ctx context.Context, scope interfaces.MemoryScope) error {
|
||||
var keep []string
|
||||
err := r.scoped(ctx, scope).
|
||||
Model(&types.MemoryTombstone{}).
|
||||
Order("created_at DESC").
|
||||
Limit(types.MaxMemoryTombstones).
|
||||
Pluck("id", &keep).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(keep) < types.MaxMemoryTombstones {
|
||||
return nil
|
||||
}
|
||||
return r.scoped(ctx, scope).
|
||||
Where("id NOT IN ?", keep).
|
||||
Delete(&types.MemoryTombstone{}).Error
|
||||
}
|
||||
|
||||
func (r *memoryRepository) ListTombstones(
|
||||
ctx context.Context, scope interfaces.MemoryScope, limit int,
|
||||
) ([]*types.MemoryTombstone, error) {
|
||||
var tombstones []*types.MemoryTombstone
|
||||
query := r.scoped(ctx, scope).
|
||||
Model(&types.MemoryTombstone{}).
|
||||
Order("created_at DESC")
|
||||
if limit > 0 {
|
||||
query = query.Limit(limit)
|
||||
}
|
||||
if err := query.Find(&tombstones).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tombstones, nil
|
||||
}
|
||||
|
||||
func (r *memoryRepository) HasTombstone(
|
||||
ctx context.Context, scope interfaces.MemoryScope, fingerprint string,
|
||||
) (bool, error) {
|
||||
if fingerprint == "" {
|
||||
return false, nil
|
||||
}
|
||||
var count int64
|
||||
err := r.scoped(ctx, scope).
|
||||
Model(&types.MemoryTombstone{}).
|
||||
Where("fingerprint = ?", fingerprint).
|
||||
Count(&count).Error
|
||||
return count > 0, err
|
||||
}
|
||||
|
||||
func (r *memoryRepository) HasTombstoneForMessage(
|
||||
ctx context.Context, scope interfaces.MemoryScope, sourceMessageID string, within time.Duration,
|
||||
) (bool, error) {
|
||||
if sourceMessageID == "" {
|
||||
return false, nil
|
||||
}
|
||||
query := r.scoped(ctx, scope).
|
||||
Model(&types.MemoryTombstone{}).
|
||||
Where("source_message_id = ?", sourceMessageID)
|
||||
if within > 0 {
|
||||
query = query.Where("created_at > ?", time.Now().Add(-within))
|
||||
}
|
||||
var count int64
|
||||
err := query.Count(&count).Error
|
||||
return count > 0, err
|
||||
}
|
||||
|
||||
func (r *memoryRepository) ExpireOverdue(
|
||||
ctx context.Context, scope interfaces.MemoryScope,
|
||||
) (int64, error) {
|
||||
now := time.Now()
|
||||
result := r.scoped(ctx, scope).
|
||||
Model(&types.MemoryItem{}).
|
||||
Where("status = ? AND expires_at IS NOT NULL AND expires_at <= ?", types.MemoryStatusActive, now).
|
||||
Updates(map[string]interface{}{
|
||||
"status": types.MemoryStatusArchived,
|
||||
"updated_at": now,
|
||||
})
|
||||
return result.RowsAffected, result.Error
|
||||
}
|
||||
|
||||
func (r *memoryRepository) UpsertItemEmbedding(
|
||||
ctx context.Context, scope interfaces.MemoryScope, embedding *types.MemoryItemEmbedding,
|
||||
) error {
|
||||
if embedding == nil || embedding.ItemID == "" || len(embedding.Vector) == 0 {
|
||||
return nil
|
||||
}
|
||||
embedding.TenantID = scope.TenantID
|
||||
embedding.SubjectID = scope.SubjectID
|
||||
now := time.Now()
|
||||
embedding.UpdatedAt = now
|
||||
if embedding.CreatedAt.IsZero() {
|
||||
embedding.CreatedAt = now
|
||||
}
|
||||
return r.withSubject(ctx, scope, func(tx *gorm.DB, _ *types.MemorySubject) error {
|
||||
if embedding.SourceContent != "" {
|
||||
var current types.MemoryItem
|
||||
err := tx.Where("tenant_id = ? AND subject_id = ? AND id = ?", scope.TenantID, scope.SubjectID, embedding.ItemID).First(¤t).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if current.Content != embedding.SourceContent || current.Topic != embedding.SourceTopic {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
err := tx.
|
||||
Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "item_id"}},
|
||||
DoUpdates: clause.AssignmentColumns([]string{"model_id", "dims", "vector", "updated_at"}),
|
||||
}).
|
||||
Create(embedding).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// The blob above is what every deployment reads; this is the same
|
||||
// vector in the type the database can sort by. Written in the same
|
||||
// transaction so a row is never searchable with a stale vector.
|
||||
return r.writeVectorColumn(tx, embedding.ItemID, embedding.Vector)
|
||||
})
|
||||
}
|
||||
|
||||
// DeleteItemEmbedding drops one memory's vector so the backfill rebuilds it.
|
||||
func (r *memoryRepository) DeleteItemEmbedding(
|
||||
ctx context.Context, scope interfaces.MemoryScope, itemID string,
|
||||
) error {
|
||||
if itemID == "" {
|
||||
return nil
|
||||
}
|
||||
return r.scoped(ctx, scope).
|
||||
Where("item_id = ?", itemID).
|
||||
Delete(&types.MemoryItemEmbedding{}).Error
|
||||
}
|
||||
|
||||
func (r *memoryRepository) ItemEmbeddings(
|
||||
ctx context.Context, scope interfaces.MemoryScope, itemIDs []string, modelID string,
|
||||
) (map[string][]float32, error) {
|
||||
if len(itemIDs) == 0 || modelID == "" {
|
||||
return nil, nil
|
||||
}
|
||||
var rows []*types.MemoryItemEmbedding
|
||||
err := r.scoped(ctx, scope).
|
||||
Model(&types.MemoryItemEmbedding{}).
|
||||
Where("item_id IN ? AND model_id = ?", itemIDs, modelID).
|
||||
Find(&rows).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
vectors := make(map[string][]float32, len(rows))
|
||||
for _, row := range rows {
|
||||
if vector := types.DecodeEmbedding(row.Vector); len(vector) > 0 {
|
||||
vectors[row.ItemID] = vector
|
||||
}
|
||||
}
|
||||
return vectors, nil
|
||||
}
|
||||
|
||||
// ItemsMissingEmbeddings finds the backlog.
|
||||
//
|
||||
// Every memory written before an embedding model was configured, and every one
|
||||
// written while the model was unreachable, has no vector — and a memory with no
|
||||
// vector is invisible to semantic recall. Without a backfill the feature would
|
||||
// only ever work for memories created after it was switched on.
|
||||
func (r *memoryRepository) ItemsMissingEmbeddings(
|
||||
ctx context.Context, scope interfaces.MemoryScope, modelID string, limit int,
|
||||
) ([]*types.MemoryItem, error) {
|
||||
if limit <= 0 {
|
||||
limit = 20
|
||||
}
|
||||
var items []*types.MemoryItem
|
||||
err := r.scoped(ctx, scope).
|
||||
Model(&types.MemoryItem{}).
|
||||
Where("status IN ?", []string{types.MemoryStatusActive, types.MemoryStatusPending}).
|
||||
Where(`id NOT IN (
|
||||
SELECT item_id FROM memory_item_embeddings
|
||||
WHERE tenant_id = ? AND subject_id = ? AND model_id = ?
|
||||
)`, scope.TenantID, scope.SubjectID, modelID).
|
||||
Order("valid_from DESC").
|
||||
Limit(limit).
|
||||
Find(&items).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func (r *memoryRepository) MarkConsolidated(
|
||||
ctx context.Context, scope interfaces.MemoryScope,
|
||||
) error {
|
||||
now := time.Now()
|
||||
return r.scoped(ctx, scope).
|
||||
Model(&types.MemorySubject{}).
|
||||
Updates(map[string]interface{}{"consolidated_at": now, "updated_at": now}).Error
|
||||
}
|
||||
|
||||
func (r *memoryRepository) MarkForcedConsolidated(
|
||||
ctx context.Context, scope interfaces.MemoryScope,
|
||||
) error {
|
||||
now := time.Now()
|
||||
return r.scoped(ctx, scope).
|
||||
Model(&types.MemorySubject{}).
|
||||
Updates(map[string]interface{}{"forced_consolidated_at": now, "updated_at": now}).Error
|
||||
}
|
||||
|
||||
// BumpTopic counts one more sighting. The insert-then-increment shape keeps two
|
||||
// concurrent turns from both deciding the topic is new.
|
||||
func (r *memoryRepository) BumpTopic(
|
||||
ctx context.Context, scope interfaces.MemoryScope, topic, normalizedKey, alias string,
|
||||
) (*types.MemoryTopicStat, error) {
|
||||
if normalizedKey == "" {
|
||||
return nil, nil
|
||||
}
|
||||
now := time.Now()
|
||||
stat := &types.MemoryTopicStat{
|
||||
ID: uuid.New().String(),
|
||||
TenantID: scope.TenantID,
|
||||
SubjectID: scope.SubjectID,
|
||||
NormalizedKey: normalizedKey,
|
||||
Topic: topic,
|
||||
Hits: 0,
|
||||
LastSeenAt: now,
|
||||
}
|
||||
err := r.db.WithContext(ctx).
|
||||
Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{
|
||||
{Name: "tenant_id"}, {Name: "subject_id"}, {Name: "normalized_key"},
|
||||
},
|
||||
DoNothing: true,
|
||||
}).
|
||||
Create(stat).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = r.scoped(ctx, scope).
|
||||
Model(&types.MemoryTopicStat{}).
|
||||
Where("normalized_key = ?", normalizedKey).
|
||||
Updates(map[string]interface{}{
|
||||
"hits": gorm.Expr("hits + 1"),
|
||||
"last_seen_at": now,
|
||||
"updated_at": now,
|
||||
}).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var updated types.MemoryTopicStat
|
||||
if err := r.scoped(ctx, scope).
|
||||
Where("normalized_key = ?", normalizedKey).
|
||||
First(&updated).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Record the wording this sighting arrived as, so the same phrasing
|
||||
// resolves by exact match next time instead of being re-adjudicated.
|
||||
if alias != "" && !updated.Aliases.Has(alias) &&
|
||||
types.NormalizeTopicKey(alias) != updated.NormalizedKey {
|
||||
aliases := append(updated.Aliases, alias)
|
||||
if len(aliases) > 12 {
|
||||
aliases = aliases[len(aliases)-12:]
|
||||
}
|
||||
if err := r.scoped(ctx, scope).
|
||||
Model(&types.MemoryTopicStat{}).
|
||||
Where("normalized_key = ?", normalizedKey).
|
||||
Updates(map[string]interface{}{"aliases": aliases, "updated_at": now}).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
updated.Aliases = aliases
|
||||
}
|
||||
return &updated, nil
|
||||
}
|
||||
|
||||
// RenameTopic gives a subject a better canonical label.
|
||||
//
|
||||
// The old label becomes an alias rather than being discarded: it is what every
|
||||
// earlier sighting was counted under, and dropping it would make the next
|
||||
// occurrence of that wording look like a brand new subject. Returns false when
|
||||
// the new key already belongs to another row, in which case the rename is
|
||||
// skipped — folding two rows together is a different operation with different
|
||||
// risks, and doing it as a side effect of a rename would lose counts.
|
||||
func (r *memoryRepository) RenameTopic(
|
||||
ctx context.Context, scope interfaces.MemoryScope, oldKey, newKey, newLabel string,
|
||||
) (bool, error) {
|
||||
if oldKey == "" || newKey == "" || oldKey == newKey {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
var clash int64
|
||||
err := r.scoped(ctx, scope).
|
||||
Model(&types.MemoryTopicStat{}).
|
||||
Where("normalized_key = ?", newKey).
|
||||
Count(&clash).Error
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if clash > 0 {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
var current types.MemoryTopicStat
|
||||
if err := r.scoped(ctx, scope).
|
||||
Where("normalized_key = ?", oldKey).
|
||||
First(¤t).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
|
||||
// The incoming wording was recorded as an alias before the rename decided
|
||||
// to adopt it. Leaving it there would list the canonical label as an alias
|
||||
// of itself.
|
||||
aliases := make(types.MemoryTopicAliases, 0, len(current.Aliases)+1)
|
||||
for _, alias := range current.Aliases {
|
||||
if types.NormalizeTopicKey(alias) == newKey {
|
||||
continue
|
||||
}
|
||||
aliases = append(aliases, alias)
|
||||
}
|
||||
if current.Topic != "" && !aliases.Has(current.Topic) {
|
||||
aliases = append(aliases, current.Topic)
|
||||
}
|
||||
if len(aliases) > 12 {
|
||||
aliases = aliases[len(aliases)-12:]
|
||||
}
|
||||
|
||||
err = r.scoped(ctx, scope).
|
||||
Model(&types.MemoryTopicStat{}).
|
||||
Where("normalized_key = ?", oldKey).
|
||||
Updates(map[string]interface{}{
|
||||
"topic": newLabel,
|
||||
"normalized_key": newKey,
|
||||
"aliases": aliases,
|
||||
"updated_at": time.Now(),
|
||||
}).Error
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (r *memoryRepository) MarkTopicPromoted(
|
||||
ctx context.Context, scope interfaces.MemoryScope, normalizedKey string,
|
||||
) error {
|
||||
now := time.Now()
|
||||
return r.scoped(ctx, scope).
|
||||
Model(&types.MemoryTopicStat{}).
|
||||
Where("normalized_key = ?", normalizedKey).
|
||||
Updates(map[string]interface{}{"promoted_at": now, "updated_at": now}).Error
|
||||
}
|
||||
|
||||
// TopicByKey returns one subject's statistics, or nil when it is not tracked.
|
||||
func (r *memoryRepository) TopicByKey(
|
||||
ctx context.Context, scope interfaces.MemoryScope, normalizedKey string,
|
||||
) (*types.MemoryTopicStat, error) {
|
||||
if normalizedKey == "" {
|
||||
return nil, nil
|
||||
}
|
||||
var stat types.MemoryTopicStat
|
||||
err := r.scoped(ctx, scope).
|
||||
Where("normalized_key = ?", normalizedKey).
|
||||
First(&stat).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &stat, nil
|
||||
}
|
||||
|
||||
func (r *memoryRepository) TopTopics(
|
||||
ctx context.Context, scope interfaces.MemoryScope, limit int,
|
||||
) ([]*types.MemoryTopicStat, error) {
|
||||
var stats []*types.MemoryTopicStat
|
||||
query := r.scoped(ctx, scope).
|
||||
Model(&types.MemoryTopicStat{}).
|
||||
Order("hits DESC, last_seen_at DESC")
|
||||
if limit > 0 {
|
||||
query = query.Limit(limit)
|
||||
}
|
||||
if err := query.Find(&stats).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
func (r *memoryRepository) TopicByID(
|
||||
ctx context.Context, scope interfaces.MemoryScope, id string,
|
||||
) (*types.MemoryTopicStat, error) {
|
||||
if id == "" {
|
||||
return nil, nil
|
||||
}
|
||||
var stat types.MemoryTopicStat
|
||||
err := r.scoped(ctx, scope).Where("id = ?", id).First(&stat).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &stat, nil
|
||||
}
|
||||
|
||||
func (r *memoryRepository) ListUnpromotedTopics(
|
||||
ctx context.Context, scope interfaces.MemoryScope, limit, offset int,
|
||||
) ([]*types.MemoryTopicStat, int64, error) {
|
||||
query := r.scoped(ctx, scope).
|
||||
Model(&types.MemoryTopicStat{}).
|
||||
Where("promoted_at IS NULL")
|
||||
var total int64
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if limit <= 0 {
|
||||
limit = 50
|
||||
}
|
||||
var stats []*types.MemoryTopicStat
|
||||
err := query.Order("hits DESC, last_seen_at DESC").
|
||||
Limit(limit).Offset(offset).Find(&stats).Error
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return stats, total, nil
|
||||
}
|
||||
|
||||
func (r *memoryRepository) DeleteTopic(
|
||||
ctx context.Context, scope interfaces.MemoryScope, id string,
|
||||
) error {
|
||||
return r.scoped(ctx, scope).Where("id = ?", id).Delete(&types.MemoryTopicStat{}).Error
|
||||
}
|
||||
|
||||
func (r *memoryRepository) DeleteAllTopics(
|
||||
ctx context.Context, scope interfaces.MemoryScope,
|
||||
) error {
|
||||
return r.scoped(ctx, scope).Delete(&types.MemoryTopicStat{}).Error
|
||||
}
|
||||
|
||||
func (r *memoryRepository) BumpDocAffinity(
|
||||
ctx context.Context, scope interfaces.MemoryScope, docs []types.MemoryDocAffinity,
|
||||
) error {
|
||||
now := time.Now()
|
||||
for _, doc := range docs {
|
||||
if doc.KnowledgeID == "" {
|
||||
continue
|
||||
}
|
||||
row := &types.MemoryDocAffinity{
|
||||
ID: uuid.New().String(),
|
||||
TenantID: scope.TenantID,
|
||||
SubjectID: scope.SubjectID,
|
||||
KnowledgeID: doc.KnowledgeID,
|
||||
KnowledgeBaseID: doc.KnowledgeBaseID,
|
||||
Title: doc.Title,
|
||||
Hits: 0,
|
||||
LastUsedAt: now,
|
||||
}
|
||||
if err := r.db.WithContext(ctx).
|
||||
Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{
|
||||
{Name: "tenant_id"}, {Name: "subject_id"}, {Name: "knowledge_id"},
|
||||
},
|
||||
DoNothing: true,
|
||||
}).
|
||||
Create(row).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
updates := map[string]interface{}{
|
||||
"hits": gorm.Expr("hits + 1"),
|
||||
"last_used_at": now,
|
||||
"updated_at": now,
|
||||
}
|
||||
if doc.Title != "" {
|
||||
updates["title"] = doc.Title
|
||||
}
|
||||
if doc.KnowledgeBaseID != "" {
|
||||
updates["knowledge_base_id"] = doc.KnowledgeBaseID
|
||||
}
|
||||
if err := r.scoped(ctx, scope).
|
||||
Model(&types.MemoryDocAffinity{}).
|
||||
Where("knowledge_id = ?", doc.KnowledgeID).
|
||||
Updates(updates).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *memoryRepository) DocAffinity(
|
||||
ctx context.Context, scope interfaces.MemoryScope, knowledgeIDs []string,
|
||||
) (map[string]int, error) {
|
||||
if len(knowledgeIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var rows []*types.MemoryDocAffinity
|
||||
err := r.scoped(ctx, scope).
|
||||
Model(&types.MemoryDocAffinity{}).
|
||||
Where("knowledge_id IN ?", knowledgeIDs).
|
||||
Find(&rows).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
affinity := make(map[string]int, len(rows))
|
||||
for _, row := range rows {
|
||||
affinity[row.KnowledgeID] = row.Hits
|
||||
}
|
||||
return affinity, nil
|
||||
}
|
||||
|
||||
func (r *memoryRepository) TopDocAffinity(
|
||||
ctx context.Context, scope interfaces.MemoryScope, limit int,
|
||||
) ([]*types.MemoryDocAffinity, error) {
|
||||
var rows []*types.MemoryDocAffinity
|
||||
query := r.scoped(ctx, scope).
|
||||
Model(&types.MemoryDocAffinity{}).
|
||||
Order("hits DESC, last_used_at DESC")
|
||||
if limit > 0 {
|
||||
query = query.Limit(limit)
|
||||
}
|
||||
if err := query.Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
func (r *memoryRepository) DocAffinityByID(
|
||||
ctx context.Context, scope interfaces.MemoryScope, id string,
|
||||
) (*types.MemoryDocAffinity, error) {
|
||||
if id == "" {
|
||||
return nil, nil
|
||||
}
|
||||
var row types.MemoryDocAffinity
|
||||
err := r.scoped(ctx, scope).Where("id = ?", id).First(&row).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &row, nil
|
||||
}
|
||||
|
||||
func (r *memoryRepository) ListFamiliarDocs(
|
||||
ctx context.Context, scope interfaces.MemoryScope, minHits, limit, offset int,
|
||||
) ([]*types.MemoryDocAffinity, int64, error) {
|
||||
if minHits < 1 {
|
||||
minHits = types.MemoryDocAffinityMinHits
|
||||
}
|
||||
query := r.scoped(ctx, scope).
|
||||
Model(&types.MemoryDocAffinity{}).
|
||||
Where("hits >= ?", minHits)
|
||||
var total int64
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if limit <= 0 {
|
||||
limit = 50
|
||||
}
|
||||
var rows []*types.MemoryDocAffinity
|
||||
err := query.Order("hits DESC, last_used_at DESC").
|
||||
Limit(limit).Offset(offset).Find(&rows).Error
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return rows, total, nil
|
||||
}
|
||||
|
||||
func (r *memoryRepository) DeleteDocAffinity(
|
||||
ctx context.Context, scope interfaces.MemoryScope, id string,
|
||||
) error {
|
||||
return r.scoped(ctx, scope).Where("id = ?", id).Delete(&types.MemoryDocAffinity{}).Error
|
||||
}
|
||||
|
||||
func (r *memoryRepository) DeleteAllDocAffinity(
|
||||
ctx context.Context, scope interfaces.MemoryScope,
|
||||
) error {
|
||||
return r.scoped(ctx, scope).Delete(&types.MemoryDocAffinity{}).Error
|
||||
}
|
||||
|
||||
func (r *memoryRepository) CountActive(
|
||||
ctx context.Context, scope interfaces.MemoryScope,
|
||||
) (int64, error) {
|
||||
var count int64
|
||||
err := r.scoped(ctx, scope).
|
||||
Model(&types.MemoryItem{}).
|
||||
Where("status = ?", types.MemoryStatusActive).
|
||||
Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
func (r *memoryRepository) withSubject(ctx context.Context, scope interfaces.MemoryScope, fn func(*gorm.DB, *types.MemorySubject) error) error {
|
||||
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var subject types.MemorySubject
|
||||
if err := tx.Where("tenant_id = ? AND subject_id = ?", scope.TenantID, scope.SubjectID).
|
||||
Clauses(forUpdateClause()).First(&subject).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return fn(tx, &subject)
|
||||
})
|
||||
}
|
||||
|
||||
func saveExtractionState(tx *gorm.DB, subject *types.MemorySubject) error {
|
||||
return tx.Model(subject).Updates(map[string]interface{}{
|
||||
"extraction_state": subject.ExtractionState, "pending_sessions": subject.PendingSessions,
|
||||
"extract_scheduled_at": subject.ExtractScheduledAt, "updated_at": time.Now(),
|
||||
}).Error
|
||||
}
|
||||
|
||||
func extractionRows(tx *gorm.DB, scope interfaces.MemoryScope) *gorm.DB {
|
||||
return tx.Model(&types.MemoryExtractionSession{}).
|
||||
Where("tenant_id = ? AND subject_id = ?", scope.TenantID, scope.SubjectID)
|
||||
}
|
||||
|
||||
func enqueueExtractionSession(tx *gorm.DB, subject *types.MemorySubject, id string, bump bool) error {
|
||||
if id == "" {
|
||||
return nil
|
||||
}
|
||||
row := types.MemoryExtractionSession{
|
||||
TenantID: subject.TenantID, SubjectID: subject.SubjectID, SessionID: id, Revision: 1, Pending: true,
|
||||
}
|
||||
// Preserve the pre-upgrade boundary instead of replaying every historical
|
||||
// conversation. This value is frozen; only per-session cursors advance now.
|
||||
if subject.ExtractCursor != nil {
|
||||
row.Cursor.At = *subject.ExtractCursor
|
||||
}
|
||||
conflict := clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "tenant_id"}, {Name: "subject_id"}, {Name: "session_id"}},
|
||||
DoNothing: true,
|
||||
}
|
||||
if bump {
|
||||
conflict.DoNothing = false
|
||||
conflict.DoUpdates = clause.Assignments(map[string]interface{}{
|
||||
"revision": gorm.Expr("memory_extraction_sessions.revision + 1"), "pending": true, "updated_at": time.Now(),
|
||||
})
|
||||
}
|
||||
return tx.Clauses(conflict).Create(&row).Error
|
||||
}
|
||||
|
||||
func importLegacySessions(tx *gorm.DB, subject *types.MemorySubject) error {
|
||||
for _, id := range subject.PendingSessions {
|
||||
if err := enqueueExtractionSession(tx, subject, id, false); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
subject.PendingSessions = types.MemoryPendingSessions{}
|
||||
return nil
|
||||
}
|
||||
|
||||
func hasPendingExtraction(tx *gorm.DB, scope interfaces.MemoryScope) (bool, error) {
|
||||
var rows []types.MemoryExtractionSession
|
||||
result := extractionRows(tx, scope).Select("session_id").Where("pending = ?", true).Limit(1).Find(&rows)
|
||||
return len(rows) > 0, result.Error
|
||||
}
|
||||
|
||||
func (r *memoryRepository) HasPendingExtraction(ctx context.Context, scope interfaces.MemoryScope) (bool, error) {
|
||||
return hasPendingExtraction(r.db.WithContext(ctx), scope)
|
||||
}
|
||||
|
||||
func (r *memoryRepository) EnqueuePendingSession(ctx context.Context, scope interfaces.MemoryScope, sessionID string, timeout time.Duration) (*types.MemorySubject, bool, error) {
|
||||
var snapshot types.MemorySubject
|
||||
shouldSend := false
|
||||
err := r.withSubject(ctx, scope, func(tx *gorm.DB, subject *types.MemorySubject) error {
|
||||
snapshot = *subject
|
||||
if err := importLegacySessions(tx, subject); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := enqueueExtractionSession(tx, subject, sessionID, true); err != nil {
|
||||
return err
|
||||
}
|
||||
now := time.Now()
|
||||
running := subject.ExtractionState.LeaseID != "" && subject.ExtractionState.LeaseUntil.After(now)
|
||||
queued := subject.ExtractScheduledAt != nil && now.Sub(*subject.ExtractScheduledAt) < timeout
|
||||
if !running && !queued {
|
||||
pending, err := hasPendingExtraction(tx, scope)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if pending {
|
||||
subject.ExtractScheduledAt = &now
|
||||
shouldSend = true
|
||||
}
|
||||
}
|
||||
return saveExtractionState(tx, subject)
|
||||
})
|
||||
return &snapshot, shouldSend, err
|
||||
}
|
||||
|
||||
func (r *memoryRepository) ClaimPendingSessions(ctx context.Context, scope interfaces.MemoryScope, fallbackSession, leaseID string, ttl time.Duration) (*types.MemoryExtractionBatch, error) {
|
||||
var batch *types.MemoryExtractionBatch
|
||||
err := r.withSubject(ctx, scope, func(tx *gorm.DB, subject *types.MemorySubject) error {
|
||||
now := time.Now()
|
||||
if subject.ExtractionState.LeaseID != "" && subject.ExtractionState.LeaseUntil.After(now) {
|
||||
batch = &types.MemoryExtractionBatch{RetryAt: subject.ExtractionState.LeaseUntil}
|
||||
return nil
|
||||
}
|
||||
if err := importLegacySessions(tx, subject); err != nil {
|
||||
return err
|
||||
}
|
||||
// Bootstrap legacy payloads once; a duplicate must not reactivate a drained row.
|
||||
if err := enqueueExtractionSession(tx, subject, fallbackSession, false); err != nil {
|
||||
return err
|
||||
}
|
||||
var sessions []types.MemoryExtractionSession
|
||||
if err := extractionRows(tx, scope).Where("pending = ?", true).
|
||||
Order("updated_at ASC, session_id ASC").
|
||||
Limit(types.MaxMemoryPendingSessions).Find(&sessions).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if len(sessions) == 0 {
|
||||
return saveExtractionState(tx, subject)
|
||||
}
|
||||
batch = &types.MemoryExtractionBatch{Sessions: sessions}
|
||||
subject.ExtractionState.LeaseID = leaseID
|
||||
subject.ExtractionState.LeaseUntil = now.Add(ttl)
|
||||
return saveExtractionState(tx, subject)
|
||||
})
|
||||
return batch, err
|
||||
}
|
||||
|
||||
func validExtractionLease(subject *types.MemorySubject, leaseID string) bool {
|
||||
return subject.ExtractionState.LeaseID == leaseID && subject.ExtractionState.LeaseUntil.After(time.Now())
|
||||
}
|
||||
|
||||
func (r *memoryRepository) CheckpointExtraction(ctx context.Context, scope interfaces.MemoryScope, leaseID string, session types.MemoryExtractionSession, cursor types.MemoryMessageCursor, drained bool) error {
|
||||
return r.withSubject(ctx, scope, func(tx *gorm.DB, subject *types.MemorySubject) error {
|
||||
if !validExtractionLease(subject, leaseID) {
|
||||
return types.ErrMemoryExtractionLeaseLost
|
||||
}
|
||||
var progress types.MemoryExtractionSession
|
||||
if err := extractionRows(tx, scope).Where("session_id = ?", session.SessionID).
|
||||
First(&progress).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if cursor.After(progress.Cursor) {
|
||||
progress.Cursor = cursor
|
||||
}
|
||||
// Updating just this row rotates unfinished work without rewriting the
|
||||
// subject's entire history. Completed cursors remain small indexed records.
|
||||
updates := map[string]interface{}{
|
||||
"cursor_at": progress.Cursor.At, "cursor_id": progress.Cursor.ID,
|
||||
"pending": !drained || progress.Revision != session.Revision, "updated_at": time.Now(),
|
||||
}
|
||||
if progress.FailedAt == nil {
|
||||
updates["failure_count"] = 0
|
||||
updates["failure_code"] = ""
|
||||
}
|
||||
return extractionRows(tx, scope).Where("session_id = ?", session.SessionID).Updates(updates).Error
|
||||
})
|
||||
}
|
||||
|
||||
func (r *memoryRepository) RecordExtractionFailure(
|
||||
ctx context.Context, scope interfaces.MemoryScope, leaseID string, failure interfaces.MemoryExtractionFailure,
|
||||
) (bool, error) {
|
||||
skip := false
|
||||
err := r.withSubject(ctx, scope, func(tx *gorm.DB, subject *types.MemorySubject) error {
|
||||
if !validExtractionLease(subject, leaseID) {
|
||||
return types.ErrMemoryExtractionLeaseLost
|
||||
}
|
||||
var progress types.MemoryExtractionSession
|
||||
if err := extractionRows(tx, scope).Where("session_id = ?", failure.Session.SessionID).
|
||||
First(&progress).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
attempts := 1
|
||||
if progress.FailedFrom.At.Equal(progress.Cursor.At) && progress.FailedFrom.ID == progress.Cursor.ID {
|
||||
attempts += progress.FailureCount
|
||||
}
|
||||
skip = attempts >= 3
|
||||
updates := map[string]interface{}{
|
||||
"failure_count": attempts, "failure_code": failure.Code, "updated_at": time.Now(),
|
||||
"failed_at": nil,
|
||||
"failed_from_at": progress.Cursor.At, "failed_from_id": progress.Cursor.ID,
|
||||
"failed_to_at": failure.End.At, "failed_to_id": failure.End.ID,
|
||||
}
|
||||
if skip {
|
||||
updates["failed_at"] = time.Now()
|
||||
}
|
||||
return extractionRows(tx, scope).Where("session_id = ?", failure.Session.SessionID).Updates(updates).Error
|
||||
})
|
||||
return skip, err
|
||||
}
|
||||
|
||||
func (r *memoryRepository) FinishExtraction(ctx context.Context, scope interfaces.MemoryScope, leaseID string) error {
|
||||
return r.withSubject(ctx, scope, func(tx *gorm.DB, subject *types.MemorySubject) error {
|
||||
if subject.ExtractionState.LeaseID != leaseID {
|
||||
return types.ErrMemoryExtractionLeaseLost
|
||||
}
|
||||
subject.ExtractionState.LeaseID = ""
|
||||
subject.ExtractionState.LeaseUntil = time.Time{}
|
||||
subject.ExtractScheduledAt = nil
|
||||
if err := saveExtractionState(tx, subject); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Model(subject).Update("last_extracted_at", time.Now()).Error
|
||||
})
|
||||
}
|
||||
|
||||
func (r *memoryRepository) ReleaseExtractionSlot(ctx context.Context, scope interfaces.MemoryScope, leaseID string) error {
|
||||
return r.withSubject(ctx, scope, func(tx *gorm.DB, subject *types.MemorySubject) error {
|
||||
if subject.ExtractionState.LeaseID != leaseID {
|
||||
return nil
|
||||
}
|
||||
subject.ExtractionState.LeaseID = ""
|
||||
subject.ExtractionState.LeaseUntil = time.Time{}
|
||||
subject.ExtractScheduledAt = nil
|
||||
return saveExtractionState(tx, subject)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// SaveItem serializes replacements with confirmation and manual edits. A
|
||||
// proposal can replace another proposal, but cannot retire an active fact.
|
||||
func (r *memoryRepository) SaveItem(ctx context.Context, scope interfaces.MemoryScope, item *types.MemoryItem, replacesID string) error {
|
||||
return r.withSubject(ctx, scope, func(tx *gorm.DB, _ *types.MemorySubject) error {
|
||||
query := func() *gorm.DB { return tx.Where("tenant_id = ? AND subject_id = ?", scope.TenantID, scope.SubjectID) }
|
||||
var target types.MemoryItem
|
||||
if replacesID != "" {
|
||||
if err := query().First(&target, "id = ?", replacesID).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return types.ErrMemoryConflict
|
||||
}
|
||||
return err
|
||||
}
|
||||
if target.Status != types.MemoryStatusActive && target.Status != types.MemoryStatusPending {
|
||||
// A successfully applied decision may be replayed after a failed
|
||||
// checkpoint. Return its replacement instead of writing it twice.
|
||||
var replacement types.MemoryItem
|
||||
if target.SupersededBy != "" && query().First(&replacement, "id = ?", target.SupersededBy).Error == nil &&
|
||||
replacement.Status == item.Status && replacement.Content == item.Content {
|
||||
*item = replacement
|
||||
return nil
|
||||
}
|
||||
return types.ErrMemoryConflict
|
||||
}
|
||||
}
|
||||
var live []*types.MemoryItem
|
||||
if err := query().Where("normalized_key = ? AND status IN ?", item.NormalizedKey,
|
||||
[]string{types.MemoryStatusActive, types.MemoryStatusPending}).Find(&live).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
for _, old := range live {
|
||||
if old.Content == item.Content && old.Status == item.Status {
|
||||
*item = *old
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if item.Status == types.MemoryStatusPending {
|
||||
if target.Status == types.MemoryStatusActive {
|
||||
item.ReplacesID = target.ID
|
||||
}
|
||||
if target.Status == types.MemoryStatusPending {
|
||||
item.ReplacesID = target.ReplacesID
|
||||
}
|
||||
if item.ReplacesID == "" {
|
||||
for _, old := range live {
|
||||
if old.Status == types.MemoryStatusActive {
|
||||
item.ReplacesID = old.ID
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
item.TenantID, item.SubjectID = scope.TenantID, scope.SubjectID
|
||||
if err := tx.Create(item).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
ids := make([]string, 0, len(live)+2)
|
||||
if target.ID != "" {
|
||||
live = append(live, &target)
|
||||
}
|
||||
if target.ReplacesID != "" && item.Status == types.MemoryStatusActive {
|
||||
ids = append(ids, target.ReplacesID)
|
||||
}
|
||||
for _, old := range live {
|
||||
if item.Status == types.MemoryStatusPending && old.Status == types.MemoryStatusActive {
|
||||
continue
|
||||
}
|
||||
ids = append(ids, old.ID)
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
return query().Model(&types.MemoryItem{}).
|
||||
Where("id <> ? AND (id IN ? OR replaces_id IN ?) AND status IN ?", item.ID, ids, ids,
|
||||
[]string{types.MemoryStatusActive, types.MemoryStatusPending}).
|
||||
Updates(map[string]interface{}{"status": types.MemoryStatusSuperseded, "invalid_at": time.Now(), "superseded_by": item.ID, "updated_at": time.Now()}).Error
|
||||
})
|
||||
}
|
||||
|
||||
func (r *memoryRepository) ConfirmPendingItem(ctx context.Context, scope interfaces.MemoryScope, id string) error {
|
||||
return r.withSubject(ctx, scope, func(tx *gorm.DB, _ *types.MemorySubject) error {
|
||||
query := func() *gorm.DB { return tx.Where("tenant_id = ? AND subject_id = ?", scope.TenantID, scope.SubjectID) }
|
||||
var item types.MemoryItem
|
||||
if err := query().First(&item, "id = ?", id).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if item.Status == types.MemoryStatusActive {
|
||||
return nil
|
||||
}
|
||||
if item.Status != types.MemoryStatusPending || (item.ExpiresAt != nil && !item.ExpiresAt.After(time.Now())) {
|
||||
return types.ErrMemoryConflict
|
||||
}
|
||||
if item.ReplacesID != "" {
|
||||
var target types.MemoryItem
|
||||
err := query().First(&target, "id = ?", item.ReplacesID).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) || (err == nil && target.Status != types.MemoryStatusActive) {
|
||||
return types.ErrMemoryConflict
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
now := time.Now()
|
||||
if err := query().Model(&types.MemoryItem{}).
|
||||
Where("id <> ? AND (normalized_key = ? OR id = ? OR (replaces_id <> '' AND replaces_id = ?)) AND status IN ?",
|
||||
id, item.NormalizedKey, item.ReplacesID, item.ReplacesID, []string{types.MemoryStatusActive, types.MemoryStatusPending}).
|
||||
Updates(map[string]interface{}{"status": types.MemoryStatusSuperseded, "invalid_at": now, "superseded_by": id, "updated_at": now}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return query().Model(&types.MemoryItem{}).Where("id = ?", id).
|
||||
Updates(map[string]interface{}{"status": types.MemoryStatusActive, "updated_at": now}).Error
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"academy/internal/logger"
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// fallbackVectorScanCap bounds the in-process fallback.
|
||||
//
|
||||
// One subject cannot hold more active memories than the workspace capacity
|
||||
// cap, which tops out in the low thousands, so this is a guard against a
|
||||
// corrupted scope rather than a real limit: a subject at the cap still gets
|
||||
// every one of its vectors scored, which is the whole point of the change.
|
||||
const fallbackVectorScanCap = 5000
|
||||
|
||||
// vectorColumnReady reports whether the database can do the distance
|
||||
// arithmetic itself.
|
||||
//
|
||||
// Checked once and cached. It is false on SQLite, and false on a PostgreSQL
|
||||
// deployment that never installed pgvector because its retrieval driver does
|
||||
// not use it — both of which keep working through the fallback below, just
|
||||
// with every vector crossing the wire.
|
||||
func (r *memoryRepository) vectorColumnReady() bool {
|
||||
r.vectorOnce.Do(func() {
|
||||
if r.db == nil || r.db.Dialector == nil || r.db.Dialector.Name() != "postgres" {
|
||||
return
|
||||
}
|
||||
r.vectorColumn = r.db.Migrator().HasColumn(&types.MemoryItemEmbedding{}, "embedding")
|
||||
})
|
||||
return r.vectorColumn
|
||||
}
|
||||
|
||||
// writeVectorColumn keeps the database's own vector type in step with the
|
||||
// stored blob. Best effort inside the caller's transaction: the blob is the
|
||||
// source of truth, and a row whose vector column is behind is picked up by
|
||||
// SyncVectorColumn rather than lost.
|
||||
func (r *memoryRepository) writeVectorColumn(tx *gorm.DB, itemID string, raw []byte) error {
|
||||
if !r.vectorColumnReady() || itemID == "" {
|
||||
return nil
|
||||
}
|
||||
literal := types.FormatEmbeddingLiteral(types.DecodeEmbedding(raw))
|
||||
if literal == "" {
|
||||
return nil
|
||||
}
|
||||
return tx.Exec(
|
||||
`UPDATE memory_item_embeddings SET embedding = ?::halfvec WHERE item_id = ?`,
|
||||
literal, itemID,
|
||||
).Error
|
||||
}
|
||||
|
||||
// vectorHitRow is one (item, distance) pair as the ranking query returns it.
|
||||
type vectorHitRow struct {
|
||||
ItemID string
|
||||
Score float64
|
||||
}
|
||||
|
||||
// SearchItemsByVector ranks a subject's whole vector set against one query.
|
||||
//
|
||||
// The candidate set is every vector the subject has, not a window of them.
|
||||
// This is the difference that matters: the previous implementation listed
|
||||
// items by importance, loaded the vectors belonging to that list, and scored
|
||||
// those — so relevance could only ever re-order what importance had already
|
||||
// chosen, and a matching memory outside the window was unreachable.
|
||||
func (r *memoryRepository) SearchItemsByVector(
|
||||
ctx context.Context, scope interfaces.MemoryScope, query interfaces.MemoryVectorQuery,
|
||||
) ([]interfaces.MemoryVectorHit, error) {
|
||||
if !scope.Valid() || query.ModelID == "" || len(query.Vector) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
limit := query.Limit
|
||||
if limit <= 0 {
|
||||
limit = 20
|
||||
}
|
||||
|
||||
var rows []vectorHitRow
|
||||
var err error
|
||||
if r.vectorColumnReady() {
|
||||
rows, err = r.rankInDatabase(ctx, scope, query, limit)
|
||||
} else {
|
||||
rows, err = r.rankInProcess(ctx, scope, query, limit)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
ids := make([]string, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
if row.Score >= query.MinScore {
|
||||
ids = append(ids, row.ItemID)
|
||||
}
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// Items are loaded separately rather than joined into the ranking query so
|
||||
// that neither path has to reproduce the column list of memory_items, and
|
||||
// so the ranking query stays narrow enough to be read at a glance.
|
||||
var items []*types.MemoryItem
|
||||
if err := r.scoped(ctx, scope).Where("id IN ?", ids).Find(&items).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
byID := make(map[string]*types.MemoryItem, len(items))
|
||||
for _, item := range items {
|
||||
byID[item.ID] = item
|
||||
}
|
||||
|
||||
hits := make([]interfaces.MemoryVectorHit, 0, len(ids))
|
||||
for _, row := range rows {
|
||||
item, ok := byID[row.ItemID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
hits = append(hits, interfaces.MemoryVectorHit{Item: item, Score: row.Score})
|
||||
}
|
||||
return hits, nil
|
||||
}
|
||||
|
||||
// rankInDatabase orders by cosine distance in SQL and returns only the top k.
|
||||
func (r *memoryRepository) rankInDatabase(
|
||||
ctx context.Context, scope interfaces.MemoryScope, query interfaces.MemoryVectorQuery, limit int,
|
||||
) ([]vectorHitRow, error) {
|
||||
literal := types.FormatEmbeddingLiteral(query.Vector)
|
||||
if literal == "" {
|
||||
return nil, nil
|
||||
}
|
||||
sql := `
|
||||
SELECT e.item_id AS item_id,
|
||||
1 - (e.embedding::halfvec <=> ?::halfvec) AS score
|
||||
FROM memory_item_embeddings e
|
||||
JOIN memory_items i
|
||||
ON i.id = e.item_id AND i.tenant_id = e.tenant_id AND i.subject_id = e.subject_id
|
||||
WHERE e.tenant_id = ? AND e.subject_id = ?
|
||||
AND e.model_id = ? AND e.dims = ? AND e.embedding IS NOT NULL
|
||||
AND i.status = ?
|
||||
AND (i.expires_at IS NULL OR i.expires_at > ?)`
|
||||
args := []interface{}{
|
||||
literal, scope.TenantID, scope.SubjectID,
|
||||
query.ModelID, len(query.Vector), types.MemoryStatusActive, time.Now(),
|
||||
}
|
||||
if len(query.Kinds) > 0 {
|
||||
sql += ` AND i.kind IN ?`
|
||||
args = append(args, query.Kinds)
|
||||
}
|
||||
// Ordering by the operator rather than by the computed score keeps the
|
||||
// expression identical to the one an index would be built on.
|
||||
sql += ` ORDER BY e.embedding::halfvec <=> ?::halfvec LIMIT ?`
|
||||
args = append(args, literal, limit)
|
||||
|
||||
var rows []vectorHitRow
|
||||
if err := r.db.WithContext(ctx).Raw(sql, args...).Scan(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// rankInProcess is the portable path: read this subject's vectors and score
|
||||
// them here. Bounded by the same capacity cap that bounds the subject itself,
|
||||
// so it still sees everything — it just pays to transfer it.
|
||||
func (r *memoryRepository) rankInProcess(
|
||||
ctx context.Context, scope interfaces.MemoryScope, query interfaces.MemoryVectorQuery, limit int,
|
||||
) ([]vectorHitRow, error) {
|
||||
type storedVector struct {
|
||||
ItemID string
|
||||
Vector []byte
|
||||
}
|
||||
sql := `
|
||||
SELECT e.item_id AS item_id, e.vector AS vector
|
||||
FROM memory_item_embeddings e
|
||||
JOIN memory_items i
|
||||
ON i.id = e.item_id AND i.tenant_id = e.tenant_id AND i.subject_id = e.subject_id
|
||||
WHERE e.tenant_id = ? AND e.subject_id = ?
|
||||
AND e.model_id = ? AND e.dims = ?
|
||||
AND i.status = ?
|
||||
AND (i.expires_at IS NULL OR i.expires_at > ?)`
|
||||
args := []interface{}{
|
||||
scope.TenantID, scope.SubjectID,
|
||||
query.ModelID, len(query.Vector), types.MemoryStatusActive, time.Now(),
|
||||
}
|
||||
if len(query.Kinds) > 0 {
|
||||
sql += ` AND i.kind IN ?`
|
||||
args = append(args, query.Kinds)
|
||||
}
|
||||
sql += ` LIMIT ?`
|
||||
args = append(args, fallbackVectorScanCap)
|
||||
|
||||
var stored []storedVector
|
||||
if err := r.db.WithContext(ctx).Raw(sql, args...).Scan(&stored).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows := make([]vectorHitRow, 0, len(stored))
|
||||
for _, row := range stored {
|
||||
vector := types.DecodeEmbedding(row.Vector)
|
||||
if len(vector) == 0 {
|
||||
continue
|
||||
}
|
||||
rows = append(rows, vectorHitRow{
|
||||
ItemID: row.ItemID,
|
||||
Score: types.CosineSimilarity(query.Vector, vector),
|
||||
})
|
||||
}
|
||||
sortVectorHitsDesc(rows)
|
||||
if len(rows) > limit {
|
||||
rows = rows[:limit]
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// sortVectorHitsDesc puts the closest match first.
|
||||
func sortVectorHitsDesc(rows []vectorHitRow) {
|
||||
sort.SliceStable(rows, func(i, j int) bool { return rows[i].Score > rows[j].Score })
|
||||
}
|
||||
|
||||
// SyncVectorColumn moves already-embedded rows into the database's vector
|
||||
// type. Rows written before migration 000095 hold only the blob, and a row the
|
||||
// SQL ranking cannot see is a memory that semantic recall cannot find — so this
|
||||
// has to drain without waiting for an embedding model to be called again.
|
||||
func (r *memoryRepository) SyncVectorColumn(
|
||||
ctx context.Context, scope interfaces.MemoryScope, limit int,
|
||||
) (int, error) {
|
||||
if !r.vectorColumnReady() || !scope.Valid() {
|
||||
return 0, nil
|
||||
}
|
||||
if limit <= 0 {
|
||||
limit = 500
|
||||
}
|
||||
type pending struct {
|
||||
ItemID string
|
||||
Vector []byte
|
||||
}
|
||||
var rows []pending
|
||||
err := r.db.WithContext(ctx).Raw(`
|
||||
SELECT item_id, vector FROM memory_item_embeddings
|
||||
WHERE tenant_id = ? AND subject_id = ?
|
||||
AND embedding IS NULL AND vector IS NOT NULL
|
||||
LIMIT ?`, scope.TenantID, scope.SubjectID, limit).Scan(&rows).Error
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
moved := 0
|
||||
for _, row := range rows {
|
||||
if err := r.writeVectorColumn(r.db.WithContext(ctx), row.ItemID, row.Vector); err != nil {
|
||||
logger.Warnf(ctx, "memory: sync vector column failed for %s: %v", row.ItemID, err)
|
||||
continue
|
||||
}
|
||||
moved++
|
||||
}
|
||||
return moved, nil
|
||||
}
|
||||
@@ -0,0 +1,642 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// messageRepository implements the message repository interface
|
||||
type messageRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewMessageRepository creates a new message repository
|
||||
func NewMessageRepository(db *gorm.DB) interfaces.MessageRepository {
|
||||
return &messageRepository{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
// CreateMessage creates a new message
|
||||
func (r *messageRepository) CreateMessage(
|
||||
ctx context.Context, message *types.Message,
|
||||
) (*types.Message, error) {
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Create(message).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return insertMessageArtifacts(tx, []*types.Message{message})
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return message, nil
|
||||
}
|
||||
|
||||
// GetMessage retrieves a message
|
||||
func (r *messageRepository) GetMessage(
|
||||
ctx context.Context, sessionID string, messageID string,
|
||||
) (*types.Message, error) {
|
||||
var message types.Message
|
||||
if err := r.db.WithContext(ctx).Where(
|
||||
"id = ? AND session_id = ?", messageID, sessionID,
|
||||
).First(&message).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := attachArtifacts(ctx, r.db, &message); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &message, nil
|
||||
}
|
||||
|
||||
// GetMessagesBySession retrieves all messages for a session with pagination.
|
||||
//
|
||||
// The secondary sort on id is not cosmetic: messages created in the same
|
||||
// millisecond would otherwise come back in an order the database is free to
|
||||
// vary between calls, which makes a fork boundary drawn at one of them
|
||||
// irreproducible.
|
||||
func (r *messageRepository) GetMessagesBySession(
|
||||
ctx context.Context, sessionID string, page int, pageSize int,
|
||||
) ([]*types.Message, error) {
|
||||
var messages []*types.Message
|
||||
if err := r.db.WithContext(ctx).Where("session_id = ?", sessionID).
|
||||
Order("created_at ASC, id ASC").
|
||||
Offset((page - 1) * pageSize).Limit(pageSize).Find(&messages).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := attachArtifacts(ctx, r.db, messages...); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return messages, nil
|
||||
}
|
||||
|
||||
// GetRecentMessagesBySession retrieves recent messages for a session
|
||||
func (r *messageRepository) GetRecentMessagesBySession(
|
||||
ctx context.Context, sessionID string, limit int,
|
||||
) ([]*types.Message, error) {
|
||||
var messages []*types.Message
|
||||
if err := r.db.WithContext(ctx).Where(
|
||||
"session_id = ?", sessionID,
|
||||
).Order("created_at DESC").Limit(limit).Find(&messages).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
slices.SortFunc(messages, func(a, b *types.Message) int {
|
||||
cmp := a.CreatedAt.Compare(b.CreatedAt)
|
||||
if cmp == 0 {
|
||||
if a.Role == "user" { // User messages come first
|
||||
return -1
|
||||
}
|
||||
return 1 // Assistant messages come last
|
||||
}
|
||||
return cmp
|
||||
})
|
||||
if err := attachArtifacts(ctx, r.db, messages...); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return messages, nil
|
||||
}
|
||||
|
||||
// SessionHasIncompleteAssistant reports whether any assistant message in the
|
||||
// session is still generating. Rewind uses this instead of paging oldest
|
||||
// messages, so a late incomplete turn is not hidden behind a 1000-row window.
|
||||
func (r *messageRepository) SessionHasIncompleteAssistant(
|
||||
ctx context.Context, sessionID string,
|
||||
) (bool, error) {
|
||||
if sessionID == "" {
|
||||
return false, nil
|
||||
}
|
||||
var id string
|
||||
err := r.db.WithContext(ctx).Model(&types.Message{}).
|
||||
Select("id").
|
||||
Where("session_id = ? AND role = ? AND is_completed = ?", sessionID, "assistant", false).
|
||||
Limit(1).
|
||||
Scan(&id).Error
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return id != "", nil
|
||||
}
|
||||
|
||||
// GetMessagesBySessionBeforeTime retrieves messages from a session created before a specific time
|
||||
func (r *messageRepository) GetMessagesBySessionBeforeTime(
|
||||
ctx context.Context, sessionID string, beforeTime time.Time, limit int,
|
||||
) ([]*types.Message, error) {
|
||||
var messages []*types.Message
|
||||
if err := r.db.WithContext(ctx).Where(
|
||||
"session_id = ? AND created_at < ?", sessionID, beforeTime,
|
||||
).Order("created_at DESC").Limit(limit).Find(&messages).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
slices.SortFunc(messages, func(a, b *types.Message) int {
|
||||
cmp := a.CreatedAt.Compare(b.CreatedAt)
|
||||
if cmp == 0 {
|
||||
if a.Role == "user" { // User messages come first
|
||||
return -1
|
||||
}
|
||||
return 1 // Assistant messages come last
|
||||
}
|
||||
return cmp
|
||||
})
|
||||
if err := attachArtifacts(ctx, r.db, messages...); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return messages, nil
|
||||
}
|
||||
|
||||
// ListMessagesBySessionAfterTime returns the oldest messages created after
|
||||
// afterTime, so a caller holding a watermark can walk a session forward
|
||||
// without skipping anything when it has more new messages than one page.
|
||||
func (r *messageRepository) ListMessagesBySessionAfterTime(
|
||||
ctx context.Context, sessionID string, afterTime time.Time, limit int,
|
||||
) ([]*types.Message, error) {
|
||||
var messages []*types.Message
|
||||
query := r.db.WithContext(ctx).Where("session_id = ?", sessionID)
|
||||
if !afterTime.IsZero() {
|
||||
query = query.Where("created_at > ?", afterTime)
|
||||
}
|
||||
if err := query.Order("created_at ASC").Limit(limit).Find(&messages).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := attachArtifacts(ctx, r.db, messages...); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return messages, nil
|
||||
}
|
||||
|
||||
// ListMessagesBySessionAfterCursor uses a stable tie-breaker for memory paging.
|
||||
func (r *messageRepository) ListMessagesBySessionAfterCursor(ctx context.Context, sessionID string, cursor types.MemoryMessageCursor, limit int) ([]*types.Message, error) {
|
||||
var messages []*types.Message
|
||||
query := r.db.WithContext(ctx).Where("session_id = ?", sessionID)
|
||||
if !cursor.At.IsZero() || cursor.ID != "" {
|
||||
query = query.Where("created_at > ? OR (created_at = ? AND id > ?)", cursor.At, cursor.At, cursor.ID)
|
||||
}
|
||||
if err := query.Order("created_at ASC, id ASC").Limit(limit).Find(&messages).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := attachArtifacts(ctx, r.db, messages...); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return messages, nil
|
||||
}
|
||||
|
||||
// ListMessagesBySessionBeforeCursor pages a session backwards: up to limit
|
||||
// messages sorting strictly before the (before, beforeID) cursor, newest first.
|
||||
// A zero cursor starts from the newest message. The ID tie-breaker keeps a page
|
||||
// boundary from skipping messages that share a timestamp.
|
||||
func (r *messageRepository) ListMessagesBySessionBeforeCursor(
|
||||
ctx context.Context, sessionID string, before time.Time, beforeID string, limit int,
|
||||
) ([]*types.Message, error) {
|
||||
var messages []*types.Message
|
||||
query := r.db.WithContext(ctx).Where("session_id = ?", sessionID)
|
||||
if !before.IsZero() || beforeID != "" {
|
||||
query = query.Where("created_at < ? OR (created_at = ? AND id < ?)", before, before, beforeID)
|
||||
}
|
||||
if err := query.Order("created_at DESC, id DESC").Limit(limit).Find(&messages).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := attachArtifacts(ctx, r.db, messages...); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return messages, nil
|
||||
}
|
||||
|
||||
// ListMessagesBySessionUpTo returns every message of a session that sorts
|
||||
// strictly before the (boundary, boundaryID) cursor, oldest first.
|
||||
//
|
||||
// The cursor is composite rather than a bare timestamp because a fork boundary
|
||||
// must be reproducible: two messages written in the same millisecond are
|
||||
// ordered by ID, and the caller's boundary message must be excluded regardless
|
||||
// of how many peers share its timestamp.
|
||||
func (r *messageRepository) ListMessagesBySessionUpTo(
|
||||
ctx context.Context, sessionID string, boundary time.Time, boundaryID string,
|
||||
) ([]*types.Message, error) {
|
||||
var messages []*types.Message
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("session_id = ?", sessionID).
|
||||
Where("created_at < ? OR (created_at = ? AND id < ?)", boundary, boundary, boundaryID).
|
||||
Order("created_at ASC, id ASC").
|
||||
Find(&messages).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := attachArtifacts(ctx, r.db, messages...); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return messages, nil
|
||||
}
|
||||
|
||||
// ListAssistantCheckpointsUpTo returns the assistant messages strictly before
|
||||
// the (boundary, boundaryID) cursor, oldest first, carrying only the columns
|
||||
// that identify a workspace checkpoint.
|
||||
//
|
||||
// Rewind asks "does kept history still reach a commit SHA, and did it contain
|
||||
// an assistant turn at all". ListMessagesBySessionUpTo can answer that, but it
|
||||
// selects every column and joins artifacts for the whole conversation to do
|
||||
// so. This is the same question against a fraction of the rows and bytes.
|
||||
func (r *messageRepository) ListAssistantCheckpointsUpTo(
|
||||
ctx context.Context, sessionID string, boundary time.Time, boundaryID string,
|
||||
) ([]*types.Message, error) {
|
||||
var messages []*types.Message
|
||||
if err := r.db.WithContext(ctx).
|
||||
Model(&types.Message{}).
|
||||
Select("id", "session_id", "role", "created_at", "sandbox_checkpoint").
|
||||
Where("session_id = ? AND role = ?", sessionID, "assistant").
|
||||
Where("created_at < ? OR (created_at = ? AND id < ?)", boundary, boundary, boundaryID).
|
||||
Order("created_at ASC, id ASC").
|
||||
Find(&messages).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return messages, nil
|
||||
}
|
||||
|
||||
// UpdateMessage updates an existing message. Artifacts are rewritten only
|
||||
// when message.Artifacts is non-nil (see writeMessageArtifacts).
|
||||
func (r *messageRepository) UpdateMessage(ctx context.Context, message *types.Message) error {
|
||||
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Model(&types.Message{}).Where(
|
||||
"id = ? AND session_id = ?", message.ID, message.SessionID,
|
||||
).Updates(message).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
// Updates skips zero values; written on its own so a resumed or
|
||||
// closed run can clear it.
|
||||
if err := tx.Model(&types.Message{}).Where(
|
||||
"id = ? AND session_id = ?", message.ID, message.SessionID,
|
||||
).Update("run_state", message.RunState).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return writeMessageArtifacts(tx, message)
|
||||
})
|
||||
}
|
||||
|
||||
// DeleteMessagesFrom soft-deletes every message of a session at or after the
|
||||
// (boundary, boundaryID) composite cursor and returns the deleted rows, oldest
|
||||
// first, so the caller can clean up what hangs off them.
|
||||
//
|
||||
// inclusive selects the rewind semantics: a user rewind point is dropped along
|
||||
// with everything after it (the client prefills that question back into the
|
||||
// composer), while an assistant rewind point survives and the conversation
|
||||
// resumes after it. The cursor is composite for the same reason
|
||||
// ListMessagesBySessionUpTo is — two messages written in the same millisecond
|
||||
// are ordered by ID, so the cut is reproducible.
|
||||
//
|
||||
// The read and the delete share one transaction: the returned rows must be
|
||||
// exactly the rows that went away, or the cleanup that follows would act on a
|
||||
// different set than the conversation lost.
|
||||
func (r *messageRepository) DeleteMessagesFrom(
|
||||
ctx context.Context, sessionID string, boundary time.Time, boundaryID string, inclusive bool,
|
||||
) ([]*types.Message, error) {
|
||||
condition := "created_at > ? OR (created_at = ? AND id > ?)"
|
||||
if inclusive {
|
||||
condition = "created_at > ? OR (created_at = ? AND id >= ?)"
|
||||
}
|
||||
|
||||
var deleted []*types.Message
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
scope := func() *gorm.DB {
|
||||
return tx.Where("session_id = ?", sessionID).
|
||||
Where(condition, boundary, boundary, boundaryID)
|
||||
}
|
||||
if err := scope().Order("created_at ASC, id ASC").Find(&deleted).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if len(deleted) == 0 {
|
||||
return nil
|
||||
}
|
||||
return scope().Delete(&types.Message{}).Error
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return deleted, nil
|
||||
}
|
||||
|
||||
// DeleteMessage deletes a message
|
||||
func (r *messageRepository) DeleteMessage(ctx context.Context, sessionID string, messageID string) error {
|
||||
return r.db.WithContext(ctx).Where(
|
||||
"id = ? AND session_id = ?", messageID, sessionID,
|
||||
).Delete(&types.Message{}).Error
|
||||
}
|
||||
|
||||
// GetFirstMessageOfUser retrieves the first message from a user in a session
|
||||
func (r *messageRepository) GetFirstMessageOfUser(ctx context.Context, sessionID string) (*types.Message, error) {
|
||||
var message types.Message
|
||||
if err := r.db.WithContext(ctx).Where(
|
||||
"session_id = ? and role = ?", sessionID, "user",
|
||||
).Order("created_at ASC").First(&message).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := attachArtifacts(ctx, r.db, &message); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &message, nil
|
||||
}
|
||||
|
||||
// GetMessageByRequestID retrieves a message by request ID
|
||||
func (r *messageRepository) GetMessageByRequestID(
|
||||
ctx context.Context, sessionID string, requestID string,
|
||||
) (*types.Message, error) {
|
||||
var message types.Message
|
||||
|
||||
result := r.db.WithContext(ctx).
|
||||
Where("session_id = ? AND request_id = ?", sessionID, requestID).
|
||||
First(&message)
|
||||
|
||||
if result.Error != nil {
|
||||
if result.Error == gorm.ErrRecordNotFound {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, result.Error
|
||||
}
|
||||
if err := attachArtifacts(ctx, r.db, &message); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &message, nil
|
||||
}
|
||||
|
||||
// SearchMessagesByKeyword searches messages by keyword across sessions for a tenant
|
||||
func (r *messageRepository) SearchMessagesByKeyword(
|
||||
ctx context.Context, tenantID uint64, ownerID, keyword string, sessionIDs []string, limit int,
|
||||
) ([]*types.MessageWithSession, error) {
|
||||
if limit <= 0 {
|
||||
limit = 20
|
||||
}
|
||||
|
||||
// ILIKE is Postgres-only; SQLite (Lite build) and MySQL lack the keyword,
|
||||
// so mirror the session-list search with LOWER() on both sides. ESCAPE ?
|
||||
// pairs with escapeLikeKeyword: SQLite has no default LIKE escape
|
||||
// character, so without it \% and \_ would never match a literal wildcard.
|
||||
contentLikeExpr := "LOWER(messages.content) LIKE LOWER(?) ESCAPE ?"
|
||||
if r.db.Name() == "postgres" {
|
||||
contentLikeExpr = "messages.content ILIKE ? ESCAPE ?"
|
||||
}
|
||||
|
||||
var results []*types.MessageWithSession
|
||||
|
||||
query := r.db.WithContext(ctx).
|
||||
Table("messages").
|
||||
Select("messages.*, sessions.title as session_title").
|
||||
Joins("INNER JOIN sessions ON sessions.id = messages.session_id AND sessions.deleted_at IS NULL").
|
||||
Where("sessions.tenant_id = ? AND sessions.kind = ''", tenantID).
|
||||
Where("messages.deleted_at IS NULL").
|
||||
Where(contentLikeExpr, "%"+escapeLikeKeyword(keyword)+"%", likeEscapeChar)
|
||||
|
||||
// Matches the scoping used when listing sessions, including the legacy
|
||||
// allowance for tenant-level sessions created before per-user ownership.
|
||||
if ownerID != "" {
|
||||
query = query.Where("(sessions.user_id = ? OR sessions.user_id IS NULL OR sessions.user_id = '')", ownerID)
|
||||
}
|
||||
|
||||
if len(sessionIDs) > 0 {
|
||||
query = query.Where("messages.session_id IN ?", sessionIDs)
|
||||
}
|
||||
|
||||
if err := query.Order("messages.created_at DESC").Limit(limit).Find(&results).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := attachArtifactsWithSession(ctx, r.db, results); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return results, nil
|
||||
}
|
||||
|
||||
// OwnedSessionIDs narrows a set of session ids to the ones this person owns.
|
||||
//
|
||||
// The vector path finds messages through a shared knowledge base that has no
|
||||
// notion of who wrote them, so ownership has to be re-established here before
|
||||
// anything is returned.
|
||||
func (r *messageRepository) OwnedSessionIDs(
|
||||
ctx context.Context, tenantID uint64, ownerID string, sessionIDs []string,
|
||||
) (map[string]bool, error) {
|
||||
owned := make(map[string]bool, len(sessionIDs))
|
||||
if len(sessionIDs) == 0 {
|
||||
return owned, nil
|
||||
}
|
||||
var ids []string
|
||||
query := r.db.WithContext(ctx).
|
||||
Table("sessions").
|
||||
Select("id").
|
||||
Where("tenant_id = ? AND kind = ''", tenantID).
|
||||
Where("deleted_at IS NULL").
|
||||
Where("id IN ?", sessionIDs)
|
||||
if ownerID != "" {
|
||||
query = query.Where("(user_id = ? OR user_id IS NULL OR user_id = '')", ownerID)
|
||||
}
|
||||
if err := query.Pluck("id", &ids).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, id := range ids {
|
||||
owned[id] = true
|
||||
}
|
||||
return owned, nil
|
||||
}
|
||||
|
||||
// GetMessagesByKnowledgeIDs retrieves messages by their associated Knowledge IDs
|
||||
func (r *messageRepository) GetMessagesByKnowledgeIDs(
|
||||
ctx context.Context, knowledgeIDs []string,
|
||||
) ([]*types.MessageWithSession, error) {
|
||||
if len(knowledgeIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var results []*types.MessageWithSession
|
||||
if err := r.db.WithContext(ctx).
|
||||
Table("messages").
|
||||
Select("messages.*, sessions.title as session_title").
|
||||
Joins("INNER JOIN sessions ON sessions.id = messages.session_id AND sessions.deleted_at IS NULL").
|
||||
Where("messages.deleted_at IS NULL").
|
||||
Where("messages.knowledge_id IN ?", knowledgeIDs).
|
||||
Find(&results).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := attachArtifactsWithSession(ctx, r.db, results); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return results, nil
|
||||
}
|
||||
|
||||
// GetMessagesByRequestIDs retrieves messages by request ID inside one session
|
||||
// (used to fetch Q&A pair partners). Empty sessionID is treated as no match.
|
||||
func (r *messageRepository) GetMessagesByRequestIDs(
|
||||
ctx context.Context, sessionID string, requestIDs []string,
|
||||
) ([]*types.MessageWithSession, error) {
|
||||
if sessionID == "" || len(requestIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var results []*types.MessageWithSession
|
||||
if err := r.db.WithContext(ctx).
|
||||
Table("messages").
|
||||
Select("messages.*, sessions.title as session_title").
|
||||
Joins("INNER JOIN sessions ON sessions.id = messages.session_id AND sessions.deleted_at IS NULL").
|
||||
Where("messages.deleted_at IS NULL").
|
||||
Where("messages.session_id = ?", sessionID).
|
||||
Where("messages.request_id IN ?", requestIDs).
|
||||
Find(&results).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := attachArtifactsWithSession(ctx, r.db, results); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return results, nil
|
||||
}
|
||||
|
||||
// GetKnowledgeIDsBySessionID retrieves all knowledge IDs for messages in a session
|
||||
func (r *messageRepository) GetKnowledgeIDsBySessionID(
|
||||
ctx context.Context, sessionID string,
|
||||
) ([]string, error) {
|
||||
var knowledgeIDs []string
|
||||
if err := r.db.WithContext(ctx).
|
||||
Model(&types.Message{}).
|
||||
Where("session_id = ? AND knowledge_id != '' AND knowledge_id IS NOT NULL AND deleted_at IS NULL", sessionID).
|
||||
Pluck("knowledge_id", &knowledgeIDs).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return knowledgeIDs, nil
|
||||
}
|
||||
|
||||
// UpdateMessageImages updates only the images JSONB column for a message.
|
||||
// Uses Select to force GORM to include the column even when struct-based
|
||||
// Updates would otherwise skip custom Valuer types.
|
||||
func (r *messageRepository) UpdateMessageImages(ctx context.Context, sessionID, messageID string, images types.MessageImages) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Model(&types.Message{}).
|
||||
Where("id = ? AND session_id = ?", messageID, sessionID).
|
||||
Update("images", images).Error
|
||||
}
|
||||
|
||||
// UpdateMessageRenderedContent updates only the rendered_content column for a message.
|
||||
func (r *messageRepository) UpdateMessageRenderedContent(ctx context.Context, sessionID, messageID string, renderedContent string) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Model(&types.Message{}).
|
||||
Where("id = ? AND session_id = ?", messageID, sessionID).
|
||||
Update("rendered_content", renderedContent).Error
|
||||
}
|
||||
|
||||
// UpdateMessageContextCheckpoint updates only the context_checkpoint column, so
|
||||
// it cannot race a full-row write of the same message. A write that matches no
|
||||
// row (the turn was deleted, or the ID is not this session's assistant
|
||||
// message) is an error rather than a silent success.
|
||||
func (r *messageRepository) UpdateMessageContextCheckpoint(
|
||||
ctx context.Context, sessionID, messageID string, checkpoint *types.ContextCheckpoint,
|
||||
) error {
|
||||
result := r.db.WithContext(ctx).
|
||||
Model(&types.Message{}).
|
||||
Where("id = ? AND session_id = ? AND role = 'assistant'", messageID, sessionID).
|
||||
Update("context_checkpoint", checkpoint)
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
return fmt.Errorf("no assistant message %s in session %s", messageID, sessionID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetLatestContextCheckpoint returns the newest checkpointed assistant message.
|
||||
// Only the identity and ordering columns come back with the checkpoint: the
|
||||
// caller matches it against turns it has already loaded. It walks
|
||||
// idx_messages_session_created_id backwards and stops at the first
|
||||
// checkpointed row, which in a compacting session is a recent one.
|
||||
func (r *messageRepository) GetLatestContextCheckpoint(
|
||||
ctx context.Context, sessionID string,
|
||||
) (*types.Message, error) {
|
||||
var messages []*types.Message
|
||||
if err := r.db.WithContext(ctx).
|
||||
Select("id", "session_id", "request_id", "role", "created_at", "context_checkpoint").
|
||||
Where("session_id = ? AND role = 'assistant' AND context_checkpoint IS NOT NULL", sessionID).
|
||||
Order("created_at DESC, id DESC").
|
||||
Limit(1).
|
||||
Find(&messages).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(messages) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return messages[0], nil
|
||||
}
|
||||
|
||||
// DeleteMessagesBySessionID deletes all messages belonging to a session (soft delete)
|
||||
func (r *messageRepository) DeleteMessagesBySessionID(ctx context.Context, sessionID string) error {
|
||||
return r.db.WithContext(ctx).Where("session_id = ?", sessionID).Delete(&types.Message{}).Error
|
||||
}
|
||||
|
||||
// UpdateMessageKnowledgeID updates the knowledge_id field for a message
|
||||
func (r *messageRepository) UpdateMessageKnowledgeID(
|
||||
ctx context.Context, messageID string, knowledgeID string,
|
||||
) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Model(&types.Message{}).
|
||||
Where("id = ?", messageID).
|
||||
Update("knowledge_id", knowledgeID).Error
|
||||
}
|
||||
|
||||
// RewriteSandboxCheckpoints retargets copied checkpoints onto the forked
|
||||
// session's live sandbox. CommitSHA / CommittedAt are left untouched: the git
|
||||
// objects are in the snapshot, only the sandbox identity changed.
|
||||
func (r *messageRepository) RewriteSandboxCheckpoints(
|
||||
ctx context.Context, sessionID, oldSandboxID, newSandboxID string,
|
||||
) error {
|
||||
if sessionID == "" || oldSandboxID == "" || newSandboxID == "" || oldSandboxID == newSandboxID {
|
||||
return nil
|
||||
}
|
||||
var messages []*types.Message
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("session_id = ?", sessionID).
|
||||
Find(&messages).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
for _, message := range messages {
|
||||
if message == nil || message.SandboxCheckpoint == nil {
|
||||
continue
|
||||
}
|
||||
if message.SandboxCheckpoint.SandboxID != oldSandboxID {
|
||||
continue
|
||||
}
|
||||
updated := *message.SandboxCheckpoint
|
||||
updated.SandboxID = newSandboxID
|
||||
if err := r.db.WithContext(ctx).
|
||||
Model(&types.Message{}).
|
||||
Where("id = ? AND session_id = ?", message.ID, sessionID).
|
||||
Update("sandbox_checkpoint", updated).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetSessionAttachments returns every user-uploaded attachment in creation
|
||||
// order while projecting only the attachments JSON column.
|
||||
func (r *messageRepository) GetSessionAttachments(
|
||||
ctx context.Context, sessionID string,
|
||||
) (types.MessageAttachments, error) {
|
||||
if sessionID == "" {
|
||||
return nil, nil
|
||||
}
|
||||
var rows []struct {
|
||||
Attachments types.MessageAttachments `gorm:"column:attachments"`
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
}
|
||||
if err := r.db.WithContext(ctx).
|
||||
Model(&types.Message{}).
|
||||
Select("attachments", "created_at").
|
||||
Where("session_id = ? AND deleted_at IS NULL", sessionID).
|
||||
Order("created_at ASC").
|
||||
Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := make(types.MessageAttachments, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
result = append(result, row.Attachments...)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,450 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// Artifacts live in message_artifacts, not on the message row. Every loader in
|
||||
// this package that returns messages goes through attachArtifacts, and every
|
||||
// writer goes through writeMessageArtifacts, so callers keep working with
|
||||
// Message.Artifacts as if it were a column.
|
||||
|
||||
// artifactLoadBatch bounds the IN list when loading artifacts for many
|
||||
// messages; SQLite caps bound parameters per statement.
|
||||
const artifactLoadBatch = 500
|
||||
|
||||
// writeMessageArtifacts replaces the stored artifacts of one message. A nil
|
||||
// list means "not loaded" and leaves the rows untouched; an empty non-nil list
|
||||
// clears them.
|
||||
//
|
||||
// A delete that already happened is re-applied on top of the incoming list, by
|
||||
// position. The caller usually carries the tombstones itself (they round-trip
|
||||
// through MessageArtifact.DeletedAt), but it may be holding a slice it read
|
||||
// before the delete — this is a full replace, so that snapshot would resurrect
|
||||
// the row while its bytes are already being reclaimed, leaving a live-looking
|
||||
// entry whose download 404s. Deletion is the one property of a row that a stale
|
||||
// writer must not be able to undo.
|
||||
func writeMessageArtifacts(tx *gorm.DB, message *types.Message) error {
|
||||
if message == nil || message.Artifacts == nil || message.ID == "" {
|
||||
return nil
|
||||
}
|
||||
deleted, err := deletedArtifactPositions(tx, message.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Where("message_id = ?", message.ID).
|
||||
Delete(&types.MessageArtifactRecord{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
rows := types.NewMessageArtifactRecords(message.SessionID, message.ID, message.Artifacts)
|
||||
if len(rows) == 0 {
|
||||
return nil
|
||||
}
|
||||
for i := range rows {
|
||||
if at, ok := deleted[rows[i].Position]; ok && rows[i].DeletedAt == nil {
|
||||
rows[i].DeletedAt = at
|
||||
}
|
||||
}
|
||||
return tx.CreateInBatches(rows, 100).Error
|
||||
}
|
||||
|
||||
// deletedArtifactPositions returns the stored deletion times of a message's
|
||||
// tombstoned artifacts, keyed by position.
|
||||
func deletedArtifactPositions(tx *gorm.DB, messageID string) (map[int]*time.Time, error) {
|
||||
var rows []types.MessageArtifactRecord
|
||||
if err := tx.Select("position", "deleted_at").
|
||||
Where("message_id = ? AND deleted_at IS NOT NULL", messageID).
|
||||
Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
out := make(map[int]*time.Time, len(rows))
|
||||
for _, row := range rows {
|
||||
out[row.Position] = row.DeletedAt
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// insertMessageArtifacts writes the artifacts of freshly created messages.
|
||||
// Unlike writeMessageArtifacts it skips the delete, since new messages have
|
||||
// no rows yet.
|
||||
func insertMessageArtifacts(tx *gorm.DB, messages []*types.Message) error {
|
||||
var rows []types.MessageArtifactRecord
|
||||
for _, m := range messages {
|
||||
if m == nil || m.ID == "" {
|
||||
continue
|
||||
}
|
||||
rows = append(rows, types.NewMessageArtifactRecords(m.SessionID, m.ID, m.Artifacts)...)
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return nil
|
||||
}
|
||||
return tx.CreateInBatches(rows, 100).Error
|
||||
}
|
||||
|
||||
// loadArtifactsByMessage returns each message's artifacts in position order.
|
||||
// Every requested id is present in the result, with an empty list when the
|
||||
// message has none.
|
||||
//
|
||||
// Tombstones (deleted_at set) are deliberately included: position is the index
|
||||
// the download endpoint addresses a file by, so skipping a deleted row here
|
||||
// would renumber every later file in the message. Callers that render a list
|
||||
// filter with MessageArtifacts.Live.
|
||||
func loadArtifactsByMessage(
|
||||
ctx context.Context, db *gorm.DB, messageIDs []string,
|
||||
) (map[string]types.MessageArtifacts, error) {
|
||||
out := make(map[string]types.MessageArtifacts, len(messageIDs))
|
||||
for _, id := range messageIDs {
|
||||
out[id] = types.MessageArtifacts{}
|
||||
}
|
||||
for start := 0; start < len(messageIDs); start += artifactLoadBatch {
|
||||
end := min(start+artifactLoadBatch, len(messageIDs))
|
||||
var rows []types.MessageArtifactRecord
|
||||
if err := db.WithContext(ctx).
|
||||
Where("message_id IN ?", messageIDs[start:end]).
|
||||
Order("message_id ASC, position ASC").
|
||||
Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, row := range rows {
|
||||
out[row.MessageID] = append(out[row.MessageID], row.Artifact())
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// attachArtifacts fills Message.Artifacts on every message in place.
|
||||
func attachArtifacts(ctx context.Context, db *gorm.DB, messages ...*types.Message) error {
|
||||
ids := make([]string, 0, len(messages))
|
||||
for _, m := range messages {
|
||||
if m != nil && m.ID != "" {
|
||||
ids = append(ids, m.ID)
|
||||
}
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
byMessage, err := loadArtifactsByMessage(ctx, db, ids)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, m := range messages {
|
||||
if m != nil && m.ID != "" {
|
||||
m.Artifacts = byMessage[m.ID]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// attachArtifactsWithSession is attachArtifacts for search-style results.
|
||||
func attachArtifactsWithSession(ctx context.Context, db *gorm.DB, results []*types.MessageWithSession) error {
|
||||
messages := make([]*types.Message, 0, len(results))
|
||||
for _, r := range results {
|
||||
if r != nil {
|
||||
messages = append(messages, &r.Message)
|
||||
}
|
||||
}
|
||||
return attachArtifacts(ctx, db, messages...)
|
||||
}
|
||||
|
||||
// GetSessionArtifacts returns every skill-produced MessageArtifact recorded
|
||||
// against a live message of the session, in message then position order.
|
||||
//
|
||||
// User-deleted artifacts are included as tombstones. ArtifactCollector builds
|
||||
// its de-duplication set from this call, and a tombstone is exactly what stops
|
||||
// it re-attaching a file the user deleted while the sandbox copy — same path,
|
||||
// same mtime — is still sitting there. Display paths filter with
|
||||
// MessageArtifacts.Live.
|
||||
func (r *messageRepository) GetSessionArtifacts(
|
||||
ctx context.Context, sessionID string,
|
||||
) (types.MessageArtifacts, error) {
|
||||
if sessionID == "" {
|
||||
return nil, nil
|
||||
}
|
||||
var rows []types.MessageArtifactRecord
|
||||
if err := r.db.WithContext(ctx).
|
||||
Table("message_artifacts AS ma").
|
||||
Select("ma.*").
|
||||
Joins("JOIN messages m ON m.id = ma.message_id AND m.deleted_at IS NULL").
|
||||
Where("ma.session_id = ?", sessionID).
|
||||
Order("m.created_at ASC, m.id ASC, ma.position ASC").
|
||||
Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := make(types.MessageArtifacts, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
result = append(result, row.Artifact())
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// ListLiveArtifactsByMessageIDs returns undeleted artifact rows for the given
|
||||
// messages. It does not join messages, so rewind can tombstone files after
|
||||
// those messages have already been soft-deleted.
|
||||
func (r *messageRepository) ListLiveArtifactsByMessageIDs(
|
||||
ctx context.Context, sessionID string, messageIDs []string,
|
||||
) ([]types.MessageArtifactRecord, error) {
|
||||
if sessionID == "" || len(messageIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var rows []types.MessageArtifactRecord
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("session_id = ? AND message_id IN ? AND deleted_at IS NULL", sessionID, messageIDs).
|
||||
Order("message_id ASC, position ASC").
|
||||
Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// RecordRestoredArtifactMtime stamps a same-content sandbox restore's mtime
|
||||
// onto this session's artifacts at sourcePath whose content already hashed to
|
||||
// hash, mirroring MessageArtifacts.WithRestoredMtime: other versions at the
|
||||
// path and empty-hash legacy rows are left alone.
|
||||
//
|
||||
// Tombstones are left alone too. A tombstone records what was deleted and when;
|
||||
// its (path, mtime) pair is the key that keeps the collector from re-attaching
|
||||
// the sandbox copy, so moving that mtime forward would quietly re-open the
|
||||
// door it is there to hold shut.
|
||||
func (r *messageRepository) RecordRestoredArtifactMtime(
|
||||
ctx context.Context, sessionID, sourcePath string, mod time.Time, hash string,
|
||||
) error {
|
||||
if sessionID == "" || sourcePath == "" || hash == "" {
|
||||
return nil
|
||||
}
|
||||
var rows []types.MessageArtifactRecord
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("session_id = ? AND source_path = ? AND content_hash = ? AND deleted_at IS NULL",
|
||||
sessionID, sourcePath, hash).
|
||||
Find(&rows).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
for _, row := range rows {
|
||||
if types.ParseArtifactModTime(row.ModTime).Equal(mod) {
|
||||
continue
|
||||
}
|
||||
if err := r.db.WithContext(ctx).
|
||||
Model(&types.MessageArtifactRecord{}).
|
||||
Where("id = ?", row.ID).
|
||||
Update("mod_time", types.FormatArtifactModTime(mod)).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListArtifactLibrary returns the latest version of every artifact in the
|
||||
// sessions the caller can see, newest first.
|
||||
//
|
||||
// User-deleted artifacts are excluded, versions included: deleting the newest
|
||||
// version of a file surfaces the one before it, which is why the delete path
|
||||
// tombstones every version of a library row at once.
|
||||
//
|
||||
// Session visibility mirrors the home sidebar, i.e. the "web" bucket of
|
||||
// sessionRepository.QueryPaged: same tenant, not deleted, owned by the user or
|
||||
// a legacy tenant-level row, not a skill-maintenance session, and not an IM,
|
||||
// embed or API session. IM sessions are created without an owner, so without
|
||||
// the web predicate every member would see every IM chat's files. Artifacts
|
||||
// of soft-deleted messages are hidden. Versions are grouped by (session, source path); artifacts without a
|
||||
// source path stand alone. A later answer that references an earlier file
|
||||
// stores another row with the same URL, so versions are counted as distinct
|
||||
// URLs (the max DENSE_RANK over url, since window functions reject DISTINCT).
|
||||
func (r *messageRepository) ListArtifactLibrary(
|
||||
ctx context.Context, q *types.ArtifactLibraryQuery,
|
||||
) ([]*types.ArtifactLibraryItem, int64, error) {
|
||||
var (
|
||||
where []string
|
||||
args []any
|
||||
)
|
||||
where = append(where, "s.tenant_id = ?", "s.kind = ''", "s.deleted_at IS NULL", "ma.deleted_at IS NULL")
|
||||
args = append(args, q.TenantID)
|
||||
if q.UserID != "" {
|
||||
where = append(where, "(s.user_id = ? OR s.user_id IS NULL OR s.user_id = '')")
|
||||
args = append(args, q.UserID)
|
||||
}
|
||||
where = append(where, "(s.description IS NULL OR s.description NOT LIKE ?)", webSessionPredicate)
|
||||
args = append(args, types.SkillMaintenanceSessionMarker+"%")
|
||||
args = append(args, webSessionPredicateArgs()...)
|
||||
if kw := strings.TrimSpace(q.Keyword); kw != "" {
|
||||
where = append(where, "LOWER(ma.file_name) LIKE LOWER(?) ESCAPE ?")
|
||||
args = append(args, "%"+escapeLikeKeyword(kw)+"%", likeEscapeChar)
|
||||
}
|
||||
if len(q.FileTypes) > 0 {
|
||||
where = append(where, "LOWER(ma.file_type) IN ?")
|
||||
args = append(args, q.FileTypes)
|
||||
}
|
||||
|
||||
grouped := `SELECT ma.session_id, ma.message_id, ma.position, ma.url, ma.file_name,
|
||||
ma.file_type, ma.file_size, ma.source_path, ma.created_at, ma.id,
|
||||
s.title AS session_title,
|
||||
CASE WHEN ma.source_path = '' THEN ma.id ELSE ma.source_path END AS version_key,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY ma.session_id, CASE WHEN ma.source_path = '' THEN ma.id ELSE ma.source_path END
|
||||
ORDER BY ma.created_at DESC, m.created_at DESC, ma.position DESC
|
||||
) AS version_rank,
|
||||
DENSE_RANK() OVER (
|
||||
PARTITION BY ma.session_id, CASE WHEN ma.source_path = '' THEN ma.id ELSE ma.source_path END
|
||||
ORDER BY ma.url
|
||||
) AS url_rank
|
||||
FROM message_artifacts ma
|
||||
JOIN messages m ON m.id = ma.message_id AND m.deleted_at IS NULL
|
||||
JOIN sessions s ON s.id = ma.session_id
|
||||
LEFT JOIN im_channel_sessions ics ON ics.session_id = s.id
|
||||
WHERE ` + strings.Join(where, " AND ")
|
||||
ranked := `SELECT g.*, MAX(g.url_rank) OVER (PARTITION BY g.session_id, g.version_key) AS version_count
|
||||
FROM (` + grouped + `) g`
|
||||
|
||||
var total int64
|
||||
if err := r.db.WithContext(ctx).
|
||||
Raw("SELECT COUNT(*) FROM ("+ranked+") latest WHERE version_rank = 1", args...).
|
||||
Scan(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
page := max(q.Page, 1)
|
||||
size := q.PageSize
|
||||
if size < 1 {
|
||||
size = 20
|
||||
}
|
||||
items := make([]*types.ArtifactLibraryItem, 0)
|
||||
listArgs := append(append([]any{}, args...), size, (page-1)*size)
|
||||
if err := r.db.WithContext(ctx).
|
||||
Raw("SELECT * FROM ("+ranked+") latest WHERE version_rank = 1 "+
|
||||
"ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?", listArgs...).
|
||||
Scan(&items).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return items, total, nil
|
||||
}
|
||||
|
||||
// FindSessionArtifact returns one live artifact row of the session addressed by
|
||||
// (message, position) — the same coordinates the download endpoint uses.
|
||||
// A tombstone is reported as not found, so deleting twice is a 404 rather than
|
||||
// a second blob reclaim.
|
||||
func (r *messageRepository) FindSessionArtifact(
|
||||
ctx context.Context, sessionID, messageID string, position int,
|
||||
) (*types.MessageArtifactRecord, error) {
|
||||
if sessionID == "" || messageID == "" || position < 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var row types.MessageArtifactRecord
|
||||
err := r.db.WithContext(ctx).
|
||||
Table("message_artifacts AS ma").
|
||||
Select("ma.*").
|
||||
Joins("JOIN messages m ON m.id = ma.message_id AND m.deleted_at IS NULL").
|
||||
Where("ma.session_id = ? AND ma.message_id = ? AND ma.position = ? AND ma.deleted_at IS NULL",
|
||||
sessionID, messageID, position).
|
||||
Take(&row).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &row, nil
|
||||
}
|
||||
|
||||
// FindSessionArtifactVersions returns every live row of the session that shares
|
||||
// sourcePath, i.e. the regenerations the artifact library folds into one entry.
|
||||
// An empty sourcePath has no version group — the artifact stands alone — so the
|
||||
// caller gets nothing back and deletes just the row it started from.
|
||||
func (r *messageRepository) FindSessionArtifactVersions(
|
||||
ctx context.Context, sessionID, sourcePath string,
|
||||
) ([]types.MessageArtifactRecord, error) {
|
||||
if sessionID == "" || sourcePath == "" {
|
||||
return nil, nil
|
||||
}
|
||||
var rows []types.MessageArtifactRecord
|
||||
if err := r.db.WithContext(ctx).
|
||||
Table("message_artifacts AS ma").
|
||||
Select("ma.*").
|
||||
Joins("JOIN messages m ON m.id = ma.message_id AND m.deleted_at IS NULL").
|
||||
Where("ma.session_id = ? AND ma.source_path = ? AND ma.deleted_at IS NULL", sessionID, sourcePath).
|
||||
Order("ma.created_at ASC, ma.id ASC").
|
||||
Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// SoftDeleteSessionArtifacts tombstones the given rows and returns the subset it
|
||||
// actually marked. Rows another caller already tombstoned are left out, so the
|
||||
// caller reclaims exactly the blobs it took ownership of and a concurrent
|
||||
// duplicate delete reclaims none of them twice.
|
||||
//
|
||||
// url is left on the tombstone on purpose: if the blob reclaim that follows
|
||||
// fails, the storage path is still on record for a later GC pass.
|
||||
func (r *messageRepository) SoftDeleteSessionArtifacts(
|
||||
ctx context.Context, sessionID string, refs []types.ArtifactRef, at time.Time,
|
||||
) ([]types.ArtifactRef, error) {
|
||||
if sessionID == "" || len(refs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
marked := make([]types.ArtifactRef, 0, len(refs))
|
||||
// All or nothing. Deleting a file's versions is several statements, and a
|
||||
// failure partway through would leave some versions hidden from every
|
||||
// listing with their bytes never reclaimed, while the caller reports an
|
||||
// error and the user's retry 404s on the row that did get marked.
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
marked = marked[:0]
|
||||
// One statement per ref: the pairs are a handful at most (a message's
|
||||
// artifacts, or one file's versions), and a composite IN list is not
|
||||
// portable across PostgreSQL and SQLite.
|
||||
for _, ref := range refs {
|
||||
if ref.MessageID == "" || ref.Position < 0 {
|
||||
continue
|
||||
}
|
||||
res := tx.Model(&types.MessageArtifactRecord{}).
|
||||
Where("session_id = ? AND message_id = ? AND position = ? AND deleted_at IS NULL",
|
||||
sessionID, ref.MessageID, ref.Position).
|
||||
Update("deleted_at", at.UTC())
|
||||
if res.Error != nil {
|
||||
return res.Error
|
||||
}
|
||||
if res.RowsAffected > 0 {
|
||||
marked = append(marked, ref)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return marked, nil
|
||||
}
|
||||
|
||||
// CountLiveArtifactsByURL counts artifact rows that still point at a stored
|
||||
// object and have not been deleted, across every session.
|
||||
//
|
||||
// It is the last guard before a delete reclaims bytes. The catalog's binding
|
||||
// count is the primary one, but it does not cover every way two rows come to
|
||||
// share a URL: a forked session's copied rows carry the parent's storage URLs
|
||||
// without a binding of their own (CreateForked copies the rows, it does not
|
||||
// re-Bind them), a deployment may store raw provider paths that the catalog
|
||||
// never registered, and a later answer that re-attaches an earlier file writes
|
||||
// another row with the same URL. Any of those still needs the bytes.
|
||||
//
|
||||
// Soft-deleted messages are counted on purpose: their rows can come back, and
|
||||
// keeping a blob costs less than a restored message pointing at nothing.
|
||||
func (r *messageRepository) CountLiveArtifactsByURL(ctx context.Context, url string) (int64, error) {
|
||||
if url == "" {
|
||||
return 0, nil
|
||||
}
|
||||
var count int64
|
||||
if err := r.db.WithContext(ctx).
|
||||
Model(&types.MessageArtifactRecord{}).
|
||||
Where("url = ? AND deleted_at IS NULL", url).
|
||||
Count(&count).Error; err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// Deleting an artifact must not renumber the ones after it: position is the
|
||||
// index the download endpoint addresses a file by, so a shift would hand an
|
||||
// existing link the wrong blob.
|
||||
func TestSoftDeleteKeepsPositionsStable(t *testing.T) {
|
||||
db := newArtifactTestDB(t)
|
||||
repo := NewMessageRepository(db)
|
||||
ctx := context.Background()
|
||||
created := time.Date(2026, 9, 1, 2, 0, 0, 0, time.UTC)
|
||||
|
||||
msg, err := repo.CreateMessage(ctx, &types.Message{
|
||||
SessionID: "s1", RequestID: "r1", Role: "assistant",
|
||||
Artifacts: types.MessageArtifacts{
|
||||
testArtifact("a.pptx", "/w/a.pptx", created),
|
||||
testArtifact("b.pptx", "/w/b.pptx", created),
|
||||
testArtifact("c.pptx", "/w/c.pptx", created),
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
marked, err := repo.SoftDeleteSessionArtifacts(ctx, "s1",
|
||||
[]types.ArtifactRef{{MessageID: msg.ID, Position: 1}}, created)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []types.ArtifactRef{{MessageID: msg.ID, Position: 1}}, marked)
|
||||
|
||||
got, err := repo.GetMessage(ctx, "s1", msg.ID)
|
||||
require.NoError(t, err)
|
||||
// GORM only soft-deletes for fields typed gorm.DeletedAt. Ours is a plain
|
||||
// *time.Time precisely so the tombstone keeps loading and holding its slot.
|
||||
require.Len(t, got.Artifacts, 3, "the tombstone keeps its slot in the list")
|
||||
require.False(t, got.Artifacts[0].Deleted())
|
||||
require.True(t, got.Artifacts[1].Deleted())
|
||||
require.Equal(t, "c.pptx", got.Artifacts[2].FileName, "index 2 still addresses the third file")
|
||||
|
||||
require.Equal(t, types.MessageArtifacts{got.Artifacts[0], got.Artifacts[2]}, got.Artifacts.Live())
|
||||
}
|
||||
|
||||
// The collector de-duplicates sandbox files against the session's rows. The
|
||||
// tombstone has to stay in that set, or the next collect re-attaches the file
|
||||
// the user just deleted — its sandbox mtime has not moved.
|
||||
func TestSoftDeletedArtifactsStayInSessionDedupSet(t *testing.T) {
|
||||
db := newArtifactTestDB(t)
|
||||
repo := NewMessageRepository(db)
|
||||
ctx := context.Background()
|
||||
created := time.Date(2026, 9, 1, 2, 0, 0, 0, time.UTC)
|
||||
|
||||
msg, err := repo.CreateMessage(ctx, &types.Message{
|
||||
SessionID: "s1", RequestID: "r1", Role: "assistant",
|
||||
Artifacts: types.MessageArtifacts{testArtifact("a.pptx", "/w/a.pptx", created)},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
_, err = repo.SoftDeleteSessionArtifacts(ctx, "s1",
|
||||
[]types.ArtifactRef{{MessageID: msg.ID, Position: 0}}, created)
|
||||
require.NoError(t, err)
|
||||
|
||||
all, err := repo.GetSessionArtifacts(ctx, "s1")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, all, 1)
|
||||
require.True(t, all[0].Deleted())
|
||||
require.Equal(t, "/w/a.pptx", all[0].SourcePath, "source path and mtime survive for de-duplication")
|
||||
require.Empty(t, all.Live())
|
||||
}
|
||||
|
||||
// Rewriting a message's artifacts (any UpdateMessage carrying a non-nil list)
|
||||
// goes through the same slice, so the tombstone has to round-trip.
|
||||
func TestWriteMessageArtifactsPreservesTombstones(t *testing.T) {
|
||||
db := newArtifactTestDB(t)
|
||||
repo := NewMessageRepository(db)
|
||||
ctx := context.Background()
|
||||
created := time.Date(2026, 9, 1, 2, 0, 0, 0, time.UTC)
|
||||
|
||||
msg, err := repo.CreateMessage(ctx, &types.Message{
|
||||
SessionID: "s1", RequestID: "r1", Role: "assistant",
|
||||
Artifacts: types.MessageArtifacts{
|
||||
testArtifact("a.pptx", "/w/a.pptx", created),
|
||||
testArtifact("b.pptx", "/w/b.pptx", created),
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
_, err = repo.SoftDeleteSessionArtifacts(ctx, "s1",
|
||||
[]types.ArtifactRef{{MessageID: msg.ID, Position: 0}}, created)
|
||||
require.NoError(t, err)
|
||||
|
||||
reloaded, err := repo.GetMessage(ctx, "s1", msg.ID)
|
||||
require.NoError(t, err)
|
||||
reloaded.Content = "edited"
|
||||
require.NoError(t, repo.UpdateMessage(ctx, reloaded))
|
||||
|
||||
got, err := repo.GetMessage(ctx, "s1", msg.ID)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got.Artifacts, 2)
|
||||
require.True(t, got.Artifacts[0].Deleted(), "the tombstone survives a message rewrite")
|
||||
require.False(t, got.Artifacts[1].Deleted())
|
||||
}
|
||||
|
||||
func TestFindSessionArtifactSkipsTombstones(t *testing.T) {
|
||||
db := newArtifactTestDB(t)
|
||||
repo := NewMessageRepository(db)
|
||||
ctx := context.Background()
|
||||
created := time.Date(2026, 9, 1, 2, 0, 0, 0, time.UTC)
|
||||
|
||||
msg, err := repo.CreateMessage(ctx, &types.Message{
|
||||
SessionID: "s1", RequestID: "r1", Role: "assistant",
|
||||
Artifacts: types.MessageArtifacts{testArtifact("a.pptx", "/w/a.pptx", created)},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
found, err := repo.FindSessionArtifact(ctx, "s1", msg.ID, 0)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, found)
|
||||
require.Equal(t, "a.pptx", found.FileName)
|
||||
|
||||
missing, err := repo.FindSessionArtifact(ctx, "s1", msg.ID, 9)
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, missing)
|
||||
|
||||
_, err = repo.SoftDeleteSessionArtifacts(ctx, "s1",
|
||||
[]types.ArtifactRef{{MessageID: msg.ID, Position: 0}}, created)
|
||||
require.NoError(t, err)
|
||||
|
||||
gone, err := repo.FindSessionArtifact(ctx, "s1", msg.ID, 0)
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, gone, "a tombstone reads as absent, so a second delete is a 404")
|
||||
|
||||
// And a second delete claims nothing, so its caller reclaims no blobs.
|
||||
marked, err := repo.SoftDeleteSessionArtifacts(ctx, "s1",
|
||||
[]types.ArtifactRef{{MessageID: msg.ID, Position: 0}}, created)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, marked, "a second delete claims nothing, so its caller reclaims no blobs")
|
||||
}
|
||||
|
||||
// Versions are the rows of one session sharing a sandbox path — what the
|
||||
// artifact library folds into a single entry with a version count.
|
||||
func TestFindSessionArtifactVersions(t *testing.T) {
|
||||
db := newArtifactTestDB(t)
|
||||
repo := NewMessageRepository(db)
|
||||
ctx := context.Background()
|
||||
base := time.Date(2026, 9, 1, 2, 0, 0, 0, time.UTC)
|
||||
|
||||
first, err := repo.CreateMessage(ctx, &types.Message{
|
||||
SessionID: "s1", RequestID: "r1", Role: "assistant", CreatedAt: base,
|
||||
Artifacts: types.MessageArtifacts{testArtifact("report.pptx", "/w/report.pptx", base)},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
v2 := testArtifact("report.pptx", "/w/report.pptx", base.Add(time.Hour))
|
||||
v2.URL = "local://blobs/report-v2.pptx"
|
||||
_, err = repo.CreateMessage(ctx, &types.Message{
|
||||
SessionID: "s1", RequestID: "r2", Role: "assistant", CreatedAt: base.Add(time.Hour),
|
||||
Artifacts: types.MessageArtifacts{v2, testArtifact("other.csv", "/w/other.csv", base)},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
// Another session's file at the same sandbox path is a different file.
|
||||
_, err = repo.CreateMessage(ctx, &types.Message{
|
||||
SessionID: "s2", RequestID: "r3", Role: "assistant", CreatedAt: base,
|
||||
Artifacts: types.MessageArtifacts{testArtifact("report.pptx", "/w/report.pptx", base)},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
versions, err := repo.FindSessionArtifactVersions(ctx, "s1", "/w/report.pptx")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, versions, 2)
|
||||
|
||||
// An artifact with no sandbox path has no version group.
|
||||
none, err := repo.FindSessionArtifactVersions(ctx, "s1", "")
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, none)
|
||||
|
||||
_, err = repo.SoftDeleteSessionArtifacts(ctx, "s1",
|
||||
[]types.ArtifactRef{{MessageID: first.ID, Position: 0}}, base)
|
||||
require.NoError(t, err)
|
||||
versions, err = repo.FindSessionArtifactVersions(ctx, "s1", "/w/report.pptx")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, versions, 1, "already-deleted versions drop out")
|
||||
}
|
||||
|
||||
func TestListArtifactLibraryHidesDeletedArtifacts(t *testing.T) {
|
||||
db := newArtifactTestDB(t)
|
||||
repo := NewMessageRepository(db)
|
||||
ctx := context.Background()
|
||||
base := time.Date(2026, 9, 1, 2, 0, 0, 0, time.UTC)
|
||||
mine := createSession(t, db, &types.Session{TenantID: 7, UserID: "alice", Title: "我的会话"})
|
||||
|
||||
first, err := repo.CreateMessage(ctx, &types.Message{
|
||||
SessionID: mine, RequestID: "r1", Role: "assistant", CreatedAt: base,
|
||||
Artifacts: types.MessageArtifacts{testArtifact("report.pptx", "/w/report.pptx", base)},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
v2 := testArtifact("report.pptx", "/w/report.pptx", base.Add(time.Hour))
|
||||
v2.URL = "local://blobs/report-v2.pptx"
|
||||
latest, err := repo.CreateMessage(ctx, &types.Message{
|
||||
SessionID: mine, RequestID: "r2", Role: "assistant", CreatedAt: base.Add(time.Hour),
|
||||
Artifacts: types.MessageArtifacts{v2},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
query := &types.ArtifactLibraryQuery{TenantID: 7, UserID: "alice", Page: 1, PageSize: 20}
|
||||
items, total, err := repo.ListArtifactLibrary(ctx, query)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 1, total)
|
||||
require.Equal(t, 2, items[0].VersionCount)
|
||||
|
||||
// Deleting only the newest version surfaces the one before it — which is
|
||||
// why the delete path tombstones every version of a library row at once.
|
||||
_, err = repo.SoftDeleteSessionArtifacts(ctx, mine,
|
||||
[]types.ArtifactRef{{MessageID: latest.ID, Position: 0}}, base)
|
||||
require.NoError(t, err)
|
||||
items, total, err = repo.ListArtifactLibrary(ctx, query)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 1, total)
|
||||
require.Equal(t, first.ID, items[0].MessageID)
|
||||
require.Equal(t, 1, items[0].VersionCount)
|
||||
|
||||
_, err = repo.SoftDeleteSessionArtifacts(ctx, mine,
|
||||
[]types.ArtifactRef{{MessageID: first.ID, Position: 0}}, base)
|
||||
require.NoError(t, err)
|
||||
items, total, err = repo.ListArtifactLibrary(ctx, query)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 0, total)
|
||||
require.Empty(t, items)
|
||||
}
|
||||
|
||||
// A stale writer must not be able to undo a delete. writeMessageArtifacts is a
|
||||
// full replace, so a caller holding a pre-delete snapshot would resurrect the
|
||||
// row while its bytes are already being reclaimed.
|
||||
func TestWriteMessageArtifactsCannotResurrectATombstone(t *testing.T) {
|
||||
db := newArtifactTestDB(t)
|
||||
repo := NewMessageRepository(db)
|
||||
ctx := context.Background()
|
||||
created := time.Date(2026, 9, 1, 2, 0, 0, 0, time.UTC)
|
||||
|
||||
msg, err := repo.CreateMessage(ctx, &types.Message{
|
||||
SessionID: "s1", RequestID: "r1", Role: "assistant",
|
||||
Artifacts: types.MessageArtifacts{
|
||||
testArtifact("a.pptx", "/w/a.pptx", created),
|
||||
testArtifact("b.pptx", "/w/b.pptx", created),
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
// A snapshot taken before the delete, still carrying both as live.
|
||||
stale, err := repo.GetMessage(ctx, "s1", msg.ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = repo.SoftDeleteSessionArtifacts(ctx, "s1",
|
||||
[]types.ArtifactRef{{MessageID: msg.ID, Position: 0}}, created)
|
||||
require.NoError(t, err)
|
||||
|
||||
stale.Content = "edited"
|
||||
require.NoError(t, repo.UpdateMessage(ctx, stale))
|
||||
|
||||
got, err := repo.GetMessage(ctx, "s1", msg.ID)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got.Artifacts, 2)
|
||||
require.True(t, got.Artifacts[0].Deleted(), "the stale write must not bring the deleted row back")
|
||||
require.False(t, got.Artifacts[1].Deleted())
|
||||
}
|
||||
|
||||
// Deleting a file's versions is several statements; a failure partway through
|
||||
// must not leave some of them hidden with their bytes never reclaimed.
|
||||
func TestSoftDeleteSessionArtifactsIsAtomic(t *testing.T) {
|
||||
db := newArtifactTestDB(t)
|
||||
repo := NewMessageRepository(db)
|
||||
ctx := context.Background()
|
||||
created := time.Date(2026, 9, 1, 2, 0, 0, 0, time.UTC)
|
||||
|
||||
msg, err := repo.CreateMessage(ctx, &types.Message{
|
||||
SessionID: "s1", RequestID: "r1", Role: "assistant",
|
||||
Artifacts: types.MessageArtifacts{
|
||||
testArtifact("a.pptx", "/w/a.pptx", created),
|
||||
testArtifact("b.pptx", "/w/b.pptx", created),
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Dropping the table mid-transaction is the cheapest way to make the
|
||||
// second statement fail after the first one succeeded.
|
||||
require.NoError(t, db.Exec(
|
||||
`CREATE TRIGGER fail_second BEFORE UPDATE ON message_artifacts
|
||||
WHEN NEW.position = 1
|
||||
BEGIN SELECT RAISE(ABORT, 'boom'); END`).Error)
|
||||
|
||||
_, err = repo.SoftDeleteSessionArtifacts(ctx, "s1", []types.ArtifactRef{
|
||||
{MessageID: msg.ID, Position: 0},
|
||||
{MessageID: msg.ID, Position: 1},
|
||||
}, created)
|
||||
require.Error(t, err)
|
||||
|
||||
require.NoError(t, db.Exec("DROP TRIGGER fail_second").Error)
|
||||
got, err := repo.GetMessage(ctx, "s1", msg.ID)
|
||||
require.NoError(t, err)
|
||||
require.False(t, got.Artifacts[0].Deleted(), "the first mark must roll back with the failed second one")
|
||||
require.False(t, got.Artifacts[1].Deleted())
|
||||
}
|
||||
|
||||
// The last guard before reclaiming bytes: a fork's copied rows carry the
|
||||
// parent's storage URLs without a binding of their own.
|
||||
func TestCountLiveArtifactsByURLSpansSessions(t *testing.T) {
|
||||
db := newArtifactTestDB(t)
|
||||
repo := NewMessageRepository(db)
|
||||
ctx := context.Background()
|
||||
created := time.Date(2026, 9, 1, 2, 0, 0, 0, time.UTC)
|
||||
|
||||
shared := testArtifact("report.pptx", "/w/report.pptx", created)
|
||||
parent, err := repo.CreateMessage(ctx, &types.Message{
|
||||
SessionID: "s1", RequestID: "r1", Role: "assistant",
|
||||
Artifacts: types.MessageArtifacts{shared},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
// The fork copy: new session and message, same storage URL.
|
||||
forked, err := repo.CreateMessage(ctx, &types.Message{
|
||||
SessionID: "s2", RequestID: "r2", Role: "assistant",
|
||||
Artifacts: types.MessageArtifacts{shared},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
count, err := repo.CountLiveArtifactsByURL(ctx, shared.URL)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 2, count)
|
||||
|
||||
_, err = repo.SoftDeleteSessionArtifacts(ctx, "s1",
|
||||
[]types.ArtifactRef{{MessageID: parent.ID, Position: 0}}, created)
|
||||
require.NoError(t, err)
|
||||
count, err = repo.CountLiveArtifactsByURL(ctx, shared.URL)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 1, count, "the fork still needs the bytes")
|
||||
|
||||
_, err = repo.SoftDeleteSessionArtifacts(ctx, "s2",
|
||||
[]types.ArtifactRef{{MessageID: forked.ID, Position: 0}}, created)
|
||||
require.NoError(t, err)
|
||||
count, err = repo.CountLiveArtifactsByURL(ctx, shared.URL)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 0, count, "now nothing points at them")
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func newArtifactTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.AutoMigrate(
|
||||
&types.Session{}, &types.Message{}, &types.MessageArtifactRecord{}, &testIMChannelSession{},
|
||||
))
|
||||
return db
|
||||
}
|
||||
|
||||
func testArtifact(name, sourcePath string, created time.Time) types.MessageArtifact {
|
||||
return types.MessageArtifact{
|
||||
URL: "local://blobs/" + name,
|
||||
FileName: name,
|
||||
FileType: ".pptx",
|
||||
FileSize: 1024,
|
||||
SourcePath: sourcePath,
|
||||
// Nanoseconds on purpose: the collector matches files on the exact mtime.
|
||||
ModTime: time.Date(2026, 9, 1, 10, 0, 0, 123456789, time.FixedZone("CST", 8*3600)),
|
||||
CreatedAt: created,
|
||||
}
|
||||
}
|
||||
|
||||
func createSession(t *testing.T, db *gorm.DB, s *types.Session) string {
|
||||
t.Helper()
|
||||
require.NoError(t, db.Create(s).Error)
|
||||
return s.ID
|
||||
}
|
||||
|
||||
func TestMessageArtifactsRoundTripThroughTable(t *testing.T) {
|
||||
db := newArtifactTestDB(t)
|
||||
repo := NewMessageRepository(db)
|
||||
ctx := context.Background()
|
||||
created := time.Date(2026, 9, 1, 2, 0, 0, 0, time.UTC)
|
||||
|
||||
msg, err := repo.CreateMessage(ctx, &types.Message{
|
||||
SessionID: "s1", RequestID: "r1", Role: "assistant",
|
||||
Artifacts: types.MessageArtifacts{
|
||||
testArtifact("a.pptx", "/w/a.pptx", created),
|
||||
testArtifact("b.pptx", "/w/b.pptx", created),
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
var stored int64
|
||||
require.NoError(t, db.Model(&types.MessageArtifactRecord{}).Where("message_id = ?", msg.ID).Count(&stored).Error)
|
||||
require.EqualValues(t, 2, stored, "artifacts are written to message_artifacts")
|
||||
|
||||
got, err := repo.GetMessage(ctx, "s1", msg.ID)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got.Artifacts, 2)
|
||||
require.Equal(t, "a.pptx", got.Artifacts[0].FileName)
|
||||
require.Equal(t, "b.pptx", got.Artifacts[1].FileName)
|
||||
require.True(t, got.Artifacts[0].ModTime.Equal(testArtifact("", "", created).ModTime),
|
||||
"mtime survives at nanosecond precision")
|
||||
require.True(t, got.Artifacts[0].CreatedAt.Equal(created))
|
||||
|
||||
// A partial struct (Artifacts nil) must not wipe the stored rows.
|
||||
require.NoError(t, repo.UpdateMessage(ctx, &types.Message{ID: msg.ID, SessionID: "s1", Content: "edited"}))
|
||||
got, err = repo.GetMessage(ctx, "s1", msg.ID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "edited", got.Content)
|
||||
require.Len(t, got.Artifacts, 2)
|
||||
|
||||
// A non-nil list replaces them.
|
||||
got.Artifacts = types.MessageArtifacts{testArtifact("c.pptx", "/w/c.pptx", created)}
|
||||
require.NoError(t, repo.UpdateMessage(ctx, got))
|
||||
listed, err := repo.GetMessagesBySession(ctx, "s1", 1, 10)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, listed, 1)
|
||||
require.Len(t, listed[0].Artifacts, 1)
|
||||
require.Equal(t, "c.pptx", listed[0].Artifacts[0].FileName)
|
||||
|
||||
session, err := repo.GetSessionArtifacts(ctx, "s1")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, session, 1)
|
||||
|
||||
// Soft-deleted messages drop out of the session listing.
|
||||
require.NoError(t, repo.DeleteMessage(ctx, "s1", msg.ID))
|
||||
session, err = repo.GetSessionArtifacts(ctx, "s1")
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, session)
|
||||
}
|
||||
|
||||
func TestMessagesWithoutArtifactsLoadAsEmpty(t *testing.T) {
|
||||
db := newArtifactTestDB(t)
|
||||
repo := NewMessageRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
msg, err := repo.CreateMessage(ctx, &types.Message{SessionID: "s1", RequestID: "r1", Role: "user"})
|
||||
require.NoError(t, err)
|
||||
got, err := repo.GetMessage(ctx, "s1", msg.ID)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, got.Artifacts)
|
||||
require.Empty(t, got.Artifacts)
|
||||
}
|
||||
|
||||
func TestRecordRestoredArtifactMtimeUpdatesMatchingRows(t *testing.T) {
|
||||
db := newArtifactTestDB(t)
|
||||
repo := NewMessageRepository(db).(*messageRepository)
|
||||
ctx := context.Background()
|
||||
created := time.Date(2026, 9, 1, 2, 0, 0, 0, time.UTC)
|
||||
|
||||
withHash := func(a types.MessageArtifact, hash string) types.MessageArtifact {
|
||||
a.ContentHash = hash
|
||||
return a
|
||||
}
|
||||
v1 := withHash(testArtifact("a.pptx", "/w/a.pptx", created), "hash-a")
|
||||
v2 := withHash(testArtifact("a.pptx", "/w/a.pptx", created.Add(time.Hour)), "hash-b")
|
||||
v2.URL = "local://blobs/a-v2.pptx"
|
||||
msg, err := repo.CreateMessage(ctx, &types.Message{
|
||||
SessionID: "s1", RequestID: "r1", Role: "assistant",
|
||||
Artifacts: types.MessageArtifacts{v1, v2, testArtifact("b.pptx", "/w/b.pptx", created)},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
originalMod := testArtifact("", "", created).ModTime
|
||||
|
||||
restored := time.Date(2026, 9, 2, 8, 30, 0, 987654321, time.UTC)
|
||||
require.NoError(t, repo.RecordRestoredArtifactMtime(ctx, "s1", "/w/a.pptx", restored, "hash-a"))
|
||||
// An empty hash never matches, so it must change nothing.
|
||||
require.NoError(t, repo.RecordRestoredArtifactMtime(ctx, "s1", "/w/b.pptx", restored, ""))
|
||||
|
||||
got, err := repo.GetMessage(ctx, "s1", msg.ID)
|
||||
require.NoError(t, err)
|
||||
require.True(t, got.Artifacts[0].ModTime.Equal(restored), "the version whose content matches gets the mtime")
|
||||
require.Equal(t, "hash-a", got.Artifacts[0].ContentHash)
|
||||
require.True(t, got.Artifacts[1].ModTime.Equal(originalMod), "other versions at the path stay put")
|
||||
require.Equal(t, "hash-b", got.Artifacts[1].ContentHash, "hashes are never rewritten")
|
||||
require.True(t, got.Artifacts[2].ModTime.Equal(originalMod), "empty-hash restores are ignored")
|
||||
}
|
||||
|
||||
func TestCreateForkedCopiesArtifactRows(t *testing.T) {
|
||||
db := newArtifactTestDB(t)
|
||||
sessions := NewSessionRepository(db)
|
||||
messages := NewMessageRepository(db)
|
||||
ctx := context.Background()
|
||||
created := time.Date(2026, 9, 1, 2, 0, 0, 0, time.UTC)
|
||||
|
||||
fork := &types.Session{ID: "fork-1", TenantID: 1, UserID: "u1", Title: "fork"}
|
||||
copied := []*types.Message{{
|
||||
ID: "copy-1", SessionID: "fork-1", Role: "assistant", CreatedAt: created,
|
||||
Artifacts: types.MessageArtifacts{testArtifact("a.pptx", "/w/a.pptx", created)},
|
||||
}}
|
||||
require.NoError(t, sessions.CreateForked(ctx, fork, copied))
|
||||
|
||||
got, err := messages.GetMessage(ctx, "fork-1", "copy-1")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got.Artifacts, 1)
|
||||
require.Equal(t, "local://blobs/a.pptx", got.Artifacts[0].URL, "the fork points at the same blob")
|
||||
}
|
||||
|
||||
func TestListArtifactLibraryScopesAndGroupsVersions(t *testing.T) {
|
||||
db := newArtifactTestDB(t)
|
||||
repo := NewMessageRepository(db)
|
||||
ctx := context.Background()
|
||||
base := time.Date(2026, 9, 1, 2, 0, 0, 0, time.UTC)
|
||||
|
||||
mine := createSession(t, db, &types.Session{TenantID: 7, UserID: "alice", Title: "我的会话"})
|
||||
legacy := createSession(t, db, &types.Session{TenantID: 7, Title: "旧会话"})
|
||||
bobs := createSession(t, db, &types.Session{TenantID: 7, UserID: "bob", Title: "Bob"})
|
||||
otherTenant := createSession(t, db, &types.Session{TenantID: 8, UserID: "alice", Title: "别的空间"})
|
||||
maintenance := createSession(t, db, &types.Session{
|
||||
TenantID: 7, UserID: "alice", Title: "维护", Description: types.SkillMaintenanceSessionMarker + "x",
|
||||
})
|
||||
// IM sessions are created without an owner, so they look like legacy
|
||||
// tenant-level rows; only the IM mapping tells them apart. A cleared chat
|
||||
// keeps its soft-deleted mapping and must stay out as well.
|
||||
imChat := createSession(t, db, &types.Session{TenantID: 7, Title: "飞书:张三的私聊"})
|
||||
clearedIMChat := createSession(t, db, &types.Session{TenantID: 7, Title: "企微:已清空"})
|
||||
embedChat := createSession(t, db, &types.Session{
|
||||
TenantID: 7, Title: "网页挂件", Description: types.EmbedSessionMarkerPrefix + "ch-1",
|
||||
})
|
||||
require.NoError(t, db.Create(&testIMChannelSession{
|
||||
ID: "ics-1", SessionID: imChat, Platform: "feishu", TenantID: 7,
|
||||
}).Error)
|
||||
require.NoError(t, db.Create(&testIMChannelSession{
|
||||
ID: "ics-2", SessionID: clearedIMChat, Platform: "wecom", TenantID: 7,
|
||||
}).Error)
|
||||
require.NoError(t, db.Delete(&testIMChannelSession{ID: "ics-2"}).Error)
|
||||
|
||||
add := func(sessionID string, at time.Time, arts ...types.MessageArtifact) *types.Message {
|
||||
m, err := repo.CreateMessage(ctx, &types.Message{
|
||||
SessionID: sessionID, RequestID: at.String(), Role: "assistant", CreatedAt: at, Artifacts: arts,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return m
|
||||
}
|
||||
// report.pptx regenerated twice in the same session: one item, 2 versions.
|
||||
add(mine, base, testArtifact("report.pptx", "/w/report.pptx", base))
|
||||
// Each regeneration is persisted as a new blob.
|
||||
regenerated := testArtifact("report.pptx", "/w/report.pptx", base.Add(time.Hour))
|
||||
regenerated.URL = "local://blobs/report-v2.pptx"
|
||||
latest := add(mine, base.Add(time.Hour),
|
||||
regenerated,
|
||||
types.MessageArtifact{
|
||||
URL: "local://blobs/data.csv", FileName: "data.csv", FileType: ".csv",
|
||||
SourcePath: "/w/data.csv", CreatedAt: base.Add(2 * time.Hour),
|
||||
},
|
||||
)
|
||||
// A later answer that references old.pptx again stores a second row with
|
||||
// the same URL; that is not a new version.
|
||||
oldDeck := testArtifact("old.pptx", "/w/old.pptx", base.Add(3*time.Hour))
|
||||
add(legacy, base.Add(3*time.Hour), oldDeck)
|
||||
add(legacy, base.Add(3*time.Hour+time.Minute), oldDeck)
|
||||
add(bobs, base, testArtifact("bob.pptx", "/w/bob.pptx", base))
|
||||
add(otherTenant, base, testArtifact("elsewhere.pptx", "/w/e.pptx", base))
|
||||
add(maintenance, base, testArtifact("maint.pptx", "/w/m.pptx", base))
|
||||
add(imChat, base.Add(5*time.Hour), testArtifact("salary.xlsx", "/w/salary.xlsx", base.Add(5*time.Hour)))
|
||||
add(clearedIMChat, base.Add(5*time.Hour), testArtifact("cleared.xlsx", "/w/c.xlsx", base.Add(5*time.Hour)))
|
||||
add(embedChat, base.Add(5*time.Hour), testArtifact("widget.pdf", "/w/widget.pdf", base.Add(5*time.Hour)))
|
||||
deleted := add(mine, base.Add(4*time.Hour), testArtifact("gone.pptx", "/w/gone.pptx", base.Add(4*time.Hour)))
|
||||
require.NoError(t, repo.DeleteMessage(ctx, mine, deleted.ID))
|
||||
|
||||
items, total, err := repo.ListArtifactLibrary(ctx, &types.ArtifactLibraryQuery{
|
||||
TenantID: 7, UserID: "alice", Page: 1, PageSize: 20,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 3, total)
|
||||
require.Len(t, items, 3)
|
||||
require.Equal(t, []string{"old.pptx", "data.csv", "report.pptx"},
|
||||
[]string{items[0].FileName, items[1].FileName, items[2].FileName}, "newest first")
|
||||
require.Equal(t, "旧会话", items[0].SessionTitle)
|
||||
require.Equal(t, 1, items[0].VersionCount, "re-referencing a file does not add a version")
|
||||
|
||||
report := items[2]
|
||||
require.Equal(t, 2, report.VersionCount)
|
||||
require.Equal(t, latest.ID, report.MessageID, "the latest version wins")
|
||||
require.Equal(t, 0, report.Index)
|
||||
require.Equal(t, mine, report.SessionID)
|
||||
require.Equal(t, 1, items[1].Index, "index is the position inside the owning message")
|
||||
|
||||
// Filters.
|
||||
items, total, err = repo.ListArtifactLibrary(ctx, &types.ArtifactLibraryQuery{
|
||||
TenantID: 7, UserID: "alice", FileTypes: []string{".csv"}, Page: 1, PageSize: 20,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 1, total)
|
||||
require.Equal(t, "data.csv", items[0].FileName)
|
||||
|
||||
items, total, err = repo.ListArtifactLibrary(ctx, &types.ArtifactLibraryQuery{
|
||||
TenantID: 7, UserID: "alice", Keyword: "REPORT", Page: 1, PageSize: 20,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 1, total)
|
||||
require.Equal(t, "report.pptx", items[0].FileName)
|
||||
|
||||
// Paging keeps the total.
|
||||
items, total, err = repo.ListArtifactLibrary(ctx, &types.ArtifactLibraryQuery{
|
||||
TenantID: 7, UserID: "alice", Page: 2, PageSize: 2,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 3, total)
|
||||
require.Len(t, items, 1)
|
||||
require.Equal(t, "report.pptx", items[0].FileName)
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestGetLatestContextCheckpointReturnsTheNewestInTheSession(t *testing.T) {
|
||||
repo, db := newMessageRepositoryForForkTest(t)
|
||||
ctx := context.Background()
|
||||
base := time.Date(2026, 9, 18, 9, 0, 0, 0, time.UTC)
|
||||
|
||||
none, err := repo.GetLatestContextCheckpoint(ctx, "s1")
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, none)
|
||||
|
||||
seedMessage(t, db, "a1", "s1", "assistant", base)
|
||||
seedMessage(t, db, "a2", "s1", "assistant", base.Add(time.Minute))
|
||||
seedMessage(t, db, "a3", "s1", "assistant", base.Add(2*time.Minute))
|
||||
seedMessage(t, db, "other", "s2", "assistant", base.Add(time.Hour))
|
||||
|
||||
require.NoError(t, repo.UpdateMessageContextCheckpoint(ctx, "s1", "a1",
|
||||
&types.ContextCheckpoint{Summary: "through one"}))
|
||||
require.NoError(t, repo.UpdateMessageContextCheckpoint(ctx, "s1", "a2",
|
||||
&types.ContextCheckpoint{Summary: "through two"}))
|
||||
require.NoError(t, repo.UpdateMessageContextCheckpoint(ctx, "s2", "other",
|
||||
&types.ContextCheckpoint{Summary: "another session"}))
|
||||
|
||||
got, err := repo.GetLatestContextCheckpoint(ctx, "s1")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, got)
|
||||
require.Equal(t, "a2", got.ID)
|
||||
require.Equal(t, "through two", got.ContextCheckpoint.Summary)
|
||||
require.True(t, got.CreatedAt.Equal(base.Add(time.Minute)))
|
||||
|
||||
// A deleted turn takes its checkpoint with it.
|
||||
require.NoError(t, repo.DeleteMessage(ctx, "s1", "a2"))
|
||||
got, err = repo.GetLatestContextCheckpoint(ctx, "s1")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "a1", got.ID)
|
||||
}
|
||||
|
||||
// The session guard keeps a stray turn ID from writing into another session,
|
||||
// and the role guard keeps it off user rows. Either way nothing was saved, and
|
||||
// the caller hears so instead of logging a checkpoint that does not exist.
|
||||
func TestUpdateMessageContextCheckpointIsScopedToTheSessionsAssistantRows(t *testing.T) {
|
||||
repo, db := newMessageRepositoryForForkTest(t)
|
||||
ctx := context.Background()
|
||||
at := time.Date(2026, 9, 18, 9, 0, 0, 0, time.UTC)
|
||||
|
||||
seedMessage(t, db, "u1", "s1", "user", at)
|
||||
seedMessage(t, db, "a1", "s1", "assistant", at)
|
||||
|
||||
require.Error(t, repo.UpdateMessageContextCheckpoint(ctx, "s2", "a1",
|
||||
&types.ContextCheckpoint{Summary: "wrong session"}), "a write that matches no row is not a save")
|
||||
require.Error(t, repo.UpdateMessageContextCheckpoint(ctx, "s1", "u1",
|
||||
&types.ContextCheckpoint{Summary: "user row"}))
|
||||
require.Error(t, repo.UpdateMessageContextCheckpoint(ctx, "s1", "gone",
|
||||
&types.ContextCheckpoint{Summary: "deleted turn"}))
|
||||
|
||||
got, err := repo.GetLatestContextCheckpoint(ctx, "s1")
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, got)
|
||||
}
|
||||
|
||||
// Messages are also saved whole (UpdateMessage) by paths that loaded them
|
||||
// before a checkpoint was written. Such a save must not clear it.
|
||||
func TestUpdateMessageKeepsAnExistingContextCheckpoint(t *testing.T) {
|
||||
repo, db := newMessageRepositoryForForkTest(t)
|
||||
ctx := context.Background()
|
||||
at := time.Date(2026, 9, 18, 9, 0, 0, 0, time.UTC)
|
||||
|
||||
seedMessage(t, db, "a1", "s1", "assistant", at)
|
||||
stale, err := repo.GetMessage(ctx, "s1", "a1")
|
||||
require.NoError(t, err)
|
||||
|
||||
require.NoError(t, repo.UpdateMessageContextCheckpoint(ctx, "s1", "a1",
|
||||
&types.ContextCheckpoint{Summary: "kept"}))
|
||||
stale.Content = "edited"
|
||||
require.NoError(t, repo.UpdateMessage(ctx, stale))
|
||||
|
||||
got, err := repo.GetLatestContextCheckpoint(ctx, "s1")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, got)
|
||||
require.Equal(t, "kept", got.ContextCheckpoint.Summary)
|
||||
}
|
||||
|
||||
// Agent history pages a session backwards. Messages sharing a timestamp are
|
||||
// ordered by ID, so a page boundary among them neither skips nor repeats one.
|
||||
func TestListMessagesBySessionBeforeCursorPagesBackwardsWithoutGaps(t *testing.T) {
|
||||
repo, db := newMessageRepositoryForForkTest(t)
|
||||
ctx := context.Background()
|
||||
base := time.Date(2026, 9, 18, 9, 0, 0, 0, time.UTC)
|
||||
|
||||
seedMessage(t, db, "m1", "s1", "user", base)
|
||||
seedMessage(t, db, "m2", "s1", "assistant", base.Add(time.Second))
|
||||
seedMessage(t, db, "m3-a", "s1", "user", base.Add(2*time.Second))
|
||||
seedMessage(t, db, "m3-b", "s1", "assistant", base.Add(2*time.Second))
|
||||
seedMessage(t, db, "m4", "s1", "user", base.Add(3*time.Second))
|
||||
seedMessage(t, db, "other", "s2", "user", base.Add(time.Hour))
|
||||
// Sorts inside the cursor's tie range; only the session filter keeps it out.
|
||||
seedMessage(t, db, "a-other", "s2", "user", base.Add(2*time.Second))
|
||||
|
||||
first, err := repo.ListMessagesBySessionBeforeCursor(ctx, "s1", time.Time{}, "", 2)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"m4", "m3-b"}, messageIDs(first))
|
||||
|
||||
oldest := first[len(first)-1]
|
||||
second, err := repo.ListMessagesBySessionBeforeCursor(ctx, "s1", oldest.CreatedAt, oldest.ID, 2)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"m3-a", "m2"}, messageIDs(second))
|
||||
|
||||
oldest = second[len(second)-1]
|
||||
last, err := repo.ListMessagesBySessionBeforeCursor(ctx, "s1", oldest.CreatedAt, oldest.ID, 2)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"m1"}, messageIDs(last))
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func newMessageRepositoryForForkTest(t *testing.T) (*messageRepository, *gorm.DB) {
|
||||
t.Helper()
|
||||
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.AutoMigrate(&types.Message{}, &types.MessageArtifactRecord{}))
|
||||
|
||||
return &messageRepository{db: db}, db
|
||||
}
|
||||
|
||||
func seedMessage(t *testing.T, db *gorm.DB, id, sessionID, role string, at time.Time) {
|
||||
t.Helper()
|
||||
// Message.BeforeCreate always assigns a fresh UUID, which would discard
|
||||
// the IDs these tests use as both expected results and the composite
|
||||
// cursor. Skip hooks so the seeded identity is the one the queries see.
|
||||
require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(&types.Message{
|
||||
ID: id,
|
||||
SessionID: sessionID,
|
||||
Role: role,
|
||||
CreatedAt: at,
|
||||
}).Error)
|
||||
}
|
||||
|
||||
// Same-millisecond messages must come back in a deterministic order, otherwise
|
||||
// a fork boundary drawn at one of them is not reproducible.
|
||||
func TestGetMessagesBySessionBreaksTimestampTiesById(t *testing.T) {
|
||||
repo, db := newMessageRepositoryForForkTest(t)
|
||||
ctx := context.Background()
|
||||
at := time.Date(2026, 9, 10, 9, 0, 0, 0, time.UTC)
|
||||
|
||||
seedMessage(t, db, "m-c", "s1", "assistant", at)
|
||||
seedMessage(t, db, "m-a", "s1", "user", at)
|
||||
seedMessage(t, db, "m-b", "s1", "assistant", at)
|
||||
|
||||
got, err := repo.GetMessagesBySession(ctx, "s1", 1, 10)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"m-a", "m-b", "m-c"}, messageIDs(got))
|
||||
}
|
||||
|
||||
func TestListMessagesBySessionUpToExcludesBoundaryAndLater(t *testing.T) {
|
||||
repo, db := newMessageRepositoryForForkTest(t)
|
||||
ctx := context.Background()
|
||||
base := time.Date(2026, 9, 10, 9, 0, 0, 0, time.UTC)
|
||||
|
||||
seedMessage(t, db, "m1", "s1", "user", base)
|
||||
seedMessage(t, db, "m2", "s1", "assistant", base.Add(time.Second))
|
||||
seedMessage(t, db, "m3", "s1", "user", base.Add(2*time.Second))
|
||||
seedMessage(t, db, "m4", "s1", "assistant", base.Add(3*time.Second))
|
||||
seedMessage(t, db, "other", "s2", "user", base)
|
||||
|
||||
got, err := repo.ListMessagesBySessionUpTo(ctx, "s1", base.Add(2*time.Second), "m3")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"m1", "m2"}, messageIDs(got))
|
||||
}
|
||||
|
||||
// The boundary is a composite (created_at, id) cursor, so a message sharing the
|
||||
// boundary's timestamp is included only when its ID sorts before the boundary's.
|
||||
func TestListMessagesBySessionUpToUsesCompositeCursor(t *testing.T) {
|
||||
repo, db := newMessageRepositoryForForkTest(t)
|
||||
ctx := context.Background()
|
||||
at := time.Date(2026, 9, 10, 9, 0, 0, 0, time.UTC)
|
||||
|
||||
seedMessage(t, db, "m-a", "s1", "user", at)
|
||||
seedMessage(t, db, "m-b", "s1", "assistant", at)
|
||||
seedMessage(t, db, "m-c", "s1", "user", at)
|
||||
|
||||
got, err := repo.ListMessagesBySessionUpTo(ctx, "s1", at, "m-c")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"m-a", "m-b"}, messageIDs(got))
|
||||
}
|
||||
|
||||
func TestListMessagesBySessionUpToSkipsSoftDeleted(t *testing.T) {
|
||||
repo, db := newMessageRepositoryForForkTest(t)
|
||||
ctx := context.Background()
|
||||
base := time.Date(2026, 9, 10, 9, 0, 0, 0, time.UTC)
|
||||
|
||||
seedMessage(t, db, "m1", "s1", "user", base)
|
||||
seedMessage(t, db, "m2", "s1", "assistant", base.Add(time.Second))
|
||||
seedMessage(t, db, "boundary", "s1", "user", base.Add(2*time.Second))
|
||||
require.NoError(t, db.Delete(&types.Message{}, "id = ?", "m2").Error)
|
||||
|
||||
got, err := repo.ListMessagesBySessionUpTo(ctx, "s1", base.Add(2*time.Second), "boundary")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"m1"}, messageIDs(got))
|
||||
}
|
||||
|
||||
func TestRecordRestoredArtifactMtimeOnlyTouchesThisSession(t *testing.T) {
|
||||
repo, db := newMessageRepositoryForForkTest(t)
|
||||
ctx := context.Background()
|
||||
at := time.Date(2026, 9, 10, 9, 0, 0, 0, time.UTC)
|
||||
oldMod := at
|
||||
newMod := at.Add(time.Minute)
|
||||
hash := "abc"
|
||||
art := types.MessageArtifacts{{
|
||||
SourcePath: "/workspace/output/report.pptx", FileName: "report.pptx",
|
||||
ModTime: oldMod, FileSize: 4, ContentHash: hash,
|
||||
}}
|
||||
seeded := []*types.Message{
|
||||
{ID: "parent-msg", SessionID: "parent", Role: "assistant", CreatedAt: at, Artifacts: art},
|
||||
{ID: "fork-msg", SessionID: "fork-1", Role: "assistant", CreatedAt: at, Artifacts: art},
|
||||
}
|
||||
require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(seeded).Error)
|
||||
require.NoError(t, insertMessageArtifacts(db, seeded))
|
||||
|
||||
require.NoError(t, repo.RecordRestoredArtifactMtime(ctx, "fork-1", "/workspace/output/report.pptx", newMod, hash))
|
||||
|
||||
parent, err := repo.GetMessage(ctx, "parent", "parent-msg")
|
||||
require.NoError(t, err)
|
||||
child, err := repo.GetMessage(ctx, "fork-1", "fork-msg")
|
||||
require.NoError(t, err)
|
||||
require.True(t, parent.Artifacts[0].ModTime.Equal(oldMod), "parent artifact mtime must stay put")
|
||||
require.True(t, child.Artifacts[0].ModTime.Equal(newMod), "fork artifact mtime should follow the restored sandbox")
|
||||
}
|
||||
|
||||
func messageIDs(messages []*types.Message) []string {
|
||||
ids := make([]string, 0, len(messages))
|
||||
for _, m := range messages {
|
||||
ids = append(ids, m.ID)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Sessions are per-user state and the session list has always been scoped that
|
||||
// way. Conversation search was not, which meant a workspace viewer could type a
|
||||
// colleague's project name into the search box and read their chats. These
|
||||
// tests pin the scoping so that cannot come back.
|
||||
|
||||
// Session.BeforeCreate assigns a fresh UUID, so the ids are read back rather
|
||||
// than assumed.
|
||||
func newOwnerScopeDB(t *testing.T, name string) (*gorm.DB, map[string]string) {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open("file:"+name+"?mode=memory&cache=shared"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatalf("open sqlite: %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(&types.Session{}, &types.Message{}, &types.MessageArtifactRecord{}); err != nil {
|
||||
t.Fatalf("migrate: %v", err)
|
||||
}
|
||||
sessions := map[string]*types.Session{
|
||||
"alice": {TenantID: 7, UserID: "web_user:alice", Title: "Alice 的会话"},
|
||||
"bob": {TenantID: 7, UserID: "web_user:bob", Title: "Bob 的会话"},
|
||||
"legacy": {TenantID: 7, Title: "API 建的会话"},
|
||||
"other": {TenantID: 8, UserID: "web_user:alice", Title: "别的工作区"},
|
||||
}
|
||||
ids := make(map[string]string, len(sessions))
|
||||
for label, session := range sessions {
|
||||
if err := db.Create(session).Error; err != nil {
|
||||
t.Fatalf("insert session: %v", err)
|
||||
}
|
||||
ids[label] = session.ID
|
||||
}
|
||||
return db, ids
|
||||
}
|
||||
|
||||
func TestOwnedSessionIDsExcludesOtherPeople(t *testing.T) {
|
||||
db, ids := newOwnerScopeDB(t, "owner-scope-owned")
|
||||
repo := NewMessageRepository(db)
|
||||
|
||||
owned, err := repo.OwnedSessionIDs(context.Background(), 7, "web_user:alice",
|
||||
[]string{ids["alice"], ids["bob"], ids["legacy"], ids["other"]})
|
||||
if err != nil {
|
||||
t.Fatalf("owned session ids: %v", err)
|
||||
}
|
||||
|
||||
if !owned[ids["alice"]] {
|
||||
t.Error("alice must be able to search her own conversations")
|
||||
}
|
||||
if owned[ids["bob"]] {
|
||||
t.Error("alice must not be able to reach bob's conversations")
|
||||
}
|
||||
if !owned[ids["legacy"]] {
|
||||
t.Error("tenant-level sessions stay reachable, matching how they are listed")
|
||||
}
|
||||
if owned[ids["other"]] {
|
||||
t.Error("a workspace boundary is not something an owner check may cross")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOwnedSessionIDsWithoutAnOwnerKeepsWorkspaceScope(t *testing.T) {
|
||||
db, ids := newOwnerScopeDB(t, "owner-scope-noowner")
|
||||
repo := NewMessageRepository(db)
|
||||
|
||||
// An empty owner means "no per-user narrowing", which is what admin-console
|
||||
// style callers rely on. It must still not leak across workspaces.
|
||||
owned, err := repo.OwnedSessionIDs(context.Background(), 7, "",
|
||||
[]string{ids["alice"], ids["bob"], ids["other"]})
|
||||
if err != nil {
|
||||
t.Fatalf("owned session ids: %v", err)
|
||||
}
|
||||
if !owned[ids["alice"]] || !owned[ids["bob"]] {
|
||||
t.Error("without an owner filter, every session in the workspace qualifies")
|
||||
}
|
||||
if owned[ids["other"]] {
|
||||
t.Error("tenant scoping is not optional")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestGetMessagesByRequestIDsStaysInsideSession(t *testing.T) {
|
||||
repo, db := newMessageRepositoryForForkTest(t)
|
||||
require.NoError(t, db.AutoMigrate(&types.Session{}))
|
||||
ctx := context.Background()
|
||||
at := time.Date(2026, 9, 10, 9, 0, 0, 0, time.UTC)
|
||||
|
||||
require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).
|
||||
Create(&types.Session{ID: "parent", TenantID: 1}).Error)
|
||||
require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(&types.Session{ID: "fork", TenantID: 1}).Error)
|
||||
require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(&types.Message{
|
||||
ID: "p-u", SessionID: "parent", RequestID: "req", Role: "user", CreatedAt: at,
|
||||
}).Error)
|
||||
require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(&types.Message{
|
||||
ID: "p-a", SessionID: "parent", RequestID: "req", Role: "assistant", CreatedAt: at.Add(time.Second),
|
||||
}).Error)
|
||||
require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(&types.Message{
|
||||
ID: "f-u", SessionID: "fork", RequestID: "req", Role: "user", CreatedAt: at,
|
||||
}).Error)
|
||||
require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(&types.Message{
|
||||
ID: "f-a", SessionID: "fork", RequestID: "req", Role: "assistant", CreatedAt: at.Add(time.Second),
|
||||
}).Error)
|
||||
|
||||
got, err := repo.GetMessagesByRequestIDs(ctx, "fork", []string{"req"})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"f-u", "f-a"}, messageIDsFromWithSession(got))
|
||||
|
||||
empty, err := repo.GetMessagesByRequestIDs(ctx, "", []string{"req"})
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, empty)
|
||||
}
|
||||
|
||||
func messageIDsFromWithSession(messages []*types.MessageWithSession) []string {
|
||||
ids := make([]string, 0, len(messages))
|
||||
for _, m := range messages {
|
||||
if m != nil {
|
||||
ids = append(ids, m.ID)
|
||||
}
|
||||
}
|
||||
return ids
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Rewinding at a user message drops that question too, so the boundary itself
|
||||
// is deleted and the caller can prefill it back into the composer.
|
||||
func TestDeleteMessagesFromInclusiveDropsBoundaryAndLater(t *testing.T) {
|
||||
repo, db := newMessageRepositoryForForkTest(t)
|
||||
ctx := context.Background()
|
||||
base := time.Date(2026, 9, 17, 9, 0, 0, 0, time.UTC)
|
||||
|
||||
seedMessage(t, db, "m1", "s1", "user", base)
|
||||
seedMessage(t, db, "m2", "s1", "assistant", base.Add(time.Second))
|
||||
seedMessage(t, db, "m3", "s1", "user", base.Add(2*time.Second))
|
||||
seedMessage(t, db, "m4", "s1", "assistant", base.Add(3*time.Second))
|
||||
|
||||
deleted, err := repo.DeleteMessagesFrom(ctx, "s1", base.Add(2*time.Second), "m3", true)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"m3", "m4"}, messageIDs(deleted))
|
||||
|
||||
require.Equal(t, []string{"m1", "m2"}, remainingMessageIDs(t, db, "s1"))
|
||||
}
|
||||
|
||||
// Rewinding at an assistant answer keeps that answer: the conversation resumes
|
||||
// right after it.
|
||||
func TestDeleteMessagesFromExclusiveKeepsBoundary(t *testing.T) {
|
||||
repo, db := newMessageRepositoryForForkTest(t)
|
||||
ctx := context.Background()
|
||||
base := time.Date(2026, 9, 17, 9, 0, 0, 0, time.UTC)
|
||||
|
||||
seedMessage(t, db, "m1", "s1", "user", base)
|
||||
seedMessage(t, db, "m2", "s1", "assistant", base.Add(time.Second))
|
||||
seedMessage(t, db, "m3", "s1", "user", base.Add(2*time.Second))
|
||||
|
||||
deleted, err := repo.DeleteMessagesFrom(ctx, "s1", base.Add(time.Second), "m2", false)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"m3"}, messageIDs(deleted))
|
||||
|
||||
require.Equal(t, []string{"m1", "m2"}, remainingMessageIDs(t, db, "s1"))
|
||||
}
|
||||
|
||||
// Same-millisecond peers are ordered by ID, so the cut is reproducible.
|
||||
func TestDeleteMessagesFromUsesCompositeCursor(t *testing.T) {
|
||||
repo, db := newMessageRepositoryForForkTest(t)
|
||||
ctx := context.Background()
|
||||
at := time.Date(2026, 9, 17, 9, 0, 0, 0, time.UTC)
|
||||
|
||||
seedMessage(t, db, "m-a", "s1", "user", at)
|
||||
seedMessage(t, db, "m-b", "s1", "assistant", at)
|
||||
seedMessage(t, db, "m-c", "s1", "user", at)
|
||||
|
||||
deleted, err := repo.DeleteMessagesFrom(ctx, "s1", at, "m-b", true)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"m-b", "m-c"}, messageIDs(deleted))
|
||||
require.Equal(t, []string{"m-a"}, remainingMessageIDs(t, db, "s1"))
|
||||
}
|
||||
|
||||
func TestDeleteMessagesFromLeavesOtherSessionsAlone(t *testing.T) {
|
||||
repo, db := newMessageRepositoryForForkTest(t)
|
||||
ctx := context.Background()
|
||||
base := time.Date(2026, 9, 17, 9, 0, 0, 0, time.UTC)
|
||||
|
||||
seedMessage(t, db, "mine", "s1", "user", base)
|
||||
seedMessage(t, db, "theirs", "s2", "user", base.Add(time.Second))
|
||||
|
||||
deleted, err := repo.DeleteMessagesFrom(ctx, "s1", base, "mine", true)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"mine"}, messageIDs(deleted))
|
||||
require.Equal(t, []string{"theirs"}, remainingMessageIDs(t, db, "s2"))
|
||||
}
|
||||
|
||||
func TestDeleteMessagesFromReportsNothingWhenAlreadyAtTheEnd(t *testing.T) {
|
||||
repo, db := newMessageRepositoryForForkTest(t)
|
||||
ctx := context.Background()
|
||||
base := time.Date(2026, 9, 17, 9, 0, 0, 0, time.UTC)
|
||||
|
||||
seedMessage(t, db, "m1", "s1", "user", base)
|
||||
seedMessage(t, db, "m2", "s1", "assistant", base.Add(time.Second))
|
||||
|
||||
deleted, err := repo.DeleteMessagesFrom(ctx, "s1", base.Add(time.Second), "m2", false)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, deleted)
|
||||
require.Equal(t, []string{"m1", "m2"}, remainingMessageIDs(t, db, "s1"))
|
||||
}
|
||||
|
||||
func remainingMessageIDs(t *testing.T, db *gorm.DB, sessionID string) []string {
|
||||
t.Helper()
|
||||
var rows []*types.Message
|
||||
require.NoError(t, db.Where("session_id = ?", sessionID).
|
||||
Order("created_at ASC, id ASC").Find(&rows).Error)
|
||||
return messageIDs(rows)
|
||||
}
|
||||
|
||||
// The cheap checkpoint lookup must agree with the full-history read rewind
|
||||
// used to do, or the two paths would disagree about which SHA survives a cut.
|
||||
func TestListAssistantCheckpointsUpToMatchesFullHistoryPrefix(t *testing.T) {
|
||||
repo, db := newMessageRepositoryForForkTest(t)
|
||||
ctx := context.Background()
|
||||
base := time.Date(2026, 9, 10, 9, 0, 0, 0, time.UTC)
|
||||
|
||||
seedMessage(t, db, "m1", "s1", "user", base)
|
||||
seedCheckpointMessage(t, db, "m2", "s1", base.Add(time.Second), "sb1", strings.Repeat("a", 40))
|
||||
seedMessage(t, db, "m3", "s1", "user", base.Add(2*time.Second))
|
||||
seedCheckpointMessage(t, db, "m4", "s1", base.Add(3*time.Second), "sb1", strings.Repeat("b", 40))
|
||||
seedMessage(t, db, "boundary", "s1", "user", base.Add(4*time.Second))
|
||||
seedCheckpointMessage(t, db, "later", "s1", base.Add(5*time.Second), "sb1", strings.Repeat("c", 40))
|
||||
seedCheckpointMessage(t, db, "other", "s2", base, "sb2", strings.Repeat("d", 40))
|
||||
|
||||
got, err := repo.ListAssistantCheckpointsUpTo(ctx, "s1", base.Add(4*time.Second), "boundary")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"m2", "m4"}, messageIDs(got))
|
||||
require.NotNil(t, got[1].SandboxCheckpoint)
|
||||
require.Equal(t, strings.Repeat("b", 40), got[1].SandboxCheckpoint.CommitSHA)
|
||||
require.Equal(t, "sb1", got[1].SandboxCheckpoint.SandboxID)
|
||||
|
||||
full, err := repo.ListMessagesBySessionUpTo(ctx, "s1", base.Add(4*time.Second), "boundary")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"m1", "m2", "m3", "m4"}, messageIDs(full))
|
||||
}
|
||||
|
||||
func TestListAssistantCheckpointsUpToSkipsSoftDeleted(t *testing.T) {
|
||||
repo, db := newMessageRepositoryForForkTest(t)
|
||||
ctx := context.Background()
|
||||
base := time.Date(2026, 9, 10, 9, 0, 0, 0, time.UTC)
|
||||
|
||||
seedCheckpointMessage(t, db, "m1", "s1", base, "sb1", strings.Repeat("a", 40))
|
||||
seedCheckpointMessage(t, db, "m2", "s1", base.Add(time.Second), "sb1", strings.Repeat("b", 40))
|
||||
seedMessage(t, db, "boundary", "s1", "user", base.Add(2*time.Second))
|
||||
require.NoError(t, db.Delete(&types.Message{}, "id = ?", "m2").Error)
|
||||
|
||||
got, err := repo.ListAssistantCheckpointsUpTo(ctx, "s1", base.Add(2*time.Second), "boundary")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"m1"}, messageIDs(got))
|
||||
}
|
||||
|
||||
func seedCheckpointMessage(
|
||||
t *testing.T, db *gorm.DB, id, sessionID string, at time.Time, sandboxID, sha string,
|
||||
) {
|
||||
t.Helper()
|
||||
require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(&types.Message{
|
||||
ID: id,
|
||||
SessionID: sessionID,
|
||||
Role: "assistant",
|
||||
Content: "answer body that the checkpoint query must not need to read",
|
||||
CreatedAt: at,
|
||||
SandboxCheckpoint: &types.SandboxCheckpoint{
|
||||
SandboxID: sandboxID,
|
||||
CommitSHA: sha,
|
||||
},
|
||||
}).Error)
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// SearchMessagesByKeyword runs on every supported main-database dialect —
|
||||
// the Lite build serves POST /messages/search from SQLite. The query used to
|
||||
// be Postgres-only ILIKE, which is a syntax error everywhere else.
|
||||
|
||||
func newMessageSearchDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.AutoMigrate(&types.Session{}, &types.Message{}, &types.MessageArtifactRecord{}))
|
||||
return db
|
||||
}
|
||||
|
||||
func TestSearchMessagesByKeywordMatchesOnSQLite(t *testing.T) {
|
||||
db := newMessageSearchDB(t)
|
||||
repo := NewMessageRepository(db)
|
||||
|
||||
session := &types.Session{TenantID: 7, UserID: "web_user:alice", Title: "chat"}
|
||||
require.NoError(t, db.Create(session).Error)
|
||||
require.NoError(t, db.Create(&types.Message{
|
||||
SessionID: session.ID,
|
||||
Role: "user",
|
||||
Content: "How do I reset the DEVICE password?",
|
||||
}).Error)
|
||||
|
||||
results, err := repo.SearchMessagesByKeyword(
|
||||
context.Background(), 7, "web_user:alice", "device", nil, 10)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, results, 1)
|
||||
require.Equal(t, session.ID, results[0].SessionID)
|
||||
}
|
||||
|
||||
func TestSearchMessagesByKeywordTreatsWildcardsLiterally(t *testing.T) {
|
||||
db := newMessageSearchDB(t)
|
||||
repo := NewMessageRepository(db)
|
||||
|
||||
session := &types.Session{TenantID: 7, UserID: "web_user:alice", Title: "chat"}
|
||||
require.NoError(t, db.Create(session).Error)
|
||||
require.NoError(t, db.Create(&types.Message{
|
||||
SessionID: session.ID,
|
||||
Role: "user",
|
||||
Content: "the discount is 100% today",
|
||||
}).Error)
|
||||
require.NoError(t, db.Create(&types.Message{
|
||||
SessionID: session.ID,
|
||||
Role: "user",
|
||||
Content: "no percent sign here",
|
||||
}).Error)
|
||||
|
||||
// A keyword containing % must match the literal character, not act as a
|
||||
// LIKE wildcard. escapeLikeKeyword emits \%, which only works when the
|
||||
// query declares ESCAPE '\' — SQLite has no default escape character.
|
||||
results, err := repo.SearchMessagesByKeyword(
|
||||
context.Background(), 7, "web_user:alice", "100%", nil, 10)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, results, 1)
|
||||
require.Contains(t, results[0].Content, "100%")
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type messageSuggestionRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewMessageSuggestionRepository(db *gorm.DB) interfaces.MessageSuggestionRepository {
|
||||
return &messageSuggestionRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *messageSuggestionRepository) GetByCacheKey(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
assistantMessageID string,
|
||||
placement string,
|
||||
configHash string,
|
||||
locale string,
|
||||
) (*types.MessageSuggestionSet, error) {
|
||||
var set types.MessageSuggestionSet
|
||||
err := r.db.WithContext(ctx).
|
||||
Where(
|
||||
"tenant_id = ? AND assistant_message_id = ? AND placement = ? AND config_hash = ? AND locale = ?",
|
||||
tenantID, assistantMessageID, placement, configHash, locale,
|
||||
).
|
||||
First(&set).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &set, nil
|
||||
}
|
||||
|
||||
func (r *messageSuggestionRepository) GetByID(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
sessionID string,
|
||||
id string,
|
||||
) (*types.MessageSuggestionSet, error) {
|
||||
var set types.MessageSuggestionSet
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("id = ? AND tenant_id = ? AND session_id = ?", id, tenantID, sessionID).
|
||||
First(&set).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &set, nil
|
||||
}
|
||||
|
||||
func (r *messageSuggestionRepository) AcquireGeneration(
|
||||
ctx context.Context,
|
||||
candidate *types.MessageSuggestionSet,
|
||||
regenerate bool,
|
||||
) (*types.MessageSuggestionSet, bool, error) {
|
||||
now := time.Now()
|
||||
leaseUntil := now.Add(3 * time.Minute)
|
||||
candidate.Status = types.SuggestionStatusGenerating
|
||||
candidate.LeaseUntil = &leaseUntil
|
||||
candidate.Questions = types.SuggestionItems{}
|
||||
|
||||
result := r.db.WithContext(ctx).
|
||||
Clauses(clause.OnConflict{DoNothing: true}).
|
||||
Create(candidate)
|
||||
if result.Error != nil {
|
||||
return nil, false, result.Error
|
||||
}
|
||||
if result.RowsAffected == 1 {
|
||||
return candidate, true, nil
|
||||
}
|
||||
|
||||
existing, err := r.GetByCacheKey(
|
||||
ctx,
|
||||
candidate.TenantID,
|
||||
candidate.AssistantMessageID,
|
||||
candidate.Placement,
|
||||
candidate.ConfigHash,
|
||||
candidate.Locale,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if existing.Status == types.SuggestionStatusReady && !regenerate {
|
||||
return existing, false, nil
|
||||
}
|
||||
if existing.Status == types.SuggestionStatusSuppressed && !regenerate {
|
||||
return existing, false, nil
|
||||
}
|
||||
if existing.Status == types.SuggestionStatusGenerating && existing.LeaseUntil != nil && existing.LeaseUntil.After(now) {
|
||||
return existing, false, nil
|
||||
}
|
||||
|
||||
query := r.db.WithContext(ctx).Model(&types.MessageSuggestionSet{}).
|
||||
Where("id = ?", existing.ID).
|
||||
Where("status <> ? OR lease_until IS NULL OR lease_until < ?", types.SuggestionStatusGenerating, now)
|
||||
if existing.Status == types.SuggestionStatusReady && regenerate {
|
||||
query = r.db.WithContext(ctx).Model(&types.MessageSuggestionSet{}).
|
||||
Where("id = ? AND status = ?", existing.ID, types.SuggestionStatusReady)
|
||||
}
|
||||
updates := map[string]interface{}{
|
||||
"status": types.SuggestionStatusGenerating,
|
||||
"lease_until": leaseUntil,
|
||||
"suppression_reason": "",
|
||||
"questions": types.SuggestionItems{},
|
||||
"error_code": "",
|
||||
"generated_at": nil,
|
||||
"updated_at": now,
|
||||
}
|
||||
result = query.Updates(updates)
|
||||
if result.Error != nil {
|
||||
return nil, false, result.Error
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
current, getErr := r.GetByCacheKey(
|
||||
ctx,
|
||||
candidate.TenantID,
|
||||
candidate.AssistantMessageID,
|
||||
candidate.Placement,
|
||||
candidate.ConfigHash,
|
||||
candidate.Locale,
|
||||
)
|
||||
return current, false, getErr
|
||||
}
|
||||
existing.Status = types.SuggestionStatusGenerating
|
||||
existing.LeaseUntil = &leaseUntil
|
||||
existing.Questions = types.SuggestionItems{}
|
||||
return existing, true, nil
|
||||
}
|
||||
|
||||
func (r *messageSuggestionRepository) Save(ctx context.Context, set *types.MessageSuggestionSet) error {
|
||||
if set == nil {
|
||||
return errors.New("message suggestion set is nil")
|
||||
}
|
||||
return r.db.WithContext(ctx).Save(set).Error
|
||||
}
|
||||
|
||||
func (r *messageSuggestionRepository) CreateEvent(
|
||||
ctx context.Context,
|
||||
event *types.MessageSuggestionEvent,
|
||||
) error {
|
||||
return r.db.WithContext(ctx).Create(event).Error
|
||||
}
|
||||
|
||||
func (r *messageSuggestionRepository) DeleteByMessageID(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
sessionID string,
|
||||
messageID string,
|
||||
) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND session_id = ? AND assistant_message_id = ?", tenantID, sessionID, messageID).
|
||||
Delete(&types.MessageSuggestionSet{}).Error
|
||||
}
|
||||
|
||||
// DeleteByMessageIDs is the batch form of DeleteByMessageID. Rewind drops a
|
||||
// whole tail of the conversation at once and would otherwise issue one round
|
||||
// trip per deleted message while holding the rewind lock.
|
||||
func (r *messageSuggestionRepository) DeleteByMessageIDs(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
sessionID string,
|
||||
messageIDs []string,
|
||||
) error {
|
||||
if len(messageIDs) == 0 {
|
||||
return nil
|
||||
}
|
||||
return r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND session_id = ? AND assistant_message_id IN ?", tenantID, sessionID, messageIDs).
|
||||
Delete(&types.MessageSuggestionSet{}).Error
|
||||
}
|
||||
|
||||
func (r *messageSuggestionRepository) DeleteBySessionID(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
sessionID string,
|
||||
) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND session_id = ?", tenantID, sessionID).
|
||||
Delete(&types.MessageSuggestionSet{}).Error
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// modelRepository implements the model repository interface
|
||||
type modelRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewModelRepository creates a new model repository
|
||||
func NewModelRepository(db *gorm.DB) interfaces.ModelRepository {
|
||||
return &modelRepository{db: db}
|
||||
}
|
||||
|
||||
// Create creates a new model
|
||||
func (r *modelRepository) Create(ctx context.Context, m *types.Model) error {
|
||||
return r.db.WithContext(ctx).Create(m).Error
|
||||
}
|
||||
|
||||
// GetByID retrieves a model by ID
|
||||
func (r *modelRepository) GetByID(ctx context.Context, tenantID uint64, id string) (*types.Model, error) {
|
||||
var m types.Model
|
||||
if err := r.db.WithContext(ctx).Where("id = ?", id).Where(
|
||||
"(tenant_id = ? OR is_builtin = true)", tenantID,
|
||||
).First(&m).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &m, nil
|
||||
}
|
||||
|
||||
// List lists models with optional filtering
|
||||
func (r *modelRepository) List(
|
||||
ctx context.Context, tenantID uint64, modelType types.ModelType, source types.ModelSource,
|
||||
) ([]*types.Model, error) {
|
||||
var models []*types.Model
|
||||
query := r.db.WithContext(ctx).Where(
|
||||
"(tenant_id = ? OR is_builtin = true)", tenantID,
|
||||
)
|
||||
|
||||
if modelType != "" {
|
||||
query = query.Where("type = ?", modelType)
|
||||
}
|
||||
|
||||
if source != "" {
|
||||
query = query.Where("source = ?", source)
|
||||
}
|
||||
|
||||
if err := query.Find(&models).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return models, nil
|
||||
}
|
||||
|
||||
// Update updates a model
|
||||
func (r *modelRepository) Update(ctx context.Context, m *types.Model) error {
|
||||
// Use Select to explicitly update all fields, including zero values like false
|
||||
return r.db.WithContext(ctx).Debug().Model(&types.Model{}).Where(
|
||||
"id = ? AND tenant_id = ?", m.ID, m.TenantID,
|
||||
).Select("*").Updates(m).Error
|
||||
}
|
||||
|
||||
// Delete deletes a model
|
||||
func (r *modelRepository) Delete(ctx context.Context, tenantID uint64, id string) error {
|
||||
return r.db.WithContext(ctx).Where(
|
||||
"id = ? AND tenant_id = ?", id, tenantID,
|
||||
).Delete(&types.Model{}).Error
|
||||
}
|
||||
|
||||
// ClearDefaultByType clears the default flag for all models of a specific type
|
||||
// This is a batch operation that updates all matching records in one query
|
||||
func (r *modelRepository) ClearDefaultByType(
|
||||
ctx context.Context,
|
||||
tenantID uint,
|
||||
modelType types.ModelType,
|
||||
excludeID string,
|
||||
) error {
|
||||
query := r.db.WithContext(ctx).Model(&types.Model{}).Where(
|
||||
"tenant_id = ? AND type = ? AND is_default = ?", tenantID, modelType, true,
|
||||
)
|
||||
|
||||
// If excludeID is provided, exclude that model from the update
|
||||
if excludeID != "" {
|
||||
query = query.Where("id != ?", excludeID)
|
||||
}
|
||||
|
||||
// Batch update: set is_default to false for all matching records
|
||||
return query.Update("is_default", false).Error
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"academy/internal/types"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ErrCatalogVersionConflict reports a publish based on a stale version.
|
||||
var ErrCatalogVersionConflict = errors.New("model catalog changed; reload and preview again")
|
||||
|
||||
// ModelCatalogRepository stores the singleton console overlay row.
|
||||
type ModelCatalogRepository struct{ db *gorm.DB }
|
||||
|
||||
// NewModelCatalogRepository creates a repository on db.
|
||||
func NewModelCatalogRepository(db *gorm.DB) *ModelCatalogRepository {
|
||||
return &ModelCatalogRepository{db: db}
|
||||
}
|
||||
|
||||
// Get loads the overlay row, including its bounded history.
|
||||
func (r *ModelCatalogRepository) Get(ctx context.Context) (*types.ModelCatalogConfig, error) {
|
||||
var row types.ModelCatalogConfig
|
||||
err := r.db.WithContext(ctx).First(&row, 1).Error
|
||||
return &row, err
|
||||
}
|
||||
|
||||
// Save replaces the row only if it is still at the expected version.
|
||||
func (r *ModelCatalogRepository) Save(ctx context.Context, expected uint64, row *types.ModelCatalogConfig) error {
|
||||
result := r.db.WithContext(ctx).Model(&types.ModelCatalogConfig{}).
|
||||
Where("id = ? AND version = ?", 1, expected).
|
||||
Updates(map[string]any{
|
||||
"version": row.Version, "overlay": row.Overlay,
|
||||
"history": row.History, "updated_by": row.UpdatedBy, "updated_at": row.UpdatedAt,
|
||||
})
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected != 1 {
|
||||
return ErrCatalogVersionConflict
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Version avoids transferring the bounded configuration history on every poll.
|
||||
func (r *ModelCatalogRepository) Version(ctx context.Context) (uint64, error) {
|
||||
var row types.ModelCatalogConfig
|
||||
err := r.db.WithContext(ctx).Select("version").First(&row, 1).Error
|
||||
return row.Version, err
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"academy/internal/types"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func knowledgeBaseModelUsageBindings(kb *types.KnowledgeBase, modelID string) []types.ModelUsageBinding {
|
||||
bindings := make([]types.ModelUsageBinding, 0, 7)
|
||||
if kb.EmbeddingModelID == modelID {
|
||||
bindings = append(bindings, types.ModelUsageBindingEmbeddingModel)
|
||||
}
|
||||
if kb.SummaryModelID == modelID {
|
||||
bindings = append(bindings, types.ModelUsageBindingSummaryModel)
|
||||
}
|
||||
if kb.ImageProcessingConfig.ModelID == modelID {
|
||||
bindings = append(bindings, types.ModelUsageBindingImageProcessingModel)
|
||||
}
|
||||
if kb.VLMConfig.ModelID == modelID {
|
||||
bindings = append(bindings, types.ModelUsageBindingVLMModel)
|
||||
}
|
||||
if kb.ASRConfig.ModelID == modelID {
|
||||
bindings = append(bindings, types.ModelUsageBindingASRModel)
|
||||
}
|
||||
if kb.WikiConfig != nil && kb.WikiConfig.SynthesisModelID == modelID {
|
||||
bindings = append(bindings, types.ModelUsageBindingWikiSynthesisModel)
|
||||
}
|
||||
if kb.AutoTagConfig != nil && kb.AutoTagConfig.ModelID == modelID {
|
||||
bindings = append(bindings, types.ModelUsageBindingAutoTagModel)
|
||||
}
|
||||
return bindings
|
||||
}
|
||||
|
||||
func customAgentModelUsageBindings(agent *types.CustomAgent, modelID string) []types.ModelUsageBinding {
|
||||
bindings := make([]types.ModelUsageBinding, 0, 6)
|
||||
if agent.Config.ModelID == modelID {
|
||||
bindings = append(bindings, types.ModelUsageBindingChatModel)
|
||||
}
|
||||
if agent.Config.RerankModelID == modelID {
|
||||
bindings = append(bindings, types.ModelUsageBindingRerankModel)
|
||||
}
|
||||
if agent.Config.VLMModelID == modelID {
|
||||
bindings = append(bindings, types.ModelUsageBindingVLMModel)
|
||||
}
|
||||
if agent.Config.ASRModelID == modelID {
|
||||
bindings = append(bindings, types.ModelUsageBindingASRModel)
|
||||
}
|
||||
if agent.Config.QueryUnderstandModelID == modelID {
|
||||
bindings = append(bindings, types.ModelUsageBindingQueryUnderstandModel)
|
||||
}
|
||||
if agent.Config.QuestionSuggestions != nil &&
|
||||
agent.Config.QuestionSuggestions.FollowUps.ModelID == modelID {
|
||||
bindings = append(bindings, types.ModelUsageBindingFollowUpModel)
|
||||
}
|
||||
return bindings
|
||||
}
|
||||
|
||||
// scopeKnowledgeBasesByModelID filters knowledge_bases rows that reference
|
||||
// modelID in any model-binding field.
|
||||
func scopeKnowledgeBasesByModelID(db *gorm.DB, modelID string) *gorm.DB {
|
||||
if db.Dialector.Name() == "postgres" {
|
||||
return db.Where(
|
||||
"embedding_model_id = ? OR summary_model_id = ? OR "+
|
||||
"image_processing_config->>'model_id' = ? OR "+
|
||||
"vlm_config->>'model_id' = ? OR "+
|
||||
"asr_config->>'model_id' = ? OR "+
|
||||
"wiki_config->>'synthesis_model_id' = ? OR "+
|
||||
"auto_tag_config->>'model_id' = ?",
|
||||
modelID, modelID, modelID, modelID, modelID, modelID, modelID,
|
||||
)
|
||||
}
|
||||
return db.Where(
|
||||
"embedding_model_id = ? OR summary_model_id = ? OR "+
|
||||
"json_extract(image_processing_config, '$.model_id') = ? OR "+
|
||||
"json_extract(vlm_config, '$.model_id') = ? OR "+
|
||||
"json_extract(asr_config, '$.model_id') = ? OR "+
|
||||
"json_extract(wiki_config, '$.synthesis_model_id') = ? OR "+
|
||||
"json_extract(auto_tag_config, '$.model_id') = ?",
|
||||
modelID, modelID, modelID, modelID, modelID, modelID, modelID,
|
||||
)
|
||||
}
|
||||
|
||||
// scopeCustomAgentsByModelID filters custom_agents rows whose config JSON
|
||||
// references modelID in any model-binding field.
|
||||
func scopeCustomAgentsByModelID(db *gorm.DB, modelID string) *gorm.DB {
|
||||
if db.Dialector.Name() == "postgres" {
|
||||
return db.Where(
|
||||
"config->>'model_id' = ? OR config->>'rerank_model_id' = ? OR "+
|
||||
"config->>'vlm_model_id' = ? OR config->>'asr_model_id' = ? OR "+
|
||||
"config->>'query_understand_model_id' = ? OR "+
|
||||
"config->'question_suggestions'->'follow_ups'->>'model_id' = ?",
|
||||
modelID, modelID, modelID, modelID, modelID, modelID,
|
||||
)
|
||||
}
|
||||
return db.Where(
|
||||
"json_extract(config, '$.model_id') = ? OR "+
|
||||
"json_extract(config, '$.rerank_model_id') = ? OR "+
|
||||
"json_extract(config, '$.vlm_model_id') = ? OR "+
|
||||
"json_extract(config, '$.asr_model_id') = ? OR "+
|
||||
"json_extract(config, '$.query_understand_model_id') = ? OR "+
|
||||
"json_extract(config, '$.question_suggestions.follow_ups.model_id') = ?",
|
||||
modelID, modelID, modelID, modelID, modelID, modelID,
|
||||
)
|
||||
}
|
||||
|
||||
func scopeCustomAgentsBySandboxConfigID(db *gorm.DB, configID string) *gorm.DB {
|
||||
if db.Dialector.Name() == "postgres" {
|
||||
return db.Where("config->>'sandbox_config_id' = ?", configID)
|
||||
}
|
||||
return db.Where("json_extract(config, '$.sandbox_config_id') = ?", configID)
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const customAgentsTestDDL = `
|
||||
CREATE TABLE IF NOT EXISTS custom_agents (
|
||||
id VARCHAR(36) NOT NULL,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
description TEXT,
|
||||
avatar VARCHAR(64),
|
||||
is_builtin BOOLEAN NOT NULL DEFAULT 0,
|
||||
tenant_id INTEGER NOT NULL,
|
||||
created_by VARCHAR(36),
|
||||
config TEXT NOT NULL DEFAULT '{}',
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
deleted_at DATETIME,
|
||||
PRIMARY KEY (id, tenant_id)
|
||||
);
|
||||
`
|
||||
|
||||
func setupModelUsageTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db := setupKBTestDB(t)
|
||||
require.NoError(t, db.Exec(customAgentsTestDDL).Error)
|
||||
return db
|
||||
}
|
||||
|
||||
func TestCountByModelID_KnowledgeBase(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db := setupModelUsageTestDB(t)
|
||||
repo := NewKnowledgeBaseRepository(db)
|
||||
modelID := "embed-model-1"
|
||||
|
||||
kb := makeKB(nil)
|
||||
kb.EmbeddingModelID = modelID
|
||||
require.NoError(t, db.Create(kb).Error)
|
||||
|
||||
count, err := repo.CountByModelID(ctx, 1, modelID)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(1), count)
|
||||
|
||||
count, err = repo.CountByModelID(ctx, 1, "other-model")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(0), count)
|
||||
|
||||
kb2 := makeKB(nil)
|
||||
kb2.ID = uuid.New().String()
|
||||
kb2.VLMConfig = types.VLMConfig{Enabled: true, ModelID: modelID}
|
||||
require.NoError(t, db.Create(kb2).Error)
|
||||
|
||||
count, err = repo.CountByModelID(ctx, 1, modelID)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(2), count)
|
||||
|
||||
require.NoError(t, db.Delete(kb2).Error)
|
||||
count, err = repo.CountByModelID(ctx, 1, modelID)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(1), count)
|
||||
}
|
||||
|
||||
func TestListModelUsages_KnowledgeBase(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db := setupModelUsageTestDB(t)
|
||||
repo := NewKnowledgeBaseRepository(db)
|
||||
modelID := "all-kb-bindings"
|
||||
|
||||
allBindings := makeKB(nil)
|
||||
allBindings.Name = "Zulu KB"
|
||||
allBindings.EmbeddingModelID = modelID
|
||||
allBindings.SummaryModelID = modelID
|
||||
allBindings.ImageProcessingConfig = types.ImageProcessingConfig{ModelID: modelID}
|
||||
allBindings.VLMConfig = types.VLMConfig{Enabled: true, ModelID: modelID}
|
||||
allBindings.ASRConfig = types.ASRConfig{Enabled: true, ModelID: modelID}
|
||||
allBindings.WikiConfig = &types.WikiConfig{SynthesisModelID: modelID}
|
||||
allBindings.AutoTagConfig = &types.AutoTagConfig{Enabled: true, ModelID: modelID}
|
||||
require.NoError(t, db.Create(allBindings).Error)
|
||||
|
||||
vlmOnly := makeKB(nil)
|
||||
vlmOnly.Name = "Alpha KB"
|
||||
vlmOnly.VLMConfig = types.VLMConfig{Enabled: true, ModelID: modelID}
|
||||
require.NoError(t, db.Create(vlmOnly).Error)
|
||||
|
||||
otherTenant := makeKB(nil)
|
||||
otherTenant.Name = "Other tenant"
|
||||
otherTenant.TenantID = 2
|
||||
otherTenant.EmbeddingModelID = modelID
|
||||
require.NoError(t, db.Create(otherTenant).Error)
|
||||
|
||||
deleted := makeKB(nil)
|
||||
deleted.Name = "Deleted KB"
|
||||
deleted.EmbeddingModelID = modelID
|
||||
require.NoError(t, db.Create(deleted).Error)
|
||||
require.NoError(t, db.Delete(deleted).Error)
|
||||
|
||||
usages, err := repo.ListModelUsages(ctx, 1, modelID)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, usages, 2)
|
||||
assert.Equal(t, "Alpha KB", usages[0].Name)
|
||||
assert.Equal(t, []types.ModelUsageBinding{types.ModelUsageBindingVLMModel}, usages[0].Bindings)
|
||||
assert.Equal(t, "Zulu KB", usages[1].Name)
|
||||
assert.Equal(t, []types.ModelUsageBinding{
|
||||
types.ModelUsageBindingEmbeddingModel,
|
||||
types.ModelUsageBindingSummaryModel,
|
||||
types.ModelUsageBindingImageProcessingModel,
|
||||
types.ModelUsageBindingVLMModel,
|
||||
types.ModelUsageBindingASRModel,
|
||||
types.ModelUsageBindingWikiSynthesisModel,
|
||||
types.ModelUsageBindingAutoTagModel,
|
||||
}, usages[1].Bindings)
|
||||
}
|
||||
|
||||
func TestCountByModelID_KnowledgeBaseAutoTag(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db := setupModelUsageTestDB(t)
|
||||
repo := NewKnowledgeBaseRepository(db)
|
||||
modelID := "auto-tag-model"
|
||||
|
||||
kb := makeKB(nil)
|
||||
kb.AutoTagConfig = &types.AutoTagConfig{Enabled: true, ModelID: modelID}
|
||||
require.NoError(t, db.Create(kb).Error)
|
||||
|
||||
count, err := repo.CountByModelID(ctx, 1, modelID)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(1), count)
|
||||
}
|
||||
|
||||
func TestListModelUsages_KnowledgeBaseRespectsLimit(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db := setupModelUsageTestDB(t)
|
||||
repo := NewKnowledgeBaseRepository(db)
|
||||
modelID := "shared-embed"
|
||||
|
||||
for i := 0; i < types.ModelUsageListLimit+3; i++ {
|
||||
kb := makeKB(nil)
|
||||
kb.Name = fmt.Sprintf("KB %03d", i)
|
||||
kb.EmbeddingModelID = modelID
|
||||
require.NoError(t, db.Create(kb).Error)
|
||||
}
|
||||
|
||||
usages, err := repo.ListModelUsages(ctx, 1, modelID)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, usages, types.ModelUsageListLimit)
|
||||
assert.Equal(t, "KB 000", usages[0].Name)
|
||||
|
||||
count, err := repo.CountByModelID(ctx, 1, modelID)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(types.ModelUsageListLimit+3), count)
|
||||
}
|
||||
|
||||
func TestCountByModelID_CustomAgent(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db := setupModelUsageTestDB(t)
|
||||
repo := NewCustomAgentRepository(db)
|
||||
modelID := "chat-model-1"
|
||||
|
||||
agent := &types.CustomAgent{
|
||||
ID: uuid.New().String(),
|
||||
Name: "test-agent",
|
||||
TenantID: 1,
|
||||
Config: types.CustomAgentConfig{
|
||||
ModelID: modelID,
|
||||
},
|
||||
}
|
||||
require.NoError(t, repo.CreateAgent(ctx, agent))
|
||||
|
||||
count, err := repo.CountByModelID(ctx, 1, modelID)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(1), count)
|
||||
|
||||
agent2 := &types.CustomAgent{
|
||||
ID: uuid.New().String(),
|
||||
Name: "rerank-agent",
|
||||
TenantID: 1,
|
||||
Config: types.CustomAgentConfig{
|
||||
RerankModelID: modelID,
|
||||
},
|
||||
}
|
||||
require.NoError(t, repo.CreateAgent(ctx, agent2))
|
||||
|
||||
count, err = repo.CountByModelID(ctx, 1, modelID)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(2), count)
|
||||
|
||||
count, err = repo.CountByModelID(ctx, 2, modelID)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(0), count)
|
||||
|
||||
require.NoError(t, repo.DeleteAgent(ctx, agent2.ID, 1))
|
||||
count, err = repo.CountByModelID(ctx, 1, modelID)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(1), count)
|
||||
}
|
||||
|
||||
func TestListModelUsages_CustomAgent(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db := setupModelUsageTestDB(t)
|
||||
repo := NewCustomAgentRepository(db)
|
||||
modelID := "all-agent-bindings"
|
||||
|
||||
allBindings := &types.CustomAgent{
|
||||
ID: uuid.New().String(),
|
||||
Name: "Zulu agent",
|
||||
TenantID: 1,
|
||||
Config: types.CustomAgentConfig{
|
||||
ModelID: modelID,
|
||||
RerankModelID: modelID,
|
||||
VLMModelID: modelID,
|
||||
ASRModelID: modelID,
|
||||
QueryUnderstandModelID: modelID,
|
||||
QuestionSuggestions: &types.QuestionSuggestionConfig{
|
||||
FollowUps: types.FollowUpSuggestionConfig{ModelID: modelID},
|
||||
},
|
||||
},
|
||||
}
|
||||
require.NoError(t, repo.CreateAgent(ctx, allBindings))
|
||||
|
||||
vlmOnly := &types.CustomAgent{
|
||||
ID: uuid.New().String(),
|
||||
Name: "Alpha agent",
|
||||
TenantID: 1,
|
||||
Config: types.CustomAgentConfig{VLMModelID: modelID},
|
||||
}
|
||||
require.NoError(t, repo.CreateAgent(ctx, vlmOnly))
|
||||
|
||||
otherTenant := &types.CustomAgent{
|
||||
ID: uuid.New().String(), Name: "Other tenant", TenantID: 2,
|
||||
Config: types.CustomAgentConfig{ModelID: modelID},
|
||||
}
|
||||
require.NoError(t, repo.CreateAgent(ctx, otherTenant))
|
||||
|
||||
deleted := &types.CustomAgent{
|
||||
ID: uuid.New().String(), Name: "Deleted agent", TenantID: 1,
|
||||
Config: types.CustomAgentConfig{ModelID: modelID},
|
||||
}
|
||||
require.NoError(t, repo.CreateAgent(ctx, deleted))
|
||||
require.NoError(t, repo.DeleteAgent(ctx, deleted.ID, deleted.TenantID))
|
||||
|
||||
usages, err := repo.ListModelUsages(ctx, 1, modelID)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, usages, 2)
|
||||
assert.Equal(t, "Alpha agent", usages[0].Name)
|
||||
assert.Equal(t, []types.ModelUsageBinding{types.ModelUsageBindingVLMModel}, usages[0].Bindings)
|
||||
assert.Equal(t, "Zulu agent", usages[1].Name)
|
||||
assert.Equal(t, []types.ModelUsageBinding{
|
||||
types.ModelUsageBindingChatModel,
|
||||
types.ModelUsageBindingRerankModel,
|
||||
types.ModelUsageBindingVLMModel,
|
||||
types.ModelUsageBindingASRModel,
|
||||
types.ModelUsageBindingQueryUnderstandModel,
|
||||
types.ModelUsageBindingFollowUpModel,
|
||||
}, usages[1].Bindings)
|
||||
}
|
||||
|
||||
func TestCustomAgentSandboxConfigReferences(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db := setupModelUsageTestDB(t)
|
||||
repo := NewCustomAgentRepository(db)
|
||||
configID := "sandbox-cfg-1"
|
||||
|
||||
require.NoError(t, db.Exec(
|
||||
`INSERT INTO custom_agents (id, name, tenant_id, config) VALUES
|
||||
(?, ?, ?, ?),
|
||||
(?, ?, ?, ?),
|
||||
(?, ?, ?, ?)`,
|
||||
uuid.New().String(), "analysis-agent", 1, `{"sandbox_config_id":"sandbox-cfg-1"}`,
|
||||
uuid.New().String(), "other-agent", 1, `{"sandbox_config_id":"sandbox-cfg-2"}`,
|
||||
uuid.New().String(), "other-tenant-agent", 2, `{"sandbox_config_id":"sandbox-cfg-1"}`,
|
||||
).Error)
|
||||
|
||||
count, err := repo.CountBySandboxConfigID(ctx, 1, configID)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(1), count)
|
||||
|
||||
names, err := repo.ListNamesBySandboxConfigID(ctx, 1, configID)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{"analysis-agent"}, names)
|
||||
}
|
||||
@@ -0,0 +1,369 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrOrganizationNotFound = errors.New("organization not found")
|
||||
ErrOrgMemberNotFound = errors.New("organization member not found")
|
||||
ErrOrgMemberAlreadyExists = errors.New("member already exists in organization")
|
||||
ErrOrgMemberLimitReached = errors.New("organization member limit reached")
|
||||
ErrInviteCodeNotFound = errors.New("invite code not found")
|
||||
ErrInviteCodeExpired = errors.New("invite code has expired")
|
||||
)
|
||||
|
||||
// organizationRepository implements OrganizationRepository.
|
||||
//
|
||||
// Plan 3 of #1303 lifts membership from per-user to per-tenant (see
|
||||
// migration 000045). All "member" methods on this repo now operate on
|
||||
// the (org, tenant) tuple; the underlying table is
|
||||
// organization_tenant_members.
|
||||
type organizationRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewOrganizationRepository creates a new organization repository
|
||||
func NewOrganizationRepository(db *gorm.DB) interfaces.OrganizationRepository {
|
||||
return &organizationRepository{db: db}
|
||||
}
|
||||
|
||||
// Create creates a new organization
|
||||
func (r *organizationRepository) Create(ctx context.Context, org *types.Organization) error {
|
||||
return r.db.WithContext(ctx).Create(org).Error
|
||||
}
|
||||
|
||||
// GetByID gets an organization by ID
|
||||
func (r *organizationRepository) GetByID(ctx context.Context, id string) (*types.Organization, error) {
|
||||
var org types.Organization
|
||||
if err := r.db.WithContext(ctx).Where("id = ?", id).First(&org).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrOrganizationNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &org, nil
|
||||
}
|
||||
|
||||
// GetByInviteCode gets an organization by invite code (returns ErrInviteCodeExpired if code has expired)
|
||||
func (r *organizationRepository) GetByInviteCode(ctx context.Context, inviteCode string) (*types.Organization, error) {
|
||||
var org types.Organization
|
||||
if err := r.db.WithContext(ctx).Where("invite_code = ?", inviteCode).First(&org).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrInviteCodeNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if org.InviteCodeExpiresAt != nil && org.InviteCodeExpiresAt.Before(time.Now()) {
|
||||
return nil, ErrInviteCodeExpired
|
||||
}
|
||||
return &org, nil
|
||||
}
|
||||
|
||||
// ListByTenantID lists organizations whose tenant participates as a member.
|
||||
func (r *organizationRepository) ListByTenantID(ctx context.Context, tenantID uint64) ([]*types.Organization, error) {
|
||||
var orgs []*types.Organization
|
||||
|
||||
err := r.db.WithContext(ctx).
|
||||
Joins("JOIN organization_tenant_members otm ON otm.organization_id = organizations.id").
|
||||
Where("otm.tenant_id = ?", tenantID).
|
||||
Order("organizations.created_at DESC").
|
||||
Find(&orgs).Error
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return orgs, nil
|
||||
}
|
||||
|
||||
// ListSearchable lists organizations that are searchable (open for discovery), optionally filtered by name/description/ID
|
||||
func (r *organizationRepository) ListSearchable(ctx context.Context, query string, limit int) ([]*types.Organization, error) {
|
||||
if limit <= 0 {
|
||||
limit = 20
|
||||
}
|
||||
var orgs []*types.Organization
|
||||
q := r.db.WithContext(ctx).Where("searchable = ?", true)
|
||||
if query != "" {
|
||||
pattern := "%" + query + "%"
|
||||
// 支持按名称、描述或空间 ID 搜索,便于区分同名空间
|
||||
q = q.Where("name ILIKE ? OR description ILIKE ? OR id::text ILIKE ?", pattern, pattern, pattern)
|
||||
}
|
||||
err := q.Order("created_at DESC").Limit(limit).Find(&orgs).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return orgs, nil
|
||||
}
|
||||
|
||||
// Update updates an organization (Select ensures zero values like invite_code_validity_days=0 are persisted)
|
||||
func (r *organizationRepository) Update(ctx context.Context, org *types.Organization) error {
|
||||
return r.db.WithContext(ctx).Model(&types.Organization{}).Where("id = ?", org.ID).
|
||||
Select("name", "description", "avatar", "require_approval", "searchable", "invite_code_validity_days", "member_limit", "updated_at").
|
||||
Updates(org).Error
|
||||
}
|
||||
|
||||
// Delete soft deletes an organization
|
||||
func (r *organizationRepository) Delete(ctx context.Context, id string) error {
|
||||
return r.db.WithContext(ctx).Where("id = ?", id).Delete(&types.Organization{}).Error
|
||||
}
|
||||
|
||||
// AddTenantMember inserts a new (org, tenant) membership row. Returns
|
||||
// ErrOrgMemberAlreadyExists if a row already exists for this tuple — the
|
||||
// service layer treats that as a no-op when the caller is just confirming
|
||||
// an idempotent join — and ErrOrgMemberLimitReached when a positive
|
||||
// memberLimit is already reached.
|
||||
func (r *organizationRepository) AddTenantMember(
|
||||
ctx context.Context, member *types.OrganizationTenantMember, memberLimit int,
|
||||
) error {
|
||||
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
// A positive limit is checked in the same transaction as the insert,
|
||||
// with the organization row locked, so concurrent joins cannot all
|
||||
// pass the count. SQLite has no row locks; it serializes writers,
|
||||
// and a stale read fails to upgrade to a write instead.
|
||||
if memberLimit > 0 && tx.Name() != "sqlite" {
|
||||
var org types.Organization
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Select("id").
|
||||
Where("id = ?", member.OrganizationID).First(&org).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
var existing int64
|
||||
if err := tx.Model(&types.OrganizationTenantMember{}).
|
||||
Where("organization_id = ? AND tenant_id = ?", member.OrganizationID, member.TenantID).
|
||||
Count(&existing).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if existing > 0 {
|
||||
return ErrOrgMemberAlreadyExists
|
||||
}
|
||||
if memberLimit > 0 {
|
||||
var count int64
|
||||
if err := tx.Model(&types.OrganizationTenantMember{}).
|
||||
Where("organization_id = ?", member.OrganizationID).
|
||||
Count(&count).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if count >= int64(memberLimit) {
|
||||
return ErrOrgMemberLimitReached
|
||||
}
|
||||
}
|
||||
return tx.Create(member).Error
|
||||
})
|
||||
}
|
||||
|
||||
// RemoveTenantMember removes the (org, tenant) membership row.
|
||||
func (r *organizationRepository) RemoveTenantMember(ctx context.Context, orgID string, tenantID uint64) error {
|
||||
result := r.db.WithContext(ctx).
|
||||
Where("organization_id = ? AND tenant_id = ?", orgID, tenantID).
|
||||
Delete(&types.OrganizationTenantMember{})
|
||||
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
return ErrOrgMemberNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateTenantMemberRole updates the role for a (org, tenant) membership.
|
||||
func (r *organizationRepository) UpdateTenantMemberRole(ctx context.Context, orgID string, tenantID uint64, role types.OrgMemberRole) error {
|
||||
result := r.db.WithContext(ctx).
|
||||
Model(&types.OrganizationTenantMember{}).
|
||||
Where("organization_id = ? AND tenant_id = ?", orgID, tenantID).
|
||||
Update("role", role)
|
||||
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
return ErrOrgMemberNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListTenantMembers lists all tenant memberships for an organization.
|
||||
func (r *organizationRepository) ListTenantMembers(ctx context.Context, orgID string) ([]*types.OrganizationTenantMember, error) {
|
||||
var members []*types.OrganizationTenantMember
|
||||
err := r.db.WithContext(ctx).
|
||||
Preload("RepresentativeUser").
|
||||
Where("organization_id = ?", orgID).
|
||||
Order("created_at ASC").
|
||||
Find(&members).Error
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return members, nil
|
||||
}
|
||||
|
||||
// GetTenantMember returns the (org, tenant) membership row, or
|
||||
// ErrOrgMemberNotFound when missing. This is the canonical permission
|
||||
// check primitive — callers compose this with the share permission
|
||||
// to compute effective access.
|
||||
func (r *organizationRepository) GetTenantMember(ctx context.Context, orgID string, tenantID uint64) (*types.OrganizationTenantMember, error) {
|
||||
var member types.OrganizationTenantMember
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("organization_id = ? AND tenant_id = ?", orgID, tenantID).
|
||||
First(&member).Error
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrOrgMemberNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &member, nil
|
||||
}
|
||||
|
||||
// ListTenantMembersByTenantForOrgs returns one membership row per org where
|
||||
// the tenant participates (batch).
|
||||
func (r *organizationRepository) ListTenantMembersByTenantForOrgs(ctx context.Context, tenantID uint64, orgIDs []string) (map[string]*types.OrganizationTenantMember, error) {
|
||||
if len(orgIDs) == 0 {
|
||||
return make(map[string]*types.OrganizationTenantMember), nil
|
||||
}
|
||||
var members []*types.OrganizationTenantMember
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND organization_id IN ?", tenantID, orgIDs).
|
||||
Find(&members).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make(map[string]*types.OrganizationTenantMember, len(members))
|
||||
for _, m := range members {
|
||||
if m != nil {
|
||||
out[m.OrganizationID] = m
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// CountTenantMembers counts the number of tenant members in an organization.
|
||||
func (r *organizationRepository) CountTenantMembers(ctx context.Context, orgID string) (int64, error) {
|
||||
var count int64
|
||||
err := r.db.WithContext(ctx).
|
||||
Model(&types.OrganizationTenantMember{}).
|
||||
Where("organization_id = ?", orgID).
|
||||
Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
// UpdateInviteCode updates the invite code and optional expiry for an organization (expiresAt nil = never expire)
|
||||
func (r *organizationRepository) UpdateInviteCode(ctx context.Context, orgID string, inviteCode string, expiresAt *time.Time) error {
|
||||
updates := map[string]interface{}{"invite_code": inviteCode, "invite_code_expires_at": expiresAt}
|
||||
return r.db.WithContext(ctx).
|
||||
Model(&types.Organization{}).
|
||||
Where("id = ?", orgID).
|
||||
Updates(updates).Error
|
||||
}
|
||||
|
||||
// ----------------
|
||||
// Join Requests
|
||||
// ----------------
|
||||
|
||||
var ErrJoinRequestNotFound = errors.New("join request not found")
|
||||
|
||||
// CreateJoinRequest creates a new join request
|
||||
func (r *organizationRepository) CreateJoinRequest(ctx context.Context, request *types.OrganizationJoinRequest) error {
|
||||
return r.db.WithContext(ctx).Create(request).Error
|
||||
}
|
||||
|
||||
// GetJoinRequestByID gets a join request by ID
|
||||
func (r *organizationRepository) GetJoinRequestByID(ctx context.Context, id string) (*types.OrganizationJoinRequest, error) {
|
||||
var request types.OrganizationJoinRequest
|
||||
err := r.db.WithContext(ctx).
|
||||
Preload("User").
|
||||
Where("id = ?", id).
|
||||
First(&request).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrJoinRequestNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &request, nil
|
||||
}
|
||||
|
||||
// GetPendingJoinRequestByTenant returns a pending request for the given
|
||||
// (org, tenant). After Plan 3 the dedup key is per-tenant, not per-user
|
||||
// — the user requesting and the user reviewing may be different humans
|
||||
// in the same tenant, but the resource being granted is tenant-level
|
||||
// access.
|
||||
func (r *organizationRepository) GetPendingJoinRequestByTenant(ctx context.Context, orgID string, tenantID uint64) (*types.OrganizationJoinRequest, error) {
|
||||
var request types.OrganizationJoinRequest
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("organization_id = ? AND tenant_id = ? AND status = ?", orgID, tenantID, types.JoinRequestStatusPending).
|
||||
First(&request).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrJoinRequestNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &request, nil
|
||||
}
|
||||
|
||||
// GetPendingRequestByTenantAndType narrows the (org, tenant) pending
|
||||
// dedup query to a specific request_type (join | upgrade).
|
||||
func (r *organizationRepository) GetPendingRequestByTenantAndType(ctx context.Context, orgID string, tenantID uint64, requestType types.JoinRequestType) (*types.OrganizationJoinRequest, error) {
|
||||
var request types.OrganizationJoinRequest
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("organization_id = ? AND tenant_id = ? AND status = ? AND request_type = ?", orgID, tenantID, types.JoinRequestStatusPending, requestType).
|
||||
First(&request).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrJoinRequestNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &request, nil
|
||||
}
|
||||
|
||||
// ListJoinRequests lists join requests for an organization
|
||||
func (r *organizationRepository) ListJoinRequests(ctx context.Context, orgID string, status types.JoinRequestStatus) ([]*types.OrganizationJoinRequest, error) {
|
||||
var requests []*types.OrganizationJoinRequest
|
||||
query := r.db.WithContext(ctx).
|
||||
Preload("User").
|
||||
Where("organization_id = ?", orgID)
|
||||
|
||||
if status != "" {
|
||||
query = query.Where("status = ?", status)
|
||||
}
|
||||
|
||||
err := query.Order("created_at DESC").Find(&requests).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return requests, nil
|
||||
}
|
||||
|
||||
// CountJoinRequests counts join requests for an organization by status
|
||||
func (r *organizationRepository) CountJoinRequests(ctx context.Context, orgID string, status types.JoinRequestStatus) (int64, error) {
|
||||
var count int64
|
||||
query := r.db.WithContext(ctx).Model(&types.OrganizationJoinRequest{}).Where("organization_id = ?", orgID)
|
||||
if status != "" {
|
||||
query = query.Where("status = ?", status)
|
||||
}
|
||||
err := query.Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
// UpdateJoinRequestStatus updates the status of a join request
|
||||
func (r *organizationRepository) UpdateJoinRequestStatus(ctx context.Context, id string, status types.JoinRequestStatus, reviewedBy string, reviewMessage string) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Model(&types.OrganizationJoinRequest{}).
|
||||
Where("id = ?", id).
|
||||
Updates(map[string]interface{}{
|
||||
"status": status,
|
||||
"reviewed_by": reviewedBy,
|
||||
"reviewed_at": gorm.Expr("NOW()"),
|
||||
"review_message": reviewMessage,
|
||||
}).Error
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// The member limit is enforced with the insert, not by a separate count the
|
||||
// caller did earlier, so concurrent joins cannot exceed it.
|
||||
func TestAddTenantMemberEnforcesLimitWithTheInsert(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.Exec(`CREATE TABLE organization_tenant_members (
|
||||
id TEXT PRIMARY KEY, organization_id TEXT, tenant_id INTEGER, role TEXT,
|
||||
representative_user_id TEXT, joined_at DATETIME, created_at DATETIME, updated_at DATETIME
|
||||
)`).Error)
|
||||
repo := &organizationRepository{db: db}
|
||||
add := func(tenantID uint64, limit int) error {
|
||||
return repo.AddTenantMember(context.Background(), &types.OrganizationTenantMember{
|
||||
ID: fmt.Sprintf("m-%d", tenantID), OrganizationID: "org", TenantID: tenantID, Role: types.OrgRoleViewer,
|
||||
}, limit)
|
||||
}
|
||||
|
||||
require.NoError(t, add(1, 2))
|
||||
require.NoError(t, add(2, 2))
|
||||
require.ErrorIs(t, add(3, 2), ErrOrgMemberLimitReached)
|
||||
require.ErrorIs(t, add(2, 0), ErrOrgMemberAlreadyExists)
|
||||
require.NoError(t, add(3, 0), "no limit")
|
||||
|
||||
var count int64
|
||||
require.NoError(t, db.Model(&types.OrganizationTenantMember{}).Count(&count).Error)
|
||||
require.Equal(t, int64(3), count)
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
// orgCenterRepository 组织中心(租户级共享组织架构)数据访问。
|
||||
// 表: org_depts / org_employees / org_module_members(迁移 000137)。
|
||||
// 企业培训(tr_depts/tr_members 时代)的查询语义在此平移;roles 展示字段
|
||||
// 由指定 module_key 的绑定行联查得出。
|
||||
type orgCenterRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewOrgCenterRepository constructs the org center repository.
|
||||
func NewOrgCenterRepository(db *gorm.DB) interfaces.OrgCenterRepository {
|
||||
return &orgCenterRepository{db: db}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 部门
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// ListDepts returns the tenant's department tree ordered by sort.
|
||||
func (r *orgCenterRepository) ListDepts(ctx context.Context, tenantID uint64) ([]*types.OrgDept, error) {
|
||||
var depts []*types.OrgDept
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ?", tenantID).
|
||||
Order("sort ASC, created_at ASC").
|
||||
Find(&depts).Error
|
||||
return depts, err
|
||||
}
|
||||
|
||||
// CreateDept inserts a department node.
|
||||
func (r *orgCenterRepository) CreateDept(ctx context.Context, dept *types.OrgDept) error {
|
||||
return r.db.WithContext(ctx).Create(dept).Error
|
||||
}
|
||||
|
||||
// UpdateDept updates mutable department fields.
|
||||
func (r *orgCenterRepository) UpdateDept(ctx context.Context, dept *types.OrgDept) error {
|
||||
return r.db.WithContext(ctx).Model(&types.OrgDept{}).
|
||||
Where("tenant_id = ? AND id = ?", dept.TenantID, dept.ID).
|
||||
Updates(map[string]interface{}{
|
||||
"parent_id": dept.ParentID,
|
||||
"name": dept.Name,
|
||||
"code": dept.Code,
|
||||
"sort": dept.Sort,
|
||||
}).Error
|
||||
}
|
||||
|
||||
// DeleteDept soft-deletes a department node.
|
||||
func (r *orgCenterRepository) DeleteDept(ctx context.Context, tenantID uint64, id string) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND id = ?", tenantID, id).
|
||||
Delete(&types.OrgDept{}).Error
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 员工档案
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// employeeFilter 组装员工列表的公共过滤(租户/部门/关键词)。
|
||||
func (r *orgCenterRepository) employeeFilter(ctx context.Context, tenantID uint64, q *types.OrgListQuery) *gorm.DB {
|
||||
tx := r.db.WithContext(ctx).Model(&types.OrgEmployee{}).Where("org_employees.tenant_id = ?", tenantID)
|
||||
if q != nil {
|
||||
if q.DeptID != "" {
|
||||
tx = tx.Where("org_employees.dept_id = ?", q.DeptID)
|
||||
}
|
||||
if q.Keyword != "" {
|
||||
tx = tx.Where("org_employees.employee_no ILIKE ? OR org_employees.post ILIKE ? OR org_employees.user_id ILIKE ?",
|
||||
"%"+q.Keyword+"%", "%"+q.Keyword+"%", "%"+q.Keyword+"%")
|
||||
}
|
||||
}
|
||||
return tx
|
||||
}
|
||||
|
||||
// ListEmployees returns a page of employee profiles with joined display
|
||||
// fields. moduleKey 非空时联查该模块的绑定行得出 roles 展示字段(培训列表传
|
||||
// types.OrgModuleTraining;组织中心自身列表传空保持 '[]')。
|
||||
func (r *orgCenterRepository) ListEmployees(ctx context.Context, tenantID uint64, moduleKey string, q *types.OrgListQuery) ([]*types.OrgEmployee, int64, error) {
|
||||
filter := func() *gorm.DB {
|
||||
return r.employeeFilter(ctx, tenantID, q)
|
||||
}
|
||||
var total int64
|
||||
if err := filter().Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
page, pageSize := 1, 20
|
||||
if q != nil {
|
||||
if q.Page > 0 {
|
||||
page = q.Page
|
||||
}
|
||||
if q.PageSize > 0 {
|
||||
pageSize = q.PageSize
|
||||
}
|
||||
}
|
||||
tx := filter().
|
||||
// user_name 取真实姓名(display_name)优先:员工编号型 IdP(Casdoor)的
|
||||
// username 存工号,真实姓名在 display_name(见 000143 迁移)。
|
||||
Select(`org_employees.*, COALESCE(NULLIF(u.display_name, ''), u.username, '') AS user_name, COALESCE(dp.name, '') AS dept_name`).
|
||||
Joins("LEFT JOIN users u ON u.id = org_employees.user_id").
|
||||
Joins("LEFT JOIN org_depts dp ON dp.id = org_employees.dept_id AND dp.tenant_id = org_employees.tenant_id AND dp.deleted_at IS NULL")
|
||||
if moduleKey != "" {
|
||||
// 绑定行缺失时回退 '[]'(学员为全员隐式角色,无需绑定行)。
|
||||
tx = tx.Select(`org_employees.*, COALESCE(NULLIF(u.display_name, ''), u.username, '') AS user_name, COALESCE(dp.name, '') AS dept_name,
|
||||
COALESCE(mm.roles, '[]'::jsonb) AS roles`).
|
||||
Joins("LEFT JOIN org_module_members mm ON mm.tenant_id = org_employees.tenant_id AND mm.employee_id = org_employees.id AND mm.module_key = ? AND mm.deleted_at IS NULL", moduleKey)
|
||||
}
|
||||
var employees []*types.OrgEmployee
|
||||
err := tx.
|
||||
Order("org_employees.created_at ASC").
|
||||
Offset((page - 1) * pageSize).Limit(pageSize).
|
||||
Find(&employees).Error
|
||||
return employees, total, err
|
||||
}
|
||||
|
||||
// GetEmployee fetches one employee profile by ID.
|
||||
func (r *orgCenterRepository) GetEmployee(ctx context.Context, tenantID uint64, id string) (*types.OrgEmployee, error) {
|
||||
var m types.OrgEmployee
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND id = ?", tenantID, id).
|
||||
First(&m).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &m, nil
|
||||
}
|
||||
|
||||
// GetEmployeeByUserID fetches one employee profile by the platform user ID.
|
||||
func (r *orgCenterRepository) GetEmployeeByUserID(ctx context.Context, tenantID uint64, userID string) (*types.OrgEmployee, error) {
|
||||
var m types.OrgEmployee
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND user_id = ?", tenantID, userID).
|
||||
First(&m).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &m, nil
|
||||
}
|
||||
|
||||
// UpsertEmployees bulk-imports employee profiles keyed by (tenant, user_id).
|
||||
func (r *orgCenterRepository) UpsertEmployees(ctx context.Context, employees []*types.OrgEmployee) error {
|
||||
if len(employees) == 0 {
|
||||
return nil
|
||||
}
|
||||
return r.db.WithContext(ctx).
|
||||
Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "tenant_id"}, {Name: "user_id"}},
|
||||
DoUpdates: clause.Assignments(map[string]interface{}{
|
||||
// 导入行未带工号时保留已有工号(空串不覆盖),与企微账号同款保护:
|
||||
// 防止回填不到平台账号的导入行把原工号洗掉。
|
||||
"employee_no": gorm.Expr("COALESCE(NULLIF(EXCLUDED.employee_no, ''), org_employees.employee_no)"),
|
||||
"dept_id": gorm.Expr("EXCLUDED.dept_id"),
|
||||
"post": gorm.Expr("EXCLUDED.post"),
|
||||
"lecturer_rate": gorm.Expr("EXCLUDED.lecturer_rate"),
|
||||
// 导入行未带企微账号时保留已有绑定(空串不覆盖),防止普通导入冲掉 OA 同步结果。
|
||||
"wecom_userid": gorm.Expr("COALESCE(NULLIF(EXCLUDED.wecom_userid, ''), org_employees.wecom_userid)"),
|
||||
"status": gorm.Expr("EXCLUDED.status"),
|
||||
"updated_at": gorm.Expr("CURRENT_TIMESTAMP"),
|
||||
}),
|
||||
}).
|
||||
Create(&employees).Error
|
||||
}
|
||||
|
||||
// UpdateEmployee updates mutable employee fields.
|
||||
func (r *orgCenterRepository) UpdateEmployee(ctx context.Context, employee *types.OrgEmployee) error {
|
||||
return r.db.WithContext(ctx).Model(&types.OrgEmployee{}).
|
||||
Where("tenant_id = ? AND id = ?", employee.TenantID, employee.ID).
|
||||
Updates(map[string]interface{}{
|
||||
"employee_no": employee.EmployeeNo,
|
||||
"dept_id": employee.DeptID,
|
||||
"post": employee.Post,
|
||||
"lecturer_rate": employee.LecturerRate,
|
||||
"wecom_userid": employee.WecomUserid,
|
||||
"status": employee.Status,
|
||||
}).Error
|
||||
}
|
||||
|
||||
// DeleteEmployee soft-deletes an employee profile.
|
||||
func (r *orgCenterRepository) DeleteEmployee(ctx context.Context, tenantID uint64, id string) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND id = ?", tenantID, id).
|
||||
Delete(&types.OrgEmployee{}).Error
|
||||
}
|
||||
|
||||
// CountEmployees returns the tenant's active employee count.
|
||||
func (r *orgCenterRepository) CountEmployees(ctx context.Context, tenantID uint64) (int64, error) {
|
||||
var count int64
|
||||
err := r.db.WithContext(ctx).Model(&types.OrgEmployee{}).
|
||||
Where("tenant_id = ? AND status = 'active'", tenantID).
|
||||
Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
// ListTenantUsers lists the platform users of the tenant with their roster
|
||||
// membership flag — the source for the employee-import user picker.
|
||||
//
|
||||
// 「平台用户」= 当前空间有 active 成员关系的用户,而不是主空间
|
||||
// (users.tenant_id) 落在本空间的住户:通过邀请或 OIDC 同源自动加入的成员
|
||||
// 主空间在别处,按主空间过滤会让选择器看不到他们(部署实测:共享空间
|
||||
// 锚点看不到自动加入的成员)。名册 join 同样按被查询空间取数。
|
||||
func (r *orgCenterRepository) ListTenantUsers(ctx context.Context, tenantID uint64) ([]*types.TrainingUserInfo, error) {
|
||||
var users []*types.TrainingUserInfo
|
||||
err := r.db.WithContext(ctx).
|
||||
Table("users u").
|
||||
Select(`u.id, u.username, u.email, u.display_name,
|
||||
(m.id IS NOT NULL) AS in_roster`).
|
||||
Joins("JOIN tenant_members tm ON tm.user_id = u.id AND tm.tenant_id = ? "+
|
||||
"AND tm.status = 'active' AND tm.deleted_at IS NULL", tenantID).
|
||||
Joins("LEFT JOIN org_employees m ON m.user_id = u.id AND m.tenant_id = ? AND m.deleted_at IS NULL", tenantID).
|
||||
Where("u.is_active = TRUE AND u.deleted_at IS NULL").
|
||||
Order("u.created_at ASC").
|
||||
Scan(&users).Error
|
||||
return users, err
|
||||
}
|
||||
|
||||
// GetUsernamesByUserIDs resolves platform accounts (users.username) for the
|
||||
// given user IDs within the tenant — used to backfill employee_no on import
|
||||
// (工号 = 平台账号,员工编号型 IdP 同步而来;见 ListTenantUsers 的成员口径注释)。
|
||||
func (r *orgCenterRepository) GetUsernamesByUserIDs(ctx context.Context, tenantID uint64, userIDs []string) (map[string]string, error) {
|
||||
m := make(map[string]string, len(userIDs))
|
||||
if len(userIDs) == 0 {
|
||||
return m, nil
|
||||
}
|
||||
var users []*types.TrainingUserInfo
|
||||
err := r.db.WithContext(ctx).
|
||||
Table("users u").
|
||||
Select("u.id, u.username").
|
||||
Joins("JOIN tenant_members tm ON tm.user_id = u.id AND tm.tenant_id = ? "+
|
||||
"AND tm.status = 'active' AND tm.deleted_at IS NULL", tenantID).
|
||||
Where("u.id IN ?", userIDs).
|
||||
Where("u.is_active = TRUE AND u.deleted_at IS NULL").
|
||||
Scan(&users).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, u := range users {
|
||||
m[u.ID] = u.Username
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 模块角色绑定
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// GetModuleMember fetches one module binding by employee.
|
||||
func (r *orgCenterRepository) GetModuleMember(ctx context.Context, tenantID uint64, moduleKey, employeeID string) (*types.OrgModuleMember, error) {
|
||||
var m types.OrgModuleMember
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND module_key = ? AND employee_id = ? AND deleted_at IS NULL",
|
||||
tenantID, moduleKey, employeeID).
|
||||
First(&m).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &m, nil
|
||||
}
|
||||
|
||||
// UpsertModuleMember inserts or refreshes one module binding keyed by
|
||||
// (tenant, module_key, employee_id).
|
||||
// 表上是部分唯一索引(WHERE deleted_at IS NULL),冲突目标必须带同一谓词,
|
||||
// 否则 Postgres 报 42P10(no unique constraint matching ON CONFLICT)。
|
||||
func (r *orgCenterRepository) UpsertModuleMember(ctx context.Context, member *types.OrgModuleMember) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "tenant_id"}, {Name: "module_key"}, {Name: "employee_id"}},
|
||||
TargetWhere: clause.Where{Exprs: []clause.Expression{
|
||||
gorm.Expr("deleted_at IS NULL"),
|
||||
}},
|
||||
DoUpdates: clause.Assignments(map[string]interface{}{
|
||||
"roles": gorm.Expr("EXCLUDED.roles"),
|
||||
"extra": gorm.Expr("EXCLUDED.extra"),
|
||||
"updated_at": gorm.Expr("CURRENT_TIMESTAMP"),
|
||||
}),
|
||||
}).
|
||||
Create(member).Error
|
||||
}
|
||||
|
||||
// DeleteModuleMember soft-deletes one module binding.
|
||||
func (r *orgCenterRepository) DeleteModuleMember(ctx context.Context, tenantID uint64, moduleKey, employeeID string) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND module_key = ? AND employee_id = ?", tenantID, moduleKey, employeeID).
|
||||
Delete(&types.OrgModuleMember{}).Error
|
||||
}
|
||||
|
||||
// ListModuleMembers lists all bindings of one module.
|
||||
func (r *orgCenterRepository) ListModuleMembers(ctx context.Context, tenantID uint64, moduleKey string) ([]*types.OrgModuleMember, error) {
|
||||
var members []*types.OrgModuleMember
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND module_key = ? AND deleted_at IS NULL", tenantID, moduleKey).
|
||||
Order("created_at ASC").
|
||||
Find(&members).Error
|
||||
return members, err
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Regression for the employee-import user picker: 「平台用户」must follow
|
||||
// tenant_members (active membership), not users.tenant_id (home pointer).
|
||||
// Members who arrive via invitation or the OIDC same-origin auto-join keep
|
||||
// their home tenant elsewhere and were previously invisible to the picker.
|
||||
func TestListTenantUsersIncludesMembershipMembers(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open("file:org-tenant-users?mode=memory&cache=shared"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatalf("open sqlite: %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(&types.User{}, &types.TenantMember{}, &types.OrgEmployee{}); err != nil {
|
||||
t.Fatalf("migrate schema: %v", err)
|
||||
}
|
||||
|
||||
base := time.Date(2026, 11, 10, 3, 0, 0, 0, time.UTC)
|
||||
mkUser := func(id string, home uint64, offset time.Duration) *types.User {
|
||||
return &types.User{
|
||||
ID: id, Username: id, Email: id + "@casdoor.local",
|
||||
TenantID: home, IsActive: true,
|
||||
CreatedAt: base.Add(offset), UpdatedAt: base.Add(offset),
|
||||
}
|
||||
}
|
||||
// Anchor lives (home) and owns tenant 2; the auto-joined member and the
|
||||
// invited member have their home elsewhere; one candidate has no
|
||||
// membership in tenant 2 at all; one membership is soft-deleted.
|
||||
for _, u := range []*types.User{
|
||||
mkUser("anchor", 2, 0),
|
||||
mkUser("auto-joined", 3, time.Hour),
|
||||
mkUser("invited", 4, 2*time.Hour),
|
||||
mkUser("outsider", 5, 3*time.Hour),
|
||||
mkUser("removed", 6, 4*time.Hour),
|
||||
} {
|
||||
if err := db.Create(u).Error; err != nil {
|
||||
t.Fatalf("insert user %s: %v", u.ID, err)
|
||||
}
|
||||
}
|
||||
members := []*types.TenantMember{
|
||||
{UserID: "anchor", TenantID: 2, Role: types.TenantRoleOwner, Status: types.TenantMemberStatusActive, JoinedAt: base},
|
||||
{UserID: "auto-joined", TenantID: 2, Role: types.TenantRoleContributor, Status: types.TenantMemberStatusActive, JoinedAt: base.Add(time.Hour)},
|
||||
{UserID: "invited", TenantID: 2, Role: types.TenantRoleContributor, Status: types.TenantMemberStatusActive, JoinedAt: base.Add(2 * time.Hour)},
|
||||
// Outsider never joined tenant 2. Removed has an inactive-status row
|
||||
// (soft-deleted membership must also be excluded by deleted_at).
|
||||
{UserID: "removed", TenantID: 2, Role: types.TenantRoleContributor, Status: types.TenantMemberStatusActive, JoinedAt: base.Add(4 * time.Hour)},
|
||||
}
|
||||
for _, m := range members {
|
||||
if err := db.Create(m).Error; err != nil {
|
||||
t.Fatalf("insert membership %s: %v", m.UserID, err)
|
||||
}
|
||||
}
|
||||
if err := db.Delete(&types.TenantMember{}, "user_id = ?", "removed").Error; err != nil {
|
||||
t.Fatalf("soft-delete membership: %v", err)
|
||||
}
|
||||
// The anchor already has an employee roster entry in tenant 2.
|
||||
if err := db.Create(&types.OrgEmployee{
|
||||
TenantID: 2, UserID: "anchor", EmployeeNo: "231001",
|
||||
Status: "active",
|
||||
}).Error; err != nil {
|
||||
t.Fatalf("insert roster entry: %v", err)
|
||||
}
|
||||
|
||||
repo := &orgCenterRepository{db: db}
|
||||
users, err := repo.ListTenantUsers(context.Background(), 2)
|
||||
if err != nil {
|
||||
t.Fatalf("ListTenantUsers: %v", err)
|
||||
}
|
||||
|
||||
got := map[string]bool{}
|
||||
for _, u := range users {
|
||||
got[u.ID] = true
|
||||
}
|
||||
for _, want := range []string{"anchor", "auto-joined", "invited"} {
|
||||
if !got[want] {
|
||||
t.Fatalf("user %s missing from picker list: %+v", want, users)
|
||||
}
|
||||
}
|
||||
for _, absent := range []string{"outsider", "removed"} {
|
||||
if got[absent] {
|
||||
t.Fatalf("user %s must not appear (no active membership in tenant 2)", absent)
|
||||
}
|
||||
}
|
||||
if users[0].ID != "anchor" {
|
||||
t.Fatalf("first user = %s, want anchor (created_at ASC)", users[0].ID)
|
||||
}
|
||||
|
||||
byID := map[string]*types.TrainingUserInfo{}
|
||||
for _, u := range users {
|
||||
byID[u.ID] = u
|
||||
}
|
||||
if !byID["anchor"].InRoster {
|
||||
t.Fatal("anchor InRoster = false, want true (roster entry in tenant 2)")
|
||||
}
|
||||
if byID["auto-joined"].InRoster {
|
||||
t.Fatal("auto-joined InRoster = true, want false (no roster entry)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Regression for 「工号 = 平台账号」: the employee-import backfill resolves
|
||||
// empty employee_no from users.username. The resolution must follow the same
|
||||
// tenant-membership scope as the import picker (active membership, active
|
||||
// user) — see TestListTenantUsersIncludesMembershipMembers for the matching
|
||||
// ListTenantUsers regression.
|
||||
func TestGetUsernamesByUserIDsFollowsTenantMembership(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open("file:org-username-backfill?mode=memory&cache=shared"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatalf("open sqlite: %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(&types.User{}, &types.TenantMember{}); err != nil {
|
||||
t.Fatalf("migrate schema: %v", err)
|
||||
}
|
||||
|
||||
base := time.Date(2026, 11, 12, 3, 0, 0, 0, time.UTC)
|
||||
mkUser := func(id string, active bool) *types.User {
|
||||
return &types.User{
|
||||
ID: id, Username: "26" + id, Email: id + "@casdoor.local",
|
||||
TenantID: 9, IsActive: active,
|
||||
CreatedAt: base, UpdatedAt: base,
|
||||
}
|
||||
}
|
||||
// u-member: active member of tenant 2 (resolvable);
|
||||
// u-gone: membership exists but the user is deactivated;
|
||||
// u-outsider: active user, but never joined tenant 2.
|
||||
for _, u := range []*types.User{
|
||||
mkUser("u-member", true),
|
||||
mkUser("u-gone", false),
|
||||
mkUser("u-outsider", true),
|
||||
} {
|
||||
if err := db.Create(u).Error; err != nil {
|
||||
t.Fatalf("insert user %s: %v", u.ID, err)
|
||||
}
|
||||
}
|
||||
for _, m := range []*types.TenantMember{
|
||||
{UserID: "u-member", TenantID: 2, Role: types.TenantRoleContributor, Status: types.TenantMemberStatusActive, JoinedAt: base},
|
||||
{UserID: "u-gone", TenantID: 2, Role: types.TenantRoleContributor, Status: types.TenantMemberStatusActive, JoinedAt: base},
|
||||
{UserID: "u-outsider", TenantID: 3, Role: types.TenantRoleContributor, Status: types.TenantMemberStatusActive, JoinedAt: base},
|
||||
} {
|
||||
if err := db.Create(m).Error; err != nil {
|
||||
t.Fatalf("insert membership %s: %v", m.UserID, err)
|
||||
}
|
||||
}
|
||||
|
||||
repo := &orgCenterRepository{db: db}
|
||||
got, err := repo.GetUsernamesByUserIDs(context.Background(), 2, []string{
|
||||
"u-member", "u-gone", "u-outsider", "u-missing",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("GetUsernamesByUserIDs: %v", err)
|
||||
}
|
||||
if len(got) != 1 || got["u-member"] != "26u-member" {
|
||||
t.Fatalf("unexpected username map: %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// The (tenant,user)-keyed upsert must not wash an existing employee_no when
|
||||
// the import row carries none (backfill unresolved), and must still overwrite
|
||||
// when an explicit number is provided — mirroring the wecom_userid guard.
|
||||
func TestUpsertEmployeesKeepsEmployeeNoWhenImportBlank(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open("file:org-upsert-empno?mode=memory&cache=shared"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatalf("open sqlite: %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(&types.OrgEmployee{}); err != nil {
|
||||
t.Fatalf("migrate schema: %v", err)
|
||||
}
|
||||
if err := db.Create(&types.OrgEmployee{
|
||||
TenantID: 2, UserID: "u1", EmployeeNo: "26010003",
|
||||
DeptID: "d-old", Status: "active",
|
||||
}).Error; err != nil {
|
||||
t.Fatalf("seed employee: %v", err)
|
||||
}
|
||||
|
||||
repo := &orgCenterRepository{db: db}
|
||||
blank := []*types.OrgEmployee{{
|
||||
ID: "e-blank", TenantID: 2, UserID: "u1",
|
||||
EmployeeNo: "", DeptID: "d-new", Status: "active",
|
||||
}}
|
||||
if err := repo.UpsertEmployees(context.Background(), blank); err != nil {
|
||||
t.Fatalf("upsert blank employee_no: %v", err)
|
||||
}
|
||||
var kept types.OrgEmployee
|
||||
if err := db.Where("tenant_id = 2 AND user_id = 'u1'").First(&kept).Error; err != nil {
|
||||
t.Fatalf("reload employee: %v", err)
|
||||
}
|
||||
if kept.EmployeeNo != "26010003" {
|
||||
t.Fatalf("existing employee_no washed by blank import: %q", kept.EmployeeNo)
|
||||
}
|
||||
if kept.DeptID != "d-new" {
|
||||
t.Fatalf("dept_id not updated: %q", kept.DeptID)
|
||||
}
|
||||
|
||||
explicit := []*types.OrgEmployee{{
|
||||
ID: "e-explicit", TenantID: 2, UserID: "u1",
|
||||
EmployeeNo: "26010003", DeptID: "d-new", Status: "active",
|
||||
}}
|
||||
if err := repo.UpsertEmployees(context.Background(), explicit); err != nil {
|
||||
t.Fatalf("upsert explicit employee_no: %v", err)
|
||||
}
|
||||
var updated types.OrgEmployee
|
||||
if err := db.Where("tenant_id = 2 AND user_id = 'u1'").First(&updated).Error; err != nil {
|
||||
t.Fatalf("reload employee: %v", err)
|
||||
}
|
||||
if updated.EmployeeNo != "26010003" || updated.DeptID != "d-new" {
|
||||
t.Fatalf("unexpected state after explicit upsert: no=%q dept=%q", updated.EmployeeNo, updated.DeptID)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type resourceRepository struct{ db *gorm.DB }
|
||||
|
||||
// NewResourceRepository creates the persistence adapter for resource metadata.
|
||||
func NewResourceRepository(db *gorm.DB) interfaces.ResourceRepository {
|
||||
return &resourceRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *resourceRepository) Create(ctx context.Context, resource *types.StoredResource) error {
|
||||
return r.db.WithContext(ctx).Create(resource).Error
|
||||
}
|
||||
|
||||
func (r *resourceRepository) GetByID(ctx context.Context, id string) (*types.StoredResource, error) {
|
||||
var resource types.StoredResource
|
||||
err := r.db.WithContext(ctx).Where("id = ? AND state = ?", id, types.ResourceStateActive).First(&resource).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return &resource, err
|
||||
}
|
||||
|
||||
func (r *resourceRepository) BindStorageBackend(
|
||||
ctx context.Context, id, backendID string,
|
||||
) (*types.StoredResource, error) {
|
||||
err := r.db.WithContext(ctx).Model(&types.StoredResource{}).
|
||||
Where("id = ? AND state = ? AND (storage_backend_id = '' OR storage_backend_id IS NULL)",
|
||||
id, types.ResourceStateActive).
|
||||
Update("storage_backend_id", backendID).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return r.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
func (r *resourceRepository) GetByHandle(ctx context.Context, handle string) (*types.StoredResource, error) {
|
||||
var resource types.StoredResource
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("handle = ? AND state = ?", handle, types.ResourceStateActive).
|
||||
First(&resource).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return &resource, err
|
||||
}
|
||||
|
||||
func (r *resourceRepository) GetByTenantLocation(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
locationHash string,
|
||||
) (*types.StoredResource, error) {
|
||||
var resource types.StoredResource
|
||||
err := r.db.WithContext(ctx).
|
||||
Where(
|
||||
"tenant_id = ? AND location_hash = ? AND state = ?",
|
||||
tenantID,
|
||||
locationHash,
|
||||
types.ResourceStateActive,
|
||||
).
|
||||
First(&resource).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return &resource, err
|
||||
}
|
||||
|
||||
// GetActiveByContentHash resolves identical bytes already registered under any
|
||||
// physical location. The content hash is not unique — duplicates written before
|
||||
// this lookup existed may share it — so the oldest live row is returned to keep
|
||||
// the choice stable between calls.
|
||||
func (r *resourceRepository) GetActiveByContentHash(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
contentHash string,
|
||||
) (*types.StoredResource, error) {
|
||||
var resource types.StoredResource
|
||||
err := r.db.WithContext(ctx).
|
||||
Where(
|
||||
"tenant_id = ? AND content_hash = ? AND content_hash <> '' "+
|
||||
"AND state = ? AND deleted_at IS NULL",
|
||||
tenantID,
|
||||
contentHash,
|
||||
types.ResourceStateActive,
|
||||
).
|
||||
Order("created_at ASC, id ASC").
|
||||
First(&resource).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return &resource, err
|
||||
}
|
||||
|
||||
func (r *resourceRepository) MarkDeleted(ctx context.Context, id string) error {
|
||||
return r.db.WithContext(ctx).Model(&types.StoredResource{}).Where("id = ?", id).
|
||||
Updates(map[string]interface{}{"state": types.ResourceStateDeleted, "deleted_at": time.Now()}).Error
|
||||
}
|
||||
|
||||
func (r *resourceRepository) CreateBinding(ctx context.Context, binding *types.ResourceBinding) error {
|
||||
return r.db.WithContext(ctx).Clauses(clause.OnConflict{DoNothing: true}).Create(binding).Error
|
||||
}
|
||||
|
||||
// DeleteBinding removes one owner's claim on a resource. Deleting a claim that
|
||||
// was never recorded is not an error: callers release optimistically, from a
|
||||
// content scan that cannot know which references were bound.
|
||||
func (r *resourceRepository) DeleteBinding(ctx context.Context, resourceID, ownerType, ownerID string) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Where("resource_id = ? AND owner_type = ? AND owner_id = ?", resourceID, ownerType, ownerID).
|
||||
Delete(&types.ResourceBinding{}).Error
|
||||
}
|
||||
|
||||
func (r *resourceRepository) CountBindings(ctx context.Context, resourceID string) (int64, error) {
|
||||
var count int64
|
||||
err := r.db.WithContext(ctx).Model(&types.ResourceBinding{}).
|
||||
Where("resource_id = ?", resourceID).
|
||||
Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
func (r *resourceRepository) ListHandlesByOwner(
|
||||
ctx context.Context, ownerType string, ownerIDs, relations []string,
|
||||
) ([]string, error) {
|
||||
if ownerType == "" || len(ownerIDs) == 0 || len(relations) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var handles []string
|
||||
err := r.db.WithContext(ctx).
|
||||
Table("resource_bindings AS b").
|
||||
Joins("JOIN resources AS r ON r.id = b.resource_id AND r.state = ?", types.ResourceStateActive).
|
||||
Where("b.owner_type = ? AND b.owner_id IN ? AND b.relation IN ?", ownerType, ownerIDs, relations).
|
||||
Distinct("r.handle").
|
||||
Pluck("r.handle", &handles).Error
|
||||
return handles, err
|
||||
}
|
||||
|
||||
func (r *resourceRepository) CreateGrant(ctx context.Context, grant *types.ResourceAccessGrant) error {
|
||||
return r.db.WithContext(ctx).Create(grant).Error
|
||||
}
|
||||
|
||||
func (r *resourceRepository) GetValidGrant(
|
||||
ctx context.Context,
|
||||
tokenHash string,
|
||||
now time.Time,
|
||||
) (*types.ResourceAccessGrant, error) {
|
||||
var grant types.ResourceAccessGrant
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("token_hash = ? AND revoked_at IS NULL AND expires_at > ?", tokenHash, now).
|
||||
First(&grant).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return &grant, err
|
||||
}
|
||||
|
||||
// DeleteExpiredGrants drops grants that are past their expiry. A revoked grant
|
||||
// is kept until then on purpose: it is the tombstone that stops a token derived
|
||||
// for the same resource and window from re-creating the row and reviving access.
|
||||
func (r *resourceRepository) DeleteExpiredGrants(ctx context.Context, before time.Time) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Where("expires_at <= ?", before).
|
||||
Delete(&types.ResourceAccessGrant{}).Error
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func newResourceContentHashTestRepo(t *testing.T) *resourceRepository {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
sqlDB, err := db.DB()
|
||||
require.NoError(t, err)
|
||||
// A single connection keeps the in-memory database from vanishing behind a
|
||||
// second pooled connection.
|
||||
sqlDB.SetMaxOpenConns(1)
|
||||
t.Cleanup(func() { require.NoError(t, sqlDB.Close()) })
|
||||
require.NoError(t, db.AutoMigrate(&types.StoredResource{}))
|
||||
return NewResourceRepository(db).(*resourceRepository)
|
||||
}
|
||||
|
||||
func storedResource(id, handle string, tenantID uint64, contentHash string, createdAt time.Time) *types.StoredResource {
|
||||
return &types.StoredResource{
|
||||
ID: id,
|
||||
Handle: handle,
|
||||
TenantID: tenantID,
|
||||
Provider: "local",
|
||||
PhysicalPath: "local://" + id + "/exports/" + id + ".png",
|
||||
LocationHash: id,
|
||||
Kind: "image",
|
||||
ContentHash: contentHash,
|
||||
CreatedAt: createdAt,
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetActiveByContentHashFindsLiveRow(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := newResourceContentHashTestRepo(t)
|
||||
require.NoError(t, repo.Create(ctx, storedResource("r1", "HandleAAAAAAAAAAAAAA01", 7, "hash-a", time.Now())))
|
||||
|
||||
found, err := repo.GetActiveByContentHash(ctx, 7, "hash-a")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, found)
|
||||
require.Equal(t, "r1", found.ID)
|
||||
require.Equal(t, "hash-a", found.ContentHash)
|
||||
}
|
||||
|
||||
func TestGetActiveByContentHashMisses(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := newResourceContentHashTestRepo(t)
|
||||
require.NoError(t, repo.Create(ctx, storedResource("r1", "HandleAAAAAAAAAAAAAA01", 7, "hash-a", time.Now())))
|
||||
require.NoError(t, repo.Create(ctx, storedResource("r2", "HandleAAAAAAAAAAAAAA02", 7, "", time.Now())))
|
||||
|
||||
for label, query := range map[string]struct {
|
||||
tenantID uint64
|
||||
hash string
|
||||
}{
|
||||
"unknown hash": {7, "hash-missing"},
|
||||
"other tenant": {8, "hash-a"},
|
||||
"zero tenant": {0, "hash-a"},
|
||||
"blank hash": {7, ""},
|
||||
} {
|
||||
found, err := repo.GetActiveByContentHash(ctx, query.tenantID, query.hash)
|
||||
require.NoError(t, err, label)
|
||||
require.Nilf(t, found, "case %s", label)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetActiveByContentHashIgnoresDeletedRows(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := newResourceContentHashTestRepo(t)
|
||||
require.NoError(t, repo.Create(ctx, storedResource("r1", "HandleAAAAAAAAAAAAAA01", 7, "hash-a", time.Now())))
|
||||
require.NoError(t, repo.MarkDeleted(ctx, "r1"))
|
||||
|
||||
found, err := repo.GetActiveByContentHash(ctx, 7, "hash-a")
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, found, "a soft-deleted resource must not be reused")
|
||||
}
|
||||
|
||||
// Rows registered before this lookup existed can share a hash. The choice has to
|
||||
// be deterministic or two identical requests could be handed different handles.
|
||||
func TestGetActiveByContentHashPrefersOldestDuplicate(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := newResourceContentHashTestRepo(t)
|
||||
now := time.Now()
|
||||
require.NoError(t, repo.Create(ctx, storedResource("r-new", "HandleAAAAAAAAAAAAAA02", 7, "hash-a", now)))
|
||||
require.NoError(t, repo.Create(ctx, storedResource(
|
||||
"r-old", "HandleAAAAAAAAAAAAAA01", 7, "hash-a", now.Add(-time.Hour),
|
||||
)))
|
||||
|
||||
found, err := repo.GetActiveByContentHash(ctx, 7, "hash-a")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, found)
|
||||
require.Equal(t, "r-old", found.ID)
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// IsReferencedByKnowledgeBase accepts only explicit bindings to live documents.
|
||||
// Text mentioning a handle or physical path is never ownership evidence.
|
||||
func (r *resourceRepository) IsReferencedByKnowledgeBase(
|
||||
ctx context.Context, tenantID uint64, kbID, resourceID string,
|
||||
) (bool, error) {
|
||||
if tenantID == 0 || kbID == "" || resourceID == "" {
|
||||
return false, nil
|
||||
}
|
||||
var count int64
|
||||
err := r.db.WithContext(ctx).Table("resource_bindings AS b").
|
||||
Joins("JOIN knowledges AS k ON k.id = b.owner_id AND k.tenant_id = b.tenant_id").
|
||||
Joins("JOIN knowledge_bases AS kb ON kb.id = k.knowledge_base_id "+
|
||||
"AND kb.tenant_id = k.tenant_id AND kb.deleted_at IS NULL").
|
||||
Where("b.resource_id = ? AND b.owner_type = ? AND b.tenant_id = ? "+
|
||||
"AND k.knowledge_base_id = ? AND k.deleted_at IS NULL",
|
||||
resourceID, types.ResourceOwnerKnowledge, tenantID, kbID).Count(&count).Error
|
||||
return count > 0, err
|
||||
}
|
||||
|
||||
func (r *resourceRepository) GetMessageFileBindings(
|
||||
ctx context.Context, tenantID uint64, resourceID, messageID string,
|
||||
) (*types.MessageFileBindings, error) {
|
||||
result := &types.MessageFileBindings{}
|
||||
if tenantID == 0 || resourceID == "" {
|
||||
return result, nil
|
||||
}
|
||||
err := r.db.WithContext(ctx).Table("resource_bindings AS b").
|
||||
Joins("JOIN knowledges AS k ON k.id = b.owner_id AND k.tenant_id = b.tenant_id").
|
||||
Joins("JOIN knowledge_bases AS kb ON kb.id = k.knowledge_base_id "+
|
||||
"AND kb.tenant_id = k.tenant_id AND kb.deleted_at IS NULL").
|
||||
Where("b.resource_id = ? AND b.owner_type = ? AND b.tenant_id = ? AND k.deleted_at IS NULL",
|
||||
resourceID, types.ResourceOwnerKnowledge, tenantID).
|
||||
Distinct("k.knowledge_base_id").Pluck("k.knowledge_base_id", &result.KnowledgeBaseIDs).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if messageID != "" {
|
||||
var count int64
|
||||
err = r.db.WithContext(ctx).Model(&types.ResourceBinding{}).
|
||||
Where("resource_id = ? AND tenant_id = ? AND owner_type = ? AND owner_id = ? AND relation = ?",
|
||||
resourceID, tenantID, types.ResourceOwnerMessage, messageID, types.ResourceRelationArtifact).
|
||||
Count(&count).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result.MessageArtifact = count > 0
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
package doris
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"academy/internal/logger"
|
||||
)
|
||||
|
||||
const envDorisCompatMode = "DORIS_COMPAT_MODE"
|
||||
|
||||
type dorisCompatMode string
|
||||
|
||||
const (
|
||||
dorisCompatModeAuto dorisCompatMode = "auto"
|
||||
dorisCompatModeLegacy dorisCompatMode = "legacy"
|
||||
dorisCompatModeInnerProductDuplicate dorisCompatMode = "inner_product_duplicate"
|
||||
)
|
||||
|
||||
type dorisCompatProbe struct {
|
||||
innerProductApproximate bool
|
||||
cosineDistanceApproximate bool
|
||||
}
|
||||
|
||||
func resolveConfiguredDorisCompatMode() (mode dorisCompatMode, invalid string) {
|
||||
raw := strings.TrimSpace(os.Getenv(envDorisCompatMode))
|
||||
if raw == "" {
|
||||
return dorisCompatModeAuto, ""
|
||||
}
|
||||
|
||||
switch strings.ToLower(raw) {
|
||||
case string(dorisCompatModeAuto):
|
||||
return dorisCompatModeAuto, ""
|
||||
case string(dorisCompatModeLegacy):
|
||||
return dorisCompatModeLegacy, ""
|
||||
case string(dorisCompatModeInnerProductDuplicate), "inner-product-duplicate", "inner_product", "inner-product":
|
||||
return dorisCompatModeInnerProductDuplicate, ""
|
||||
default:
|
||||
return dorisCompatModeAuto, raw
|
||||
}
|
||||
}
|
||||
|
||||
func (r *dorisRepository) resolveCompatMode(ctx context.Context) (dorisCompatMode, error) {
|
||||
r.compatResolveOnce.Do(func() {
|
||||
log := logger.GetLogger(ctx)
|
||||
requested := r.compatModeRequested
|
||||
if requested == "" {
|
||||
r.compatModeResolved = dorisCompatModeInnerProductDuplicate
|
||||
return
|
||||
}
|
||||
|
||||
existingMode, exampleTable, foundExisting, err := r.detectExistingCompatMode(ctx)
|
||||
if err != nil {
|
||||
r.compatResolveErr = err
|
||||
return
|
||||
}
|
||||
|
||||
if foundExisting {
|
||||
if requested != dorisCompatModeAuto && requested != existingMode {
|
||||
r.compatResolveErr = fmt.Errorf(
|
||||
"Doris compat mode %q does not match existing embedding tables (detected %q from %s). %s is not interchangeable after %s_* tables are created. Recreate the existing %s_* tables before switching modes, or set %s=%s",
|
||||
requested,
|
||||
existingMode,
|
||||
exampleTable,
|
||||
envDorisCompatMode,
|
||||
r.tableBaseName,
|
||||
r.tableBaseName,
|
||||
envDorisCompatMode,
|
||||
existingMode,
|
||||
)
|
||||
log.Errorf("[Doris] %v", r.compatResolveErr)
|
||||
return
|
||||
}
|
||||
|
||||
r.compatModeResolved = existingMode
|
||||
log.Warnf(
|
||||
"[Doris] Using compat mode %s from existing embedding tables (%s). %s is not interchangeable after %s_* tables are created; recreate those tables before switching modes.",
|
||||
existingMode,
|
||||
exampleTable,
|
||||
envDorisCompatMode,
|
||||
r.tableBaseName,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if requested == dorisCompatModeAuto {
|
||||
probe, probeErr := r.probeCompatMode(ctx)
|
||||
if probeErr != nil {
|
||||
r.compatResolveErr = probeErr
|
||||
log.Errorf("[Doris] %v", probeErr)
|
||||
return
|
||||
}
|
||||
log.Infof(
|
||||
"[Doris] Compat probe result: inner_product_approximate=%t, cosine_distance_approximate=%t",
|
||||
probe.innerProductApproximate,
|
||||
probe.cosineDistanceApproximate,
|
||||
)
|
||||
|
||||
switch {
|
||||
case probe.innerProductApproximate:
|
||||
r.compatModeResolved = dorisCompatModeInnerProductDuplicate
|
||||
case probe.cosineDistanceApproximate:
|
||||
r.compatModeResolved = dorisCompatModeLegacy
|
||||
default:
|
||||
r.compatResolveErr = fmt.Errorf(
|
||||
"Doris compatibility auto-detection could not find a supported vector function. Set %s=%s or %s=%s explicitly after verifying your Doris build. %s is not interchangeable after %s_* tables are created",
|
||||
envDorisCompatMode,
|
||||
dorisCompatModeInnerProductDuplicate,
|
||||
envDorisCompatMode,
|
||||
dorisCompatModeLegacy,
|
||||
envDorisCompatMode,
|
||||
r.tableBaseName,
|
||||
)
|
||||
log.Errorf("[Doris] %v", r.compatResolveErr)
|
||||
return
|
||||
}
|
||||
|
||||
log.Warnf(
|
||||
"[Doris] Auto-selected compat mode %s for new embedding tables. %s is not interchangeable after %s_* tables are created; recreate those tables before switching modes.",
|
||||
r.compatModeResolved,
|
||||
envDorisCompatMode,
|
||||
r.tableBaseName,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
r.compatModeResolved = requested
|
||||
log.Warnf(
|
||||
"[Doris] Using configured compat mode %s for new embedding tables. %s is not interchangeable after %s_* tables are created; recreate those tables before switching modes.",
|
||||
r.compatModeResolved,
|
||||
envDorisCompatMode,
|
||||
r.tableBaseName,
|
||||
)
|
||||
})
|
||||
|
||||
return r.compatModeResolved, r.compatResolveErr
|
||||
}
|
||||
|
||||
func (r *dorisRepository) detectExistingCompatMode(ctx context.Context) (dorisCompatMode, string, bool, error) {
|
||||
tables, err := r.listEmbeddingTables(ctx)
|
||||
if err != nil {
|
||||
return "", "", false, fmt.Errorf("list Doris embedding tables: %w", err)
|
||||
}
|
||||
if len(tables) == 0 {
|
||||
return "", "", false, nil
|
||||
}
|
||||
sort.Strings(tables)
|
||||
|
||||
var detected dorisCompatMode
|
||||
for _, table := range tables {
|
||||
ddl, err := r.showCreateTable(ctx, table)
|
||||
if err != nil {
|
||||
return "", "", false, fmt.Errorf("show create table %s: %w", table, err)
|
||||
}
|
||||
mode, err := compatModeFromDDL(ddl)
|
||||
if err != nil {
|
||||
return "", "", false, fmt.Errorf("detect compat mode from %s: %w", table, err)
|
||||
}
|
||||
if detected == "" {
|
||||
detected = mode
|
||||
continue
|
||||
}
|
||||
if detected != mode {
|
||||
return "", "", false, fmt.Errorf(
|
||||
"existing Doris embedding tables use mixed compat modes (%s and %s). %s is not interchangeable after %s_* tables are created; recreate the existing %s_* tables with a single mode",
|
||||
detected,
|
||||
mode,
|
||||
envDorisCompatMode,
|
||||
r.tableBaseName,
|
||||
r.tableBaseName,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return detected, tables[0], true, nil
|
||||
}
|
||||
|
||||
func (r *dorisRepository) showCreateTable(ctx context.Context, table string) (string, error) {
|
||||
row := r.db.QueryRowContext(ctx, fmt.Sprintf("SHOW CREATE TABLE `%s`", table))
|
||||
var tableName, ddl string
|
||||
if err := row.Scan(&tableName, &ddl); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return ddl, nil
|
||||
}
|
||||
|
||||
func compatModeFromDDL(ddl string) (dorisCompatMode, error) {
|
||||
normalized := strings.ToLower(ddl)
|
||||
switch {
|
||||
case strings.Contains(normalized, "duplicate key("):
|
||||
return dorisCompatModeInnerProductDuplicate, nil
|
||||
case strings.Contains(normalized, "unique key("):
|
||||
return dorisCompatModeLegacy, nil
|
||||
default:
|
||||
return "", fmt.Errorf("unsupported table definition; expected UNIQUE KEY or DUPLICATE KEY")
|
||||
}
|
||||
}
|
||||
|
||||
func (r *dorisRepository) probeCompatMode(ctx context.Context) (dorisCompatProbe, error) {
|
||||
probe := dorisCompatProbe{}
|
||||
probe.innerProductApproximate = r.vectorFunctionSupported(ctx, "inner_product_approximate([1.0],[1.0])")
|
||||
probe.cosineDistanceApproximate = r.vectorFunctionSupported(ctx, "cosine_distance_approximate([1.0],[1.0])")
|
||||
return probe, nil
|
||||
}
|
||||
|
||||
func (r *dorisRepository) vectorFunctionSupported(ctx context.Context, expr string) bool {
|
||||
var value sql.NullFloat64
|
||||
if err := r.db.QueryRowContext(ctx, "SELECT "+expr).Scan(&value); err != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (m dorisCompatMode) normalizeEmbeddings() bool {
|
||||
return m != dorisCompatModeLegacy
|
||||
}
|
||||
|
||||
func (m dorisCompatMode) usesReplaceWrite() bool {
|
||||
return m != dorisCompatModeLegacy
|
||||
}
|
||||
|
||||
func (m dorisCompatMode) usesRewriteChunkUpdates() bool {
|
||||
return m != dorisCompatModeLegacy
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package doris
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func (r *dorisRepository) ValidateKnowledgeIndexMove(ctx context.Context) error {
|
||||
mode, err := r.resolveCompatMode(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if mode.usesRewriteChunkUpdates() {
|
||||
// ANN DUPLICATE KEY tables implement replacement as DELETE + INSERT.
|
||||
// A failed insert would lose the only vector copy; changing physical IDs
|
||||
// would break the stable source-ID identity used by subsequent edits.
|
||||
return fmt.Errorf("reuse_vectors move is not supported by Doris ANN tables; use reparse mode")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *dorisRepository) MoveKnowledgeIndices(
|
||||
ctx context.Context,
|
||||
sourceKB, targetKB, knowledgeID string,
|
||||
_ []string,
|
||||
dimension int,
|
||||
_ string,
|
||||
) error {
|
||||
if err := r.ValidateKnowledgeIndexMove(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if dimension <= 0 {
|
||||
return fmt.Errorf("invalid embedding dimension")
|
||||
}
|
||||
query := fmt.Sprintf(
|
||||
"UPDATE `%s` SET knowledge_base_id = ?, tag_id = '' WHERE knowledge_base_id = ? AND knowledge_id = ?",
|
||||
r.getTableName(dimension),
|
||||
)
|
||||
_, err := r.db.ExecContext(ctx, query, targetKB, sourceKB, knowledgeID)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package doris
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestMoveIndicesRejectsNonAtomicANNReplacement(t *testing.T) {
|
||||
repo, mock, _, cleanup := newTestRepo(t)
|
||||
defer cleanup()
|
||||
primeCompatMode(repo, dorisCompatModeInnerProductDuplicate, nil)
|
||||
require.ErrorContains(
|
||||
t,
|
||||
repo.MoveKnowledgeIndices(context.Background(), "source", "target", "doc", []string{"chunk"}, 2, "document"),
|
||||
"use reparse mode",
|
||||
)
|
||||
require.NoError(t, mock.ExpectationsWereMet(), "rejection must issue no vector delete or insert")
|
||||
}
|
||||
|
||||
func TestMoveIndicesLegacyUpdatesOnlyExactSourceDocument(t *testing.T) {
|
||||
repo, mock, _, cleanup := newTestRepo(t)
|
||||
defer cleanup()
|
||||
primeCompatMode(repo, dorisCompatModeLegacy, nil)
|
||||
mock.ExpectExec("UPDATE `academy_embeddings_2` SET knowledge_base_id = \\?, tag_id = '' WHERE "+
|
||||
"knowledge_base_id = \\? AND knowledge_id = \\?").
|
||||
WithArgs("target", "source", "doc").
|
||||
WillReturnResult(sqlmock.NewResult(0, 3))
|
||||
require.NoError(
|
||||
t,
|
||||
repo.MoveKnowledgeIndices(context.Background(), "source", "target", "doc", []string{"chunk"}, 2, "document"),
|
||||
)
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
package doris
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// 字段名常量。Doris 是 SQL 库,字段名要在 SELECT/WHERE/INSERT 多处复用,
|
||||
// 用常量统一防止笔误。
|
||||
const (
|
||||
fieldID = "id"
|
||||
fieldContent = "content"
|
||||
fieldSourceID = "source_id"
|
||||
fieldSourceType = "source_type"
|
||||
fieldChunkID = "chunk_id"
|
||||
fieldKnowledgeID = "knowledge_id"
|
||||
fieldKnowledgeBaseID = "knowledge_base_id"
|
||||
fieldTagID = "tag_id"
|
||||
fieldIsEnabled = "is_enabled"
|
||||
fieldEmbedding = "embedding"
|
||||
)
|
||||
|
||||
// columns 是 INSERT / SELECT 时使用的标准列序。
|
||||
var columns = []string{
|
||||
fieldID, fieldContent, fieldSourceID, fieldSourceType,
|
||||
fieldChunkID, fieldKnowledgeID, fieldKnowledgeBaseID, fieldTagID,
|
||||
fieldIsEnabled, fieldEmbedding,
|
||||
}
|
||||
|
||||
// columnsForRetrieve 是 Retrieve 时 SELECT 的列序,
|
||||
// 不包含 embedding(向量本身查询结果中无需返回,省带宽)。
|
||||
var columnsForRetrieve = []string{
|
||||
fieldID, fieldContent, fieldSourceID, fieldSourceType,
|
||||
fieldChunkID, fieldKnowledgeID, fieldKnowledgeBaseID, fieldTagID,
|
||||
fieldIsEnabled,
|
||||
}
|
||||
|
||||
// columnsForCopy 是 CopyIndices 中分页 SELECT 时使用的列序,
|
||||
// 比 columnsForRetrieve 多 embedding,因为复制目的是搬运向量本身。
|
||||
var columnsForCopy = []string{
|
||||
fieldID, fieldContent, fieldSourceID, fieldSourceType,
|
||||
fieldChunkID, fieldKnowledgeID, fieldKnowledgeBaseID, fieldTagID,
|
||||
fieldIsEnabled, fieldEmbedding,
|
||||
}
|
||||
|
||||
// whereCond 表示一个 WHERE 子条件:clause 是参数化 SQL 片段(带 ? 占位),
|
||||
// args 是对应顺序的参数值。所有用户输入字段(IDs)必须通过 args 传入,
|
||||
// 严禁拼到 clause 字符串里。
|
||||
type whereCond struct {
|
||||
clause string
|
||||
args []any
|
||||
}
|
||||
|
||||
// whereBuilder 用于把 RetrieveParams 中的过滤条件翻译成 SQL WHERE 子句。
|
||||
//
|
||||
// 每个 add* 方法对应一种 IN / NOT IN / = 算子;最终 build() 用 AND 拼接。
|
||||
type whereBuilder struct {
|
||||
conds []whereCond
|
||||
}
|
||||
|
||||
// addEqual 追加一个 field = ? 条件。
|
||||
func (w *whereBuilder) addEqual(field string, value any) {
|
||||
w.conds = append(w.conds, whereCond{
|
||||
clause: field + " = ?",
|
||||
args: []any{value},
|
||||
})
|
||||
}
|
||||
|
||||
// addIn 追加一个 field IN (?, ?, ...) 条件。values 为空时不追加任何东西。
|
||||
func (w *whereBuilder) addIn(field string, values []string) {
|
||||
if len(values) == 0 {
|
||||
return
|
||||
}
|
||||
placeholders := make([]string, len(values))
|
||||
args := make([]any, len(values))
|
||||
for i, v := range values {
|
||||
placeholders[i] = "?"
|
||||
args[i] = v
|
||||
}
|
||||
w.conds = append(w.conds, whereCond{
|
||||
clause: field + " IN (" + strings.Join(placeholders, ", ") + ")",
|
||||
args: args,
|
||||
})
|
||||
}
|
||||
|
||||
// addNotIn 追加一个 field NOT IN (?, ?, ...) 条件。
|
||||
func (w *whereBuilder) addNotIn(field string, values []string) {
|
||||
if len(values) == 0 {
|
||||
return
|
||||
}
|
||||
placeholders := make([]string, len(values))
|
||||
args := make([]any, len(values))
|
||||
for i, v := range values {
|
||||
placeholders[i] = "?"
|
||||
args[i] = v
|
||||
}
|
||||
w.conds = append(w.conds, whereCond{
|
||||
clause: field + " NOT IN (" + strings.Join(placeholders, ", ") + ")",
|
||||
args: args,
|
||||
})
|
||||
}
|
||||
|
||||
// build 返回 WHERE 子句(不含 "WHERE " 前缀)和参数数组。
|
||||
// 没有任何条件时返回 ("1 = 1", nil),方便调用方无脑拼接。
|
||||
func (w *whereBuilder) build() (string, []any) {
|
||||
if len(w.conds) == 0 {
|
||||
return "1 = 1", nil
|
||||
}
|
||||
parts := make([]string, len(w.conds))
|
||||
var args []any
|
||||
for i, c := range w.conds {
|
||||
parts[i] = c.clause
|
||||
args = append(args, c.args...)
|
||||
}
|
||||
return strings.Join(parts, " AND "), args
|
||||
}
|
||||
|
||||
// buildBaseFilter 将 RetrieveParams 中的过滤条件翻译为 whereBuilder。
|
||||
// 默认追加 is_enabled = TRUE,与 Qdrant/Milvus/Weaviate 保持一致:
|
||||
// 关闭的 chunk 不参与检索。
|
||||
func buildBaseFilter(params types.RetrieveParams) *whereBuilder {
|
||||
w := &whereBuilder{}
|
||||
w.addEqual(fieldIsEnabled, true)
|
||||
|
||||
if len(params.KnowledgeBaseIDs) > 0 {
|
||||
w.addIn(fieldKnowledgeBaseID, params.KnowledgeBaseIDs)
|
||||
}
|
||||
if len(params.KnowledgeIDs) > 0 {
|
||||
w.addIn(fieldKnowledgeID, params.KnowledgeIDs)
|
||||
}
|
||||
if len(params.TagIDs) > 0 {
|
||||
w.addIn(fieldTagID, params.TagIDs)
|
||||
}
|
||||
if len(params.ExcludeKnowledgeIDs) > 0 {
|
||||
w.addNotIn(fieldKnowledgeID, params.ExcludeKnowledgeIDs)
|
||||
}
|
||||
if len(params.ExcludeChunkIDs) > 0 {
|
||||
w.addNotIn(fieldChunkID, params.ExcludeChunkIDs)
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
// parseEmbeddingLiteral 解析 Doris ARRAY<FLOAT> 通过 MySQL 协议返回的
|
||||
// 字面量字符串(形如 "[1,2,3]")为 []float32。
|
||||
//
|
||||
// CopyIndices 路径需要从源行读出向量本身再写回目标行;此处的解析容错优先:
|
||||
// 不带 [] 也接受、空数组返回 nil。
|
||||
func parseEmbeddingLiteral(raw []byte) ([]float32, error) {
|
||||
s := strings.TrimSpace(string(raw))
|
||||
if s == "" {
|
||||
return nil, nil
|
||||
}
|
||||
s = strings.TrimPrefix(s, "[")
|
||||
s = strings.TrimSuffix(s, "]")
|
||||
if s == "" {
|
||||
return nil, nil
|
||||
}
|
||||
parts := strings.Split(s, ",")
|
||||
out := make([]float32, 0, len(parts))
|
||||
for _, p := range parts {
|
||||
p = strings.TrimSpace(p)
|
||||
if p == "" {
|
||||
continue
|
||||
}
|
||||
f, err := strconv.ParseFloat(p, 32)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, float32(f))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// validateEmbedding 校验向量元素均为有限值。
|
||||
//
|
||||
// strconv.FormatFloat 对 NaN/±Inf 会输出 "NaN"/"+Inf"/"-Inf",
|
||||
// 这些字面量会让 Doris 拼出来的 SQL 报语法错误(或在某些版本下产生未定义结果)。
|
||||
// 上游(嵌入模型)正常情况下不会输出非有限值,但 GPU OOM、上游 bug、
|
||||
// 测试桩都可能触发;这里 fail-fast 比悄悄写脏数据安全。
|
||||
func validateEmbedding(vec []float32) error {
|
||||
for i, v := range vec {
|
||||
if f := float64(v); math.IsNaN(f) || math.IsInf(f, 0) {
|
||||
return errInvalidEmbedding{index: i, value: v}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// normalizeEmbedding returns a unit-length copy of vec so Doris inner-product
|
||||
// ANN search can preserve cosine-style similarity semantics.
|
||||
func normalizeEmbedding(vec []float32) []float32 {
|
||||
if len(vec) == 0 {
|
||||
return nil
|
||||
}
|
||||
var sumSquares float64
|
||||
for _, value := range vec {
|
||||
f := float64(value)
|
||||
sumSquares += f * f
|
||||
}
|
||||
if sumSquares == 0 {
|
||||
return append([]float32(nil), vec...)
|
||||
}
|
||||
norm := float32(math.Sqrt(sumSquares))
|
||||
normalized := make([]float32, len(vec))
|
||||
for i, value := range vec {
|
||||
normalized[i] = value / norm
|
||||
}
|
||||
return normalized
|
||||
}
|
||||
|
||||
// errInvalidEmbedding 描述哪个下标含非有限值;用结构体而非 fmt.Errorf
|
||||
// 是为了让上层在日志里能拿到下标做问题定位。
|
||||
type errInvalidEmbedding struct {
|
||||
index int
|
||||
value float32
|
||||
}
|
||||
|
||||
func (e errInvalidEmbedding) Error() string {
|
||||
return "doris: embedding[" + strconv.Itoa(e.index) +
|
||||
"] is not finite: " + strconv.FormatFloat(float64(e.value), 'g', -1, 32)
|
||||
}
|
||||
|
||||
// embeddingLiteral 把 []float32 转为 Doris ARRAY<FLOAT> 字面量字符串:
|
||||
// "[1.23,4.56,...]"。
|
||||
//
|
||||
// 为何不用占位符:go-sql-driver/mysql 不支持 ARRAY 类型的参数绑定,
|
||||
// Doris 端也只接受字面量形式。这里用 strconv.FormatFloat('g' + bitSize=32)
|
||||
// 而不是 fmt.Sprintf("%f", v),原因有二:
|
||||
// 1. fmt 在某些 locale 下会用千分位分隔符,破坏 SQL 语法;
|
||||
// 2. 'g' 比 'f' 短且不会丢精度。
|
||||
//
|
||||
// 注入风险:[]float32 元素是嵌入模型输出的有限位数浮点数,序列化后只可能
|
||||
// 包含 [0-9eE+-.\s] 字符,不会逃逸出字面量上下文。
|
||||
func embeddingLiteral(vec []float32) string {
|
||||
if len(vec) == 0 {
|
||||
return "[]"
|
||||
}
|
||||
var sb strings.Builder
|
||||
sb.Grow(len(vec) * 12)
|
||||
sb.WriteByte('[')
|
||||
for i, v := range vec {
|
||||
if i > 0 {
|
||||
sb.WriteByte(',')
|
||||
}
|
||||
sb.WriteString(strconv.FormatFloat(float64(v), 'g', -1, 32))
|
||||
}
|
||||
sb.WriteByte(']')
|
||||
return sb.String()
|
||||
}
|
||||
@@ -0,0 +1,699 @@
|
||||
package doris
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"academy/internal/logger"
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultTableBaseName = "academy_embeddings"
|
||||
envDorisTablePrefix = "DORIS_TABLE_PREFIX"
|
||||
)
|
||||
|
||||
// NewDorisRetrieveEngineRepository 创建 Doris 检索引擎仓储。
|
||||
//
|
||||
// 参数:
|
||||
// - db:MySQL 协议的 *sql.DB 实例。调用方负责 SetMaxOpenConns 等参数。
|
||||
// - feHTTPBase:Stream Load 用的 FE HTTP 基地址(含 scheme),例如 "http://doris-fe:8030"。
|
||||
// - username/password:MySQL 与 Stream Load 共用的凭据。
|
||||
// - database:目标数据库名(既用于 MySQL DSN,也用于 Stream Load URL 路径)。
|
||||
// - indexCfg:可空。为 nil 时退化为环境变量 + 默认值(env 路径)。
|
||||
func NewDorisRetrieveEngineRepository(
|
||||
db *sql.DB,
|
||||
feHTTPBase, username, password, database string,
|
||||
indexCfg *types.IndexConfig,
|
||||
) interfaces.RetrieveEngineRepository {
|
||||
log := logger.GetLogger(context.Background())
|
||||
log.Info("[Doris] Initializing Doris retriever engine repository")
|
||||
|
||||
tableBaseName := types.ResolveCollectionName(indexCfg, envDorisTablePrefix, defaultTableBaseName)
|
||||
compatMode, invalidCompatMode := resolveConfiguredDorisCompatMode()
|
||||
if invalidCompatMode != "" {
|
||||
log.Warnf("[Doris] Invalid %s=%q, defaulting to %s", envDorisCompatMode, invalidCompatMode, dorisCompatModeAuto)
|
||||
}
|
||||
|
||||
repo := &dorisRepository{
|
||||
db: db,
|
||||
httpClient: newDorisStreamLoadHTTPClient(),
|
||||
feHTTPBase: strings.TrimRight(feHTTPBase, "/"),
|
||||
username: username,
|
||||
password: password,
|
||||
database: database,
|
||||
tableBaseName: tableBaseName,
|
||||
bucketsNum: indexCfg.GetBucketsNum(0),
|
||||
replicationNum: indexCfg.GetReplicationNum(0),
|
||||
compatModeRequested: compatMode,
|
||||
}
|
||||
log.Infof("[Doris] Repository initialized: db=%s, base=%s, fe_http=%s, compat_mode=%s",
|
||||
database, tableBaseName, repo.feHTTPBase, repo.compatModeRequested)
|
||||
if os.Getenv(envDorisCompatMode) == "" {
|
||||
log.Infof("[Doris] %s not set, defaulting to %s and probing on first use", envDorisCompatMode, dorisCompatModeAuto)
|
||||
}
|
||||
return repo
|
||||
}
|
||||
|
||||
func (r *dorisRepository) EngineType() types.RetrieverEngineType {
|
||||
return types.DorisRetrieverEngineType
|
||||
}
|
||||
|
||||
func (r *dorisRepository) Support() []types.RetrieverType {
|
||||
return []types.RetrieverType{types.KeywordsRetrieverType, types.VectorRetrieverType}
|
||||
}
|
||||
|
||||
// EstimateStorageSize 估算给定 IndexInfo 列表的存储字节数。
|
||||
//
|
||||
// 参考 Qdrant 的算法:payload 字段长度 + 向量字节 + HNSW 邻居 + 元数据。
|
||||
func (r *dorisRepository) EstimateStorageSize(_ context.Context,
|
||||
indexInfoList []*types.IndexInfo, params map[string]any,
|
||||
) int64 {
|
||||
var total int64
|
||||
for _, info := range indexInfoList {
|
||||
emb := toDorisVectorEmbedding(info, params, dorisCompatModeInnerProductDuplicate)
|
||||
total += calculateStorageSize(emb)
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
// Save 写入单条记录到对应维度的表。空向量在 BatchSave 内部统一拒绝。
|
||||
func (r *dorisRepository) Save(ctx context.Context,
|
||||
info *types.IndexInfo, additionalParams map[string]any,
|
||||
) error {
|
||||
return r.BatchSave(ctx, []*types.IndexInfo{info}, additionalParams)
|
||||
}
|
||||
|
||||
// BatchSave 把同一批 IndexInfo 按维度分组;Doris ANN 兼容表使用
|
||||
// DUPLICATE KEY,因此这里显式按 id 做 delete + insert,保持原先的替换语义。
|
||||
func (r *dorisRepository) BatchSave(ctx context.Context,
|
||||
indexInfoList []*types.IndexInfo, additionalParams map[string]any,
|
||||
) error {
|
||||
log := logger.GetLogger(ctx)
|
||||
if len(indexInfoList) == 0 {
|
||||
return nil
|
||||
}
|
||||
compatMode, err := r.resolveCompatMode(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
groups := make(map[int][]*DorisVectorEmbedding)
|
||||
for _, info := range indexInfoList {
|
||||
emb := toDorisVectorEmbedding(info, additionalParams, compatMode)
|
||||
if len(emb.Embedding) == 0 {
|
||||
log.Warnf("[Doris] Skipping empty embedding for chunk %s", info.ChunkID)
|
||||
continue
|
||||
}
|
||||
if err := validateEmbedding(emb.Embedding); err != nil {
|
||||
return fmt.Errorf("invalid embedding for chunk %s: %w", info.ChunkID, err)
|
||||
}
|
||||
// 给一个稳定的主键。SourceID 是上层最有意义的"行身份",
|
||||
// 但同 chunk 多 question 的场景下 SourceID 已经唯一,所以直接用它。
|
||||
if emb.ID == "" {
|
||||
emb.ID = emb.SourceID
|
||||
}
|
||||
if emb.ID == "" {
|
||||
emb.ID = uuid.New().String()
|
||||
}
|
||||
dim := len(emb.Embedding)
|
||||
groups[dim] = append(groups[dim], emb)
|
||||
}
|
||||
|
||||
for dim, rows := range groups {
|
||||
if err := r.ensureTable(ctx, dim); err != nil {
|
||||
return err
|
||||
}
|
||||
if compatMode.usesReplaceWrite() {
|
||||
err = r.replaceRows(ctx, r.getTableName(dim), rows)
|
||||
} else {
|
||||
err = r.insertRows(ctx, r.getTableName(dim), rows)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("batch save dim=%d: %w", dim, err)
|
||||
}
|
||||
log.Infof("[Doris] Saved %d rows to %s", len(rows), r.getTableName(dim))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// insertRows 按列序拼一条多 VALUES 的 INSERT。embedding 列由于
|
||||
// go-sql-driver/mysql 不支持 ARRAY 占位符,必须以字面量形式拼到 SQL 文本中。
|
||||
func (r *dorisRepository) insertRows(ctx context.Context,
|
||||
table string, rows []*DorisVectorEmbedding,
|
||||
) error {
|
||||
if len(rows) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 9 个普通占位符 + 1 个 embedding 字面量。
|
||||
const perRowPlaceholders = "(?, ?, ?, ?, ?, ?, ?, ?, ?, %s)"
|
||||
|
||||
parts := make([]string, len(rows))
|
||||
args := make([]any, 0, len(rows)*9)
|
||||
for i, e := range rows {
|
||||
parts[i] = fmt.Sprintf(perRowPlaceholders, embeddingLiteral(e.Embedding))
|
||||
args = append(args,
|
||||
e.ID, e.Content, e.SourceID, e.SourceType,
|
||||
e.ChunkID, e.KnowledgeID, e.KnowledgeBaseID, e.TagID,
|
||||
e.IsEnabled,
|
||||
)
|
||||
}
|
||||
|
||||
stmt := fmt.Sprintf("INSERT INTO `%s` (%s) VALUES %s",
|
||||
table,
|
||||
strings.Join(columns, ", "),
|
||||
strings.Join(parts, ", "),
|
||||
)
|
||||
_, err := r.db.ExecContext(ctx, stmt, args...)
|
||||
return err
|
||||
}
|
||||
|
||||
// replaceRows 在 DUPLICATE KEY 表上显式模拟“按 id 覆盖”的语义。
|
||||
func (r *dorisRepository) replaceRows(ctx context.Context,
|
||||
table string, rows []*DorisVectorEmbedding,
|
||||
) error {
|
||||
rows = dedupeRowsByID(rows)
|
||||
if len(rows) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
ids := make([]string, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
ids = append(ids, row.ID)
|
||||
}
|
||||
if err := r.deleteRowsByID(ctx, table, ids); err != nil {
|
||||
return err
|
||||
}
|
||||
return r.insertRows(ctx, table, rows)
|
||||
}
|
||||
|
||||
func (r *dorisRepository) deleteRowsByID(ctx context.Context,
|
||||
table string, ids []string,
|
||||
) error {
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
placeholders := make([]string, len(ids))
|
||||
args := make([]any, len(ids))
|
||||
for i, id := range ids {
|
||||
placeholders[i] = "?"
|
||||
args[i] = id
|
||||
}
|
||||
|
||||
stmt := fmt.Sprintf("DELETE FROM `%s` WHERE %s IN (%s)",
|
||||
table, fieldID, strings.Join(placeholders, ", "))
|
||||
_, err := r.db.ExecContext(ctx, stmt, args...)
|
||||
return err
|
||||
}
|
||||
|
||||
func dedupeRowsByID(rows []*DorisVectorEmbedding) []*DorisVectorEmbedding {
|
||||
if len(rows) < 2 {
|
||||
return rows
|
||||
}
|
||||
|
||||
out := make([]*DorisVectorEmbedding, 0, len(rows))
|
||||
positions := make(map[string]int, len(rows))
|
||||
for _, row := range rows {
|
||||
if idx, ok := positions[row.ID]; ok {
|
||||
out[idx] = row
|
||||
continue
|
||||
}
|
||||
positions[row.ID] = len(out)
|
||||
out = append(out, row)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// DeleteByChunkIDList 用 chunk_id 列删除。dimension 用于定位具体表。
|
||||
func (r *dorisRepository) DeleteByChunkIDList(ctx context.Context,
|
||||
chunkIDList []string, dimension int, _ string,
|
||||
) error {
|
||||
return r.deleteByField(ctx, fieldChunkID, chunkIDList, dimension)
|
||||
}
|
||||
|
||||
// DeleteByKnowledgeIDList 用 knowledge_id 列删除。
|
||||
func (r *dorisRepository) DeleteByKnowledgeIDList(ctx context.Context,
|
||||
knowledgeIDList []string, dimension int, _ string,
|
||||
) error {
|
||||
return r.deleteByField(ctx, fieldKnowledgeID, knowledgeIDList, dimension)
|
||||
}
|
||||
|
||||
// DeleteBySourceIDList 用 source_id 列删除。
|
||||
func (r *dorisRepository) DeleteBySourceIDList(ctx context.Context,
|
||||
sourceIDList []string, dimension int, _ string,
|
||||
) error {
|
||||
return r.deleteByField(ctx, fieldSourceID, sourceIDList, dimension)
|
||||
}
|
||||
|
||||
// deleteByField 是三个 Delete* 方法的统一实现:
|
||||
// DELETE FROM <table> WHERE <field> IN (?, ?, ...)。
|
||||
func (r *dorisRepository) deleteByField(ctx context.Context,
|
||||
field string, ids []string, dimension int,
|
||||
) error {
|
||||
log := logger.GetLogger(ctx)
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
table := r.getTableName(dimension)
|
||||
placeholders := make([]string, len(ids))
|
||||
args := make([]any, len(ids))
|
||||
for i, v := range ids {
|
||||
placeholders[i] = "?"
|
||||
args[i] = v
|
||||
}
|
||||
stmt := fmt.Sprintf("DELETE FROM `%s` WHERE %s IN (%s)",
|
||||
table, field, strings.Join(placeholders, ", "))
|
||||
|
||||
if _, err := r.db.ExecContext(ctx, stmt, args...); err != nil {
|
||||
log.Errorf("[Doris] Delete by %s failed: %v", field, err)
|
||||
return fmt.Errorf("delete by %s: %w", field, err)
|
||||
}
|
||||
log.Infof("[Doris] Deleted %d rows from %s by %s", len(ids), table, field)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Retrieve 根据 RetrieverType 分发到向量检索或关键词检索。
|
||||
func (r *dorisRepository) Retrieve(ctx context.Context,
|
||||
params types.RetrieveParams,
|
||||
) ([]*types.RetrieveResult, error) {
|
||||
switch params.RetrieverType {
|
||||
case types.VectorRetrieverType:
|
||||
return r.VectorRetrieve(ctx, params)
|
||||
case types.KeywordsRetrieverType:
|
||||
return r.KeywordsRetrieve(ctx, params)
|
||||
}
|
||||
return nil, fmt.Errorf("invalid retriever type: %v", params.RetrieverType)
|
||||
}
|
||||
|
||||
// VectorRetrieve 对查询向量先做单位化,再调用 inner_product_approximate 做
|
||||
// ANN 搜索;对单位向量而言,inner product 与 cosine similarity 等价,
|
||||
// 因此 score 仍然保持“越大越相似”的语义。
|
||||
func (r *dorisRepository) VectorRetrieve(ctx context.Context,
|
||||
params types.RetrieveParams,
|
||||
) ([]*types.RetrieveResult, error) {
|
||||
log := logger.GetLogger(ctx)
|
||||
if err := validateEmbedding(params.Embedding); err != nil {
|
||||
return nil, fmt.Errorf("invalid query embedding: %w", err)
|
||||
}
|
||||
compatMode, err := r.resolveCompatMode(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
queryEmbedding := append([]float32(nil), params.Embedding...)
|
||||
if compatMode.normalizeEmbeddings() {
|
||||
queryEmbedding = normalizeEmbedding(queryEmbedding)
|
||||
}
|
||||
dim := len(params.Embedding)
|
||||
table := r.getTableName(dim)
|
||||
|
||||
exists, err := r.tableExists(ctx, table)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("check table %s: %w", table, err)
|
||||
}
|
||||
if !exists {
|
||||
log.Warnf("[Doris] Table %s does not exist, returning empty results", table)
|
||||
return buildRetrieveResult(nil, types.VectorRetrieverType), nil
|
||||
}
|
||||
|
||||
wb := buildBaseFilter(params)
|
||||
whereClause, whereArgs := wb.build()
|
||||
|
||||
// embedding 必须用字面量,Doris 不支持 LIMIT/OFFSET 使用占位符,必须内联为字面量。
|
||||
// 使用 HAVING 是因为 score 是 SELECT 列别名,WHERE 阶段还看不到。
|
||||
scoreExpr := fmt.Sprintf("inner_product_approximate(`%s`, %s)", fieldEmbedding, embeddingLiteral(queryEmbedding))
|
||||
if compatMode == dorisCompatModeLegacy {
|
||||
scoreExpr = fmt.Sprintf("(1 - cosine_distance_approximate(`%s`, %s))", fieldEmbedding, embeddingLiteral(queryEmbedding))
|
||||
}
|
||||
stmt := fmt.Sprintf(
|
||||
"SELECT %s, %s AS score "+
|
||||
"FROM `%s` WHERE %s "+
|
||||
"HAVING score >= ? "+
|
||||
"ORDER BY score DESC LIMIT %d",
|
||||
strings.Join(columnsForRetrieve, ", "),
|
||||
scoreExpr,
|
||||
table,
|
||||
whereClause,
|
||||
params.TopK,
|
||||
)
|
||||
args := append(whereArgs, params.Threshold)
|
||||
|
||||
rows, err := r.db.QueryContext(ctx, stmt, args...)
|
||||
if err != nil {
|
||||
return nil, r.wrapVectorRetrieveError(table, compatMode, err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
results, err := scanRetrieveRows(rows, types.MatchTypeEmbedding)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
log.Infof("[Doris] Vector retrieval found %d results in %s", len(results), table)
|
||||
return buildRetrieveResult(results, types.VectorRetrieverType), nil
|
||||
}
|
||||
|
||||
// KeywordsRetrieve 用 Doris 倒排索引 + MATCH_ANY 做关键词匹配。
|
||||
//
|
||||
// 不需要 jieba 客户端分词:CREATE TABLE 时 idx_content 已经声明了 chinese parser。
|
||||
// 不同维度的表跨表合并取 topK,与 Milvus/Weaviate 现状一致。
|
||||
func (r *dorisRepository) KeywordsRetrieve(ctx context.Context,
|
||||
params types.RetrieveParams,
|
||||
) ([]*types.RetrieveResult, error) {
|
||||
log := logger.GetLogger(ctx)
|
||||
query := strings.TrimSpace(params.Query)
|
||||
if query == "" {
|
||||
return buildRetrieveResult(nil, types.KeywordsRetrieverType), nil
|
||||
}
|
||||
|
||||
tables, err := r.listEmbeddingTables(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list tables: %w", err)
|
||||
}
|
||||
if len(tables) == 0 {
|
||||
return buildRetrieveResult(nil, types.KeywordsRetrieverType), nil
|
||||
}
|
||||
|
||||
wb := buildBaseFilter(params)
|
||||
whereClause, whereArgs := wb.build()
|
||||
|
||||
var all []*types.IndexWithScore
|
||||
for _, table := range tables {
|
||||
stmt := fmt.Sprintf(
|
||||
"SELECT %s FROM `%s` WHERE %s AND %s MATCH_ANY ? LIMIT %d",
|
||||
strings.Join(columnsForRetrieve, ", "),
|
||||
table, whereClause, fieldContent,
|
||||
params.TopK,
|
||||
)
|
||||
args := append(append([]any{}, whereArgs...), query)
|
||||
|
||||
rows, err := r.db.QueryContext(ctx, stmt, args...)
|
||||
if err != nil {
|
||||
log.Warnf("[Doris] Keyword retrieve in %s failed: %v", table, err)
|
||||
continue
|
||||
}
|
||||
// score 在 KeywordsRetrieve 中固定 1.0,与 Qdrant 行为一致。
|
||||
batch, scanErr := scanRetrieveRows(rows, types.MatchTypeKeywords)
|
||||
_ = rows.Close()
|
||||
if scanErr != nil {
|
||||
return nil, scanErr
|
||||
}
|
||||
all = append(all, batch...)
|
||||
}
|
||||
if len(all) > params.TopK {
|
||||
all = all[:params.TopK]
|
||||
}
|
||||
log.Infof("[Doris] Keywords retrieval found %d results across %d tables", len(all), len(tables))
|
||||
return buildRetrieveResult(all, types.KeywordsRetrieverType), nil
|
||||
}
|
||||
|
||||
// CopyIndices 把源知识库的 chunk 复制到目标知识库,避免重新生成 embedding。
|
||||
//
|
||||
// 与 Qdrant 的实现完全镜像:
|
||||
// - 分页扫描源表
|
||||
// - 按 sourceToTargetChunkIDMap 把 chunk_id 翻译过去
|
||||
// - 处理 source_id 翻译规则(普通 chunk / 生成型问题 / 其他)
|
||||
// - 把目标行写回同一个表
|
||||
func (r *dorisRepository) CopyIndices(ctx context.Context,
|
||||
sourceKnowledgeBaseID string,
|
||||
sourceToTargetKBIDMap map[string]string,
|
||||
sourceToTargetChunkIDMap map[string]string,
|
||||
targetKnowledgeBaseID string,
|
||||
dimension int,
|
||||
_ string,
|
||||
) error {
|
||||
log := logger.GetLogger(ctx)
|
||||
if len(sourceToTargetChunkIDMap) == 0 {
|
||||
return nil
|
||||
}
|
||||
if err := r.ensureTable(ctx, dimension); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
table := r.getTableName(dimension)
|
||||
const pageSize = 64
|
||||
offset := 0
|
||||
totalCopied := 0
|
||||
|
||||
for {
|
||||
stmt := fmt.Sprintf(
|
||||
"SELECT %s FROM `%s` WHERE %s = ? ORDER BY %s LIMIT %d OFFSET %d",
|
||||
strings.Join(columnsForCopy, ", "),
|
||||
table, fieldKnowledgeBaseID, fieldID,
|
||||
pageSize, offset,
|
||||
)
|
||||
rows, err := r.db.QueryContext(ctx, stmt, sourceKnowledgeBaseID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("copy indices scan: %w", err)
|
||||
}
|
||||
batch, err := scanCopyRows(rows)
|
||||
_ = rows.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(batch) == 0 {
|
||||
break
|
||||
}
|
||||
|
||||
var targets []*DorisVectorEmbedding
|
||||
for _, src := range batch {
|
||||
targetChunkID, ok := sourceToTargetChunkIDMap[src.ChunkID]
|
||||
if !ok {
|
||||
log.Warnf("[Doris] Source chunk %s not in target mapping", src.ChunkID)
|
||||
continue
|
||||
}
|
||||
targetKnowledgeID, ok := sourceToTargetKBIDMap[src.KnowledgeID]
|
||||
if !ok {
|
||||
log.Warnf("[Doris] Source knowledge %s not in target mapping", src.KnowledgeID)
|
||||
continue
|
||||
}
|
||||
|
||||
targetSourceID := translateSourceID(src.SourceID, src.ChunkID, targetChunkID)
|
||||
targets = append(targets, &DorisVectorEmbedding{
|
||||
ID: uuid.New().String(),
|
||||
Content: src.Content,
|
||||
SourceID: targetSourceID,
|
||||
SourceType: src.SourceType,
|
||||
ChunkID: targetChunkID,
|
||||
KnowledgeID: targetKnowledgeID,
|
||||
KnowledgeBaseID: targetKnowledgeBaseID,
|
||||
TagID: src.TagID,
|
||||
IsEnabled: src.IsEnabled,
|
||||
Embedding: src.Embedding,
|
||||
})
|
||||
}
|
||||
|
||||
if len(targets) > 0 {
|
||||
if err := r.insertRows(ctx, table, targets); err != nil {
|
||||
return fmt.Errorf("copy indices insert: %w", err)
|
||||
}
|
||||
totalCopied += len(targets)
|
||||
}
|
||||
|
||||
if len(batch) < pageSize {
|
||||
break
|
||||
}
|
||||
offset += pageSize
|
||||
}
|
||||
log.Infof("[Doris] CopyIndices done, dim=%d, copied=%d", dimension, totalCopied)
|
||||
return nil
|
||||
}
|
||||
|
||||
// BatchUpdateChunkEnabledStatus / BatchUpdateChunkTagID 实际实现位于 streamload.go,
|
||||
// 会按 compat mode 选择 partial update 或 rewrite rows。
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 私有辅助
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// toDorisVectorEmbedding 把 IndexInfo + 上层传入的 embedding 映射 转换为
|
||||
// Doris 行模型。Embedding 通过 additionalParams[fieldEmbedding] 中的
|
||||
// map[string][]float32 按 SourceID 取出,与 Qdrant/Milvus 完全一致。
|
||||
// inner_product_duplicate 模式会先单位化,legacy 模式保留原始向量。
|
||||
func toDorisVectorEmbedding(
|
||||
info *types.IndexInfo,
|
||||
additionalParams map[string]any,
|
||||
compatMode dorisCompatMode,
|
||||
) *DorisVectorEmbedding {
|
||||
emb := &DorisVectorEmbedding{
|
||||
ID: info.ID,
|
||||
Content: info.Content,
|
||||
SourceID: info.SourceID,
|
||||
SourceType: int(info.SourceType),
|
||||
ChunkID: info.ChunkID,
|
||||
KnowledgeID: info.KnowledgeID,
|
||||
KnowledgeBaseID: info.KnowledgeBaseID,
|
||||
TagID: info.TagID,
|
||||
IsEnabled: info.IsEnabled,
|
||||
}
|
||||
if additionalParams != nil {
|
||||
if v, ok := additionalParams[fieldEmbedding]; ok {
|
||||
if m, ok := v.(map[string][]float32); ok {
|
||||
emb.Embedding = append([]float32(nil), m[info.SourceID]...)
|
||||
if compatMode.normalizeEmbeddings() {
|
||||
emb.Embedding = normalizeEmbedding(emb.Embedding)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return emb
|
||||
}
|
||||
|
||||
func (r *dorisRepository) wrapVectorRetrieveError(table string, compatMode dorisCompatMode, err error) error {
|
||||
if compatMode == dorisCompatModeLegacy {
|
||||
return fmt.Errorf(
|
||||
"vector retrieve %s in Doris compat mode %s: %w. If your Doris build does not support cosine_distance_approximate or ANN on UNIQUE KEY tables, set %s=%s before creating embedding tables. %s is not interchangeable after %s_* tables are created",
|
||||
table,
|
||||
compatMode,
|
||||
err,
|
||||
envDorisCompatMode,
|
||||
dorisCompatModeInnerProductDuplicate,
|
||||
envDorisCompatMode,
|
||||
r.tableBaseName,
|
||||
)
|
||||
}
|
||||
return fmt.Errorf("vector retrieve %s in Doris compat mode %s: %w", table, compatMode, err)
|
||||
}
|
||||
|
||||
// translateSourceID 把源 SourceID 翻译到目标 SourceID,与 Qdrant 实现完全镜像:
|
||||
// - 普通 chunk:SourceID == ChunkID -> 使用 targetChunkID
|
||||
// - 生成型问题:SourceID == "<chunkID>-<questionID>" -> "<targetChunkID>-<questionID>"
|
||||
// - 其他场景:生成新的 UUID(保持唯一性)
|
||||
func translateSourceID(originalSourceID, sourceChunkID, targetChunkID string) string {
|
||||
switch {
|
||||
case originalSourceID == sourceChunkID:
|
||||
return targetChunkID
|
||||
case strings.HasPrefix(originalSourceID, sourceChunkID+"-"):
|
||||
questionID := strings.TrimPrefix(originalSourceID, sourceChunkID+"-")
|
||||
return fmt.Sprintf("%s-%s", targetChunkID, questionID)
|
||||
default:
|
||||
return uuid.New().String()
|
||||
}
|
||||
}
|
||||
|
||||
// scanRetrieveRows 把 Retrieve 阶段的 rows 反序列化为 IndexWithScore 列表。
|
||||
//
|
||||
// 分两路:
|
||||
// - 列数 == columnsForRetrieve+1:第 N+1 列是 score(向量检索路径)
|
||||
// - 列数 == columnsForRetrieve:score 统一赋 1.0(关键词检索路径)
|
||||
func scanRetrieveRows(rows *sql.Rows, matchType types.MatchType) ([]*types.IndexWithScore, error) {
|
||||
cols, err := rows.Columns()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
withScore := len(cols) == len(columnsForRetrieve)+1
|
||||
|
||||
var out []*types.IndexWithScore
|
||||
for rows.Next() {
|
||||
var (
|
||||
id, content, sourceID, chunkID string
|
||||
knowledgeID, knowledgeBaseID, tagID string
|
||||
sourceType int
|
||||
isEnabled bool
|
||||
score float64
|
||||
err error
|
||||
)
|
||||
if withScore {
|
||||
err = rows.Scan(&id, &content, &sourceID, &sourceType,
|
||||
&chunkID, &knowledgeID, &knowledgeBaseID, &tagID, &isEnabled, &score)
|
||||
} else {
|
||||
err = rows.Scan(&id, &content, &sourceID, &sourceType,
|
||||
&chunkID, &knowledgeID, &knowledgeBaseID, &tagID, &isEnabled)
|
||||
score = 1.0
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("scan row: %w", err)
|
||||
}
|
||||
out = append(out, &types.IndexWithScore{
|
||||
ID: id,
|
||||
Content: content,
|
||||
SourceID: sourceID,
|
||||
SourceType: types.SourceType(sourceType),
|
||||
ChunkID: chunkID,
|
||||
KnowledgeID: knowledgeID,
|
||||
KnowledgeBaseID: knowledgeBaseID,
|
||||
TagID: tagID,
|
||||
Score: score,
|
||||
MatchType: matchType,
|
||||
})
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// scanCopyRows 反序列化 CopyIndices 的分页查询结果。
|
||||
//
|
||||
// 与 scanRetrieveRows 不同,这里需要 embedding 字段(去复制原始向量)。
|
||||
// Doris 的 ARRAY<FLOAT> 通过 mysql 协议返回的是字符串字面量 "[1,2,3]"。
|
||||
func scanCopyRows(rows *sql.Rows) ([]*DorisVectorEmbedding, error) {
|
||||
var out []*DorisVectorEmbedding
|
||||
for rows.Next() {
|
||||
var (
|
||||
id, content, sourceID, chunkID string
|
||||
knowledgeID, knowledgeBaseID, tagID string
|
||||
sourceType int
|
||||
isEnabled bool
|
||||
embeddingRaw sql.RawBytes
|
||||
)
|
||||
if err := rows.Scan(&id, &content, &sourceID, &sourceType,
|
||||
&chunkID, &knowledgeID, &knowledgeBaseID, &tagID, &isEnabled, &embeddingRaw); err != nil {
|
||||
return nil, fmt.Errorf("scan copy row: %w", err)
|
||||
}
|
||||
vec, err := parseEmbeddingLiteral(embeddingRaw)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse embedding: %w", err)
|
||||
}
|
||||
out = append(out, &DorisVectorEmbedding{
|
||||
ID: id,
|
||||
Content: content,
|
||||
SourceID: sourceID,
|
||||
SourceType: sourceType,
|
||||
ChunkID: chunkID,
|
||||
KnowledgeID: knowledgeID,
|
||||
KnowledgeBaseID: knowledgeBaseID,
|
||||
TagID: tagID,
|
||||
IsEnabled: isEnabled,
|
||||
Embedding: vec,
|
||||
})
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// buildRetrieveResult 把 IndexWithScore 列表包装成 RetrieveResult。
|
||||
func buildRetrieveResult(results []*types.IndexWithScore, retrieverType types.RetrieverType) []*types.RetrieveResult {
|
||||
return []*types.RetrieveResult{{
|
||||
Results: results,
|
||||
RetrieverEngineType: types.DorisRetrieverEngineType,
|
||||
RetrieverType: retrieverType,
|
||||
Error: nil,
|
||||
}}
|
||||
}
|
||||
|
||||
// calculateStorageSize 估算单行的存储成本。
|
||||
//
|
||||
// 与 Qdrant 一致:payload 字符串字节 + 向量 (dim*4) + HNSW M*2*8 + 元数据 24。
|
||||
func calculateStorageSize(emb *DorisVectorEmbedding) int64 {
|
||||
var payload int64
|
||||
payload += int64(len(emb.Content))
|
||||
payload += int64(len(emb.SourceID))
|
||||
payload += int64(len(emb.ChunkID))
|
||||
payload += int64(len(emb.KnowledgeID))
|
||||
payload += int64(len(emb.KnowledgeBaseID))
|
||||
payload += int64(len(emb.TagID))
|
||||
payload += 8 // source_type int
|
||||
|
||||
var vec int64
|
||||
var hnsw int64
|
||||
if len(emb.Embedding) > 0 {
|
||||
vec = int64(len(emb.Embedding)) * 4
|
||||
const hnswM = 32
|
||||
hnsw = hnswM * 2 * 8
|
||||
}
|
||||
const metaBytes int64 = 24
|
||||
return payload + vec + hnsw + metaBytes
|
||||
}
|
||||
@@ -0,0 +1,807 @@
|
||||
package doris
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
"academy/internal/types"
|
||||
secutils "academy/internal/utils"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// newTestRepo 构造一个共享 sqlmock 的 dorisRepository,
|
||||
// 默认绕过 ensureTable(initializedTables 已置位),便于专注测试 SQL 形态。
|
||||
//
|
||||
// 返回的 cleanup 用 defer 调用即可。
|
||||
func newTestRepo(t *testing.T) (*dorisRepository, sqlmock.Sqlmock, *httptest.Server, func()) {
|
||||
t.Helper()
|
||||
// httptest binds to loopback, which production SSRF policy correctly blocks.
|
||||
// Make that one test host explicit and restore the process-global policy when
|
||||
// the test completes.
|
||||
secutils.SetSSRFWhitelistFromRaw("127.0.0.1")
|
||||
t.Cleanup(secutils.ResetSSRFWhitelistForTest)
|
||||
|
||||
db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherRegexp))
|
||||
require.NoError(t, err)
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// 默认行为:成功,回 1 行。
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
_ = body
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"Status": "Success",
|
||||
"NumberTotalRows": 1,
|
||||
"NumberLoadedRows": 1,
|
||||
"Label": "test",
|
||||
})
|
||||
}))
|
||||
|
||||
repo := &dorisRepository{
|
||||
db: db,
|
||||
httpClient: srv.Client(),
|
||||
feHTTPBase: srv.URL,
|
||||
username: "u",
|
||||
password: "p",
|
||||
database: "academy",
|
||||
tableBaseName: "academy_embeddings",
|
||||
}
|
||||
|
||||
cleanup := func() {
|
||||
_ = db.Close()
|
||||
srv.Close()
|
||||
}
|
||||
return repo, mock, srv, cleanup
|
||||
}
|
||||
|
||||
func primeCompatMode(repo *dorisRepository, mode dorisCompatMode, err error) {
|
||||
repo.compatModeResolved = mode
|
||||
repo.compatResolveErr = err
|
||||
repo.compatResolveOnce.Do(func() {})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// query.go:whereBuilder / embeddingLiteral / parseEmbeddingLiteral
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestEmbeddingLiteralRoundTrip(t *testing.T) {
|
||||
t.Run("empty vector returns []", func(t *testing.T) {
|
||||
assert.Equal(t, "[]", embeddingLiteral(nil))
|
||||
assert.Equal(t, "[]", embeddingLiteral([]float32{}))
|
||||
})
|
||||
|
||||
t.Run("does not contain locale-sensitive separators", func(t *testing.T) {
|
||||
s := embeddingLiteral([]float32{1.5, -2.25, 0.001})
|
||||
// 必须只包含数字 / 点 / 负号 / e / 逗号 / 方括号
|
||||
assert.Regexp(t, regexp.MustCompile(`^\[[\-+0-9eE.,]+\]$`), s)
|
||||
})
|
||||
|
||||
t.Run("round trip", func(t *testing.T) {
|
||||
orig := []float32{1.5, -2.25, 0.0625}
|
||||
s := embeddingLiteral(orig)
|
||||
got, err := parseEmbeddingLiteral([]byte(s))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, orig, got)
|
||||
})
|
||||
|
||||
t.Run("parse handles whitespace and missing brackets", func(t *testing.T) {
|
||||
v, err := parseEmbeddingLiteral([]byte(" 1.0 , 2.0 ,3.0 "))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []float32{1.0, 2.0, 3.0}, v)
|
||||
})
|
||||
}
|
||||
|
||||
func TestWhereBuilder(t *testing.T) {
|
||||
t.Run("empty builder returns 1 = 1", func(t *testing.T) {
|
||||
w := &whereBuilder{}
|
||||
clause, args := w.build()
|
||||
assert.Equal(t, "1 = 1", clause)
|
||||
assert.Nil(t, args)
|
||||
})
|
||||
|
||||
t.Run("equal + IN + NOT IN", func(t *testing.T) {
|
||||
w := &whereBuilder{}
|
||||
w.addEqual("is_enabled", true)
|
||||
w.addIn("knowledge_base_id", []string{"kb1", "kb2"})
|
||||
w.addNotIn("chunk_id", []string{"x"})
|
||||
clause, args := w.build()
|
||||
assert.Contains(t, clause, "is_enabled = ?")
|
||||
assert.Contains(t, clause, "knowledge_base_id IN (?, ?)")
|
||||
assert.Contains(t, clause, "chunk_id NOT IN (?)")
|
||||
assert.Equal(t, []any{true, "kb1", "kb2", "x"}, args)
|
||||
})
|
||||
|
||||
t.Run("buildBaseFilter applies all params", func(t *testing.T) {
|
||||
w := buildBaseFilter(types.RetrieveParams{
|
||||
KnowledgeBaseIDs: []string{"kb1"},
|
||||
KnowledgeIDs: []string{"k1", "k2"},
|
||||
TagIDs: []string{"t1"},
|
||||
ExcludeKnowledgeIDs: []string{"k9"},
|
||||
ExcludeChunkIDs: []string{"c9"},
|
||||
})
|
||||
clause, _ := w.build()
|
||||
assert.Contains(t, clause, "is_enabled = ?")
|
||||
assert.Contains(t, clause, "knowledge_base_id IN (?)")
|
||||
assert.Contains(t, clause, "knowledge_id IN (?, ?)")
|
||||
assert.Contains(t, clause, "tag_id IN (?)")
|
||||
assert.Contains(t, clause, "knowledge_id NOT IN (?)")
|
||||
assert.Contains(t, clause, "chunk_id NOT IN (?)")
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// streamload.go:chunkRows / partialUpdateRows
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestChunkRows(t *testing.T) {
|
||||
rows := []map[string]any{
|
||||
{"id": "a", "is_enabled": true},
|
||||
{"id": "b", "is_enabled": false},
|
||||
{"id": "c", "is_enabled": true},
|
||||
}
|
||||
|
||||
t.Run("single batch when fits", func(t *testing.T) {
|
||||
batches := chunkRows(rows, 4096)
|
||||
require.Len(t, batches, 1)
|
||||
assert.Len(t, batches[0], 3)
|
||||
})
|
||||
|
||||
t.Run("splits when exceeding maxBytes", func(t *testing.T) {
|
||||
// 给一个非常小的上限,强制每行单独成段
|
||||
batches := chunkRows(rows, 16)
|
||||
assert.GreaterOrEqual(t, len(batches), 2)
|
||||
|
||||
var total int
|
||||
for _, b := range batches {
|
||||
total += len(b)
|
||||
}
|
||||
assert.Equal(t, len(rows), total)
|
||||
})
|
||||
}
|
||||
|
||||
func TestPartialUpdateRows_HappyPath(t *testing.T) {
|
||||
repo, _, _, cleanup := newTestRepo(t)
|
||||
defer cleanup()
|
||||
|
||||
// 自定义 server 验证请求形态。
|
||||
var captured *http.Request
|
||||
var capturedBody []byte
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
captured = r
|
||||
capturedBody, _ = io.ReadAll(r.Body)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"Status": "Success",
|
||||
"NumberTotalRows": 2,
|
||||
"NumberLoadedRows": 2,
|
||||
"Label": "ok",
|
||||
})
|
||||
}))
|
||||
defer srv.Close()
|
||||
repo.feHTTPBase = srv.URL
|
||||
|
||||
rows := []map[string]any{
|
||||
{"id": "id1", "is_enabled": true},
|
||||
{"id": "id2", "is_enabled": false},
|
||||
}
|
||||
require.NoError(t, repo.partialUpdateRows(context.Background(),
|
||||
"academy_embeddings_768", []string{"id", "is_enabled"}, rows))
|
||||
|
||||
require.NotNil(t, captured)
|
||||
assert.Equal(t, http.MethodPut, captured.Method)
|
||||
assert.Equal(t, "/api/academy/academy_embeddings_768/_stream_load", captured.URL.Path)
|
||||
|
||||
assert.Equal(t, "true", captured.Header.Get("partial_columns"))
|
||||
assert.Equal(t, "true", captured.Header.Get("strip_outer_array"))
|
||||
assert.Equal(t, "json", captured.Header.Get("format"))
|
||||
assert.Equal(t, "id,is_enabled", captured.Header.Get("columns"))
|
||||
assert.Equal(t, "APPEND", captured.Header.Get("merge_type"))
|
||||
assert.True(t, strings.HasPrefix(captured.Header.Get("Authorization"), "Basic "))
|
||||
|
||||
var got []map[string]any
|
||||
require.NoError(t, json.Unmarshal(capturedBody, &got))
|
||||
assert.Len(t, got, 2)
|
||||
assert.Equal(t, "id1", got[0]["id"])
|
||||
}
|
||||
|
||||
func TestPartialUpdateRows_FailureSurfaced(t *testing.T) {
|
||||
repo, _, _, cleanup := newTestRepo(t)
|
||||
defer cleanup()
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"Status": "Fail",
|
||||
"Message": "label exists",
|
||||
"ErrorURL": "http://...",
|
||||
})
|
||||
}))
|
||||
defer srv.Close()
|
||||
repo.feHTTPBase = srv.URL
|
||||
|
||||
err := repo.partialUpdateRows(context.Background(),
|
||||
"t", []string{"id", "is_enabled"},
|
||||
[]map[string]any{{"id": "x", "is_enabled": true}},
|
||||
)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "stream load failed")
|
||||
}
|
||||
|
||||
func TestStreamLoadOnce_BlocksUnsafeTarget(t *testing.T) {
|
||||
repo, _, _, cleanup := newTestRepo(t)
|
||||
defer cleanup()
|
||||
|
||||
// Override the helper's loopback allowance: link-local metadata endpoints
|
||||
// must be rejected before the HTTP client is called.
|
||||
secutils.SetSSRFWhitelistFromRaw("")
|
||||
repo.feHTTPBase = "http://169.254.169.254"
|
||||
|
||||
err := repo.streamLoadOnce(context.Background(), "t", []string{"id"},
|
||||
[]map[string]any{{"id": "x"}})
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "blocked by SSRF validation")
|
||||
}
|
||||
|
||||
func TestDorisStreamLoadHTTPClient_BlocksUnsafeRedirect(t *testing.T) {
|
||||
secutils.SetSSRFWhitelistFromRaw("127.0.0.1")
|
||||
t.Cleanup(secutils.ResetSSRFWhitelistForTest)
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, "http://169.254.169.254/latest/meta-data", http.StatusTemporaryRedirect)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
req, err := http.NewRequest(http.MethodPut, server.URL, strings.NewReader("[]"))
|
||||
require.NoError(t, err)
|
||||
_, err = newDorisStreamLoadHTTPClient().Do(req)
|
||||
require.Error(t, err)
|
||||
assert.ErrorIs(t, err, secutils.ErrSSRFRedirectBlocked)
|
||||
}
|
||||
|
||||
func TestDorisStreamLoadHTTPClient_ForwardsAuthorizationToTrustedRedirect(t *testing.T) {
|
||||
secutils.SetSSRFWhitelistFromRaw("127.0.0.1")
|
||||
t.Cleanup(secutils.ResetSSRFWhitelistForTest)
|
||||
|
||||
var gotAuthorization, gotBody, gotColumns, gotMethod string
|
||||
be := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotAuthorization = r.Header.Get(headerAuthorization)
|
||||
gotColumns = r.Header.Get("columns")
|
||||
gotMethod = r.Method
|
||||
body, err := io.ReadAll(r.Body)
|
||||
assert.NoError(t, err)
|
||||
gotBody = string(body)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer be.Close()
|
||||
|
||||
fe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, be.URL, http.StatusTemporaryRedirect)
|
||||
}))
|
||||
defer fe.Close()
|
||||
|
||||
req, err := http.NewRequest(http.MethodPut, fe.URL, strings.NewReader("[]"))
|
||||
require.NoError(t, err)
|
||||
req.Header.Set(headerAuthorization, "Basic trusted-doris-credential")
|
||||
req.Header.Set("columns", "id,content")
|
||||
|
||||
resp, err := newDorisStreamLoadHTTPClient().Do(req)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
assert.Equal(t, "Basic trusted-doris-credential", gotAuthorization)
|
||||
assert.Equal(t, "[]", gotBody)
|
||||
assert.Equal(t, "id,content", gotColumns)
|
||||
assert.Equal(t, http.MethodPut, gotMethod)
|
||||
}
|
||||
|
||||
func TestDorisStreamLoadHTTPClient_RedirectBoundaries(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, source, target, whitelist string
|
||||
}{
|
||||
{"untrusted port", "https://8.8.8.8:8030/load", "https://8.8.8.8:8040/load", ""},
|
||||
{"untrusted host", "https://8.8.8.8/load", "https://1.1.1.1/load", ""},
|
||||
{"HTTPS downgrade", "https://127.0.0.1:8030/load", "http://127.0.0.1:8040/load", "127.0.0.1"},
|
||||
{"invalid scheme", "http://127.0.0.1/load", "ftp://127.0.0.1/load", "127.0.0.1"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
secutils.SetSSRFWhitelistFromRaw(tc.whitelist)
|
||||
t.Cleanup(secutils.ResetSSRFWhitelistForTest)
|
||||
source, err := http.NewRequest(http.MethodPut, tc.source, strings.NewReader("[]"))
|
||||
require.NoError(t, err)
|
||||
source.Header.Set(headerAuthorization, "Basic trusted-doris-credential")
|
||||
target, err := http.NewRequest(http.MethodPut, tc.target, strings.NewReader("[]"))
|
||||
require.NoError(t, err)
|
||||
err = newDorisStreamLoadHTTPClient().CheckRedirect(target, []*http.Request{source})
|
||||
require.ErrorIs(t, err, secutils.ErrSSRFRedirectBlocked)
|
||||
assert.Empty(t, target.Header.Get(headerAuthorization))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDorisStreamLoadHTTPClient_RedirectLimit(t *testing.T) {
|
||||
secutils.SetSSRFWhitelistFromRaw("127.0.0.1")
|
||||
t.Cleanup(secutils.ResetSSRFWhitelistForTest)
|
||||
req, err := http.NewRequest(http.MethodPut, "http://127.0.0.1/load", strings.NewReader("[]"))
|
||||
require.NoError(t, err)
|
||||
via := make([]*http.Request, secutils.DefaultSSRFSafeHTTPClientConfig().MaxRedirects)
|
||||
for i := range via {
|
||||
via[i] = req
|
||||
}
|
||||
require.ErrorContains(t, newDorisStreamLoadHTTPClient().CheckRedirect(req, via), "stopped after")
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// repository.go:SQL 形态
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestDeleteByChunkIDList_SQLShape(t *testing.T) {
|
||||
repo, mock, _, cleanup := newTestRepo(t)
|
||||
defer cleanup()
|
||||
|
||||
mock.ExpectExec(`DELETE FROM .*academy_embeddings_768.* WHERE chunk_id IN \(\?, \?\)`).
|
||||
WithArgs("c1", "c2").
|
||||
WillReturnResult(sqlmock.NewResult(0, 2))
|
||||
|
||||
err := repo.DeleteByChunkIDList(context.Background(), []string{"c1", "c2"}, 768, "")
|
||||
require.NoError(t, err)
|
||||
assert.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDeleteByKnowledgeIDList_NoOpOnEmpty(t *testing.T) {
|
||||
repo, mock, _, cleanup := newTestRepo(t)
|
||||
defer cleanup()
|
||||
|
||||
require.NoError(t, repo.DeleteByKnowledgeIDList(context.Background(), nil, 768, ""))
|
||||
// 空列表不应触发任何 query
|
||||
assert.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestVectorRetrieve_SQLShape(t *testing.T) {
|
||||
repo, mock, _, cleanup := newTestRepo(t)
|
||||
defer cleanup()
|
||||
|
||||
mock.ExpectQuery(`SELECT COUNT\(1\) FROM information_schema.tables`).
|
||||
WithArgs("academy", "academy_embeddings_3").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"c"}).AddRow(1))
|
||||
|
||||
// Doris does not support placeholders for LIMIT, so TopK is inlined as a
|
||||
// literal and is not a bound argument.
|
||||
mock.ExpectQuery(`SELECT id, content, .*inner_product_approximate.*HAVING score >= \? ORDER BY score DESC LIMIT \d+`).
|
||||
WithArgs(true, 0.5).
|
||||
WillReturnRows(
|
||||
sqlmock.NewRows([]string{
|
||||
"id", "content", "source_id", "source_type",
|
||||
"chunk_id", "knowledge_id", "knowledge_base_id", "tag_id",
|
||||
"is_enabled", "score",
|
||||
}).AddRow("id1", "hello", "src", 0, "c1", "k1", "kb1", "t1", true, 0.95),
|
||||
)
|
||||
|
||||
results, err := repo.VectorRetrieve(context.Background(), types.RetrieveParams{
|
||||
Embedding: []float32{1, 2, 3},
|
||||
TopK: 5,
|
||||
Threshold: 0.5,
|
||||
RetrieverType: types.VectorRetrieverType,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, results, 1)
|
||||
require.Len(t, results[0].Results, 1)
|
||||
assert.Equal(t, "id1", results[0].Results[0].ID)
|
||||
assert.InDelta(t, 0.95, results[0].Results[0].Score, 1e-9)
|
||||
assert.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestVectorRetrieve_SQLShape_LegacyMode(t *testing.T) {
|
||||
repo, mock, _, cleanup := newTestRepo(t)
|
||||
defer cleanup()
|
||||
primeCompatMode(repo, dorisCompatModeLegacy, nil)
|
||||
|
||||
mock.ExpectQuery(`SELECT COUNT\(1\) FROM information_schema.tables`).
|
||||
WithArgs("academy", "academy_embeddings_3").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"c"}).AddRow(1))
|
||||
|
||||
mock.ExpectQuery(`SELECT id, content, .*cosine_distance_approximate.*HAVING score >= \? ORDER BY score DESC LIMIT \d+`).
|
||||
WithArgs(true, 0.5).
|
||||
WillReturnRows(
|
||||
sqlmock.NewRows([]string{
|
||||
"id", "content", "source_id", "source_type",
|
||||
"chunk_id", "knowledge_id", "knowledge_base_id", "tag_id",
|
||||
"is_enabled", "score",
|
||||
}).AddRow("id1", "hello", "src", 0, "c1", "k1", "kb1", "t1", true, 0.8),
|
||||
)
|
||||
|
||||
results, err := repo.VectorRetrieve(context.Background(), types.RetrieveParams{
|
||||
Embedding: []float32{1, 2, 3},
|
||||
TopK: 5,
|
||||
Threshold: 0.5,
|
||||
RetrieverType: types.VectorRetrieverType,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, results, 1)
|
||||
require.Len(t, results[0].Results, 1)
|
||||
assert.Equal(t, "id1", results[0].Results[0].ID)
|
||||
assert.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestNormalizeEmbedding(t *testing.T) {
|
||||
t.Run("returns unit vector copy", func(t *testing.T) {
|
||||
got := normalizeEmbedding([]float32{3, 4})
|
||||
require.Len(t, got, 2)
|
||||
assert.InDelta(t, 0.6, got[0], 1e-6)
|
||||
assert.InDelta(t, 0.8, got[1], 1e-6)
|
||||
})
|
||||
|
||||
t.Run("keeps zero vector finite", func(t *testing.T) {
|
||||
got := normalizeEmbedding([]float32{0, 0})
|
||||
require.Len(t, got, 2)
|
||||
assert.Equal(t, []float32{0, 0}, got)
|
||||
})
|
||||
}
|
||||
|
||||
func TestKeywordsRetrieve_SQLShape(t *testing.T) {
|
||||
repo, mock, _, cleanup := newTestRepo(t)
|
||||
defer cleanup()
|
||||
|
||||
mock.ExpectQuery(`SELECT TABLE_NAME FROM information_schema.tables`).
|
||||
WithArgs("academy", "academy_embeddings\\_%").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"TABLE_NAME"}).
|
||||
AddRow("academy_embeddings_768"))
|
||||
|
||||
// LIMIT is inlined (see VectorRetrieve), so only is_enabled and the
|
||||
// MATCH_ANY query string are bound arguments.
|
||||
mock.ExpectQuery(`MATCH_ANY \?`).
|
||||
WithArgs(true, "你好").
|
||||
WillReturnRows(
|
||||
sqlmock.NewRows([]string{
|
||||
"id", "content", "source_id", "source_type",
|
||||
"chunk_id", "knowledge_id", "knowledge_base_id", "tag_id",
|
||||
"is_enabled",
|
||||
}).AddRow("id1", "你好世界", "src", 0, "c1", "k1", "kb1", "", true),
|
||||
)
|
||||
|
||||
results, err := repo.KeywordsRetrieve(context.Background(), types.RetrieveParams{
|
||||
Query: "你好",
|
||||
TopK: 3,
|
||||
RetrieverType: types.KeywordsRetrieverType,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, results, 1)
|
||||
require.Len(t, results[0].Results, 1)
|
||||
assert.Equal(t, "id1", results[0].Results[0].ID)
|
||||
assert.Equal(t, 1.0, results[0].Results[0].Score)
|
||||
assert.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestBatchUpdateChunkEnabledStatus_RewritesRows(t *testing.T) {
|
||||
db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherRegexp))
|
||||
require.NoError(t, err)
|
||||
defer db.Close()
|
||||
|
||||
repo := &dorisRepository{
|
||||
db: db,
|
||||
database: "academy",
|
||||
tableBaseName: "academy_embeddings",
|
||||
}
|
||||
primeCompatMode(repo, dorisCompatModeInnerProductDuplicate, nil)
|
||||
|
||||
mock.ExpectQuery(`SELECT TABLE_NAME FROM information_schema.tables`).
|
||||
WithArgs("academy", "academy_embeddings\\_%").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"TABLE_NAME"}).AddRow("academy_embeddings_768"))
|
||||
mock.ExpectQuery(`SELECT id, content, source_id, source_type, chunk_id, knowledge_id, knowledge_base_id, tag_id, is_enabled, embedding FROM .*academy_embeddings_768.* WHERE chunk_id IN`).
|
||||
WithArgs("c1").
|
||||
WillReturnRows(sqlmock.NewRows([]string{
|
||||
"id", "content", "source_id", "source_type",
|
||||
"chunk_id", "knowledge_id", "knowledge_base_id", "tag_id",
|
||||
"is_enabled", "embedding",
|
||||
}).AddRow("row-1", "hello", "src1", 0, "c1", "k1", "kb1", "t1", true, "[1,2,3]"))
|
||||
mock.ExpectExec(`DELETE FROM .*academy_embeddings_768.* WHERE id IN \(\?\)`).
|
||||
WithArgs("row-1").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectExec(`INSERT INTO .*academy_embeddings_768.*VALUES \(\?, \?, \?, \?, \?, \?, \?, \?, \?, \[`).
|
||||
WithArgs("row-1", "hello", "src1", 0, "c1", "k1", "kb1", "t1", false).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
|
||||
require.NoError(t, repo.BatchUpdateChunkEnabledStatus(
|
||||
context.Background(), map[string]bool{"c1": false}))
|
||||
assert.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestBatchUpdateChunkEnabledStatus_LegacyModeUsesPartialUpdate(t *testing.T) {
|
||||
repo, mock, _, cleanup := newTestRepo(t)
|
||||
defer cleanup()
|
||||
primeCompatMode(repo, dorisCompatModeLegacy, nil)
|
||||
|
||||
mock.ExpectQuery(`SELECT TABLE_NAME FROM information_schema.tables`).
|
||||
WithArgs("academy", "academy_embeddings\\_%").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"TABLE_NAME"}).AddRow("academy_embeddings_768"))
|
||||
mock.ExpectQuery(`SELECT id, chunk_id FROM .*academy_embeddings_768.* WHERE chunk_id IN`).
|
||||
WithArgs("c1").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "chunk_id"}).AddRow("row-1", "c1"))
|
||||
|
||||
require.NoError(t, repo.BatchUpdateChunkEnabledStatus(
|
||||
context.Background(), map[string]bool{"c1": false}))
|
||||
assert.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestEnsureTable_DDLShape(t *testing.T) {
|
||||
db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherRegexp))
|
||||
require.NoError(t, err)
|
||||
defer db.Close()
|
||||
|
||||
repo := &dorisRepository{
|
||||
db: db,
|
||||
database: "academy",
|
||||
tableBaseName: "academy_embeddings",
|
||||
bucketsNum: 5,
|
||||
replicationNum: 2,
|
||||
}
|
||||
primeCompatMode(repo, dorisCompatModeInnerProductDuplicate, nil)
|
||||
|
||||
// 表不存在
|
||||
mock.ExpectQuery(`SELECT COUNT\(1\) FROM information_schema.tables`).
|
||||
WithArgs("academy", "academy_embeddings_768").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"c"}).AddRow(0))
|
||||
// CREATE TABLE 应包含关键属性和 Doris 支持的 inner_product ANN metric
|
||||
mock.ExpectExec(`CREATE TABLE IF NOT EXISTS .*academy_embeddings_768.*metric_type"="inner_product".*DUPLICATE KEY\(id\).*BUCKETS 5.*replication_num.*=.*2`).
|
||||
WillReturnResult(sqlmock.NewResult(0, 0))
|
||||
// SHOW INDEX 一次即返回 ANN 已 FINISHED
|
||||
mock.ExpectQuery(`SHOW INDEX FROM .*academy_embeddings_768.*`).
|
||||
WillReturnRows(
|
||||
sqlmock.NewRows([]string{"Table", "Key_name", "State"}).
|
||||
AddRow("academy_embeddings_768", "idx_emb", "FINISHED"),
|
||||
)
|
||||
|
||||
require.NoError(t, repo.ensureTable(context.Background(), 768))
|
||||
// waitANNReady 在后台 goroutine 里执行,轮询 ExpectationsWereMet 直到 SHOW INDEX 也被消费。
|
||||
require.Eventually(t, func() bool {
|
||||
return mock.ExpectationsWereMet() == nil
|
||||
}, 2*time.Second, 10*time.Millisecond, "expectations should be met after async ANN poll")
|
||||
}
|
||||
|
||||
func TestEnsureTable_DDLShape_LegacyMode(t *testing.T) {
|
||||
db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherRegexp))
|
||||
require.NoError(t, err)
|
||||
defer db.Close()
|
||||
|
||||
repo := &dorisRepository{
|
||||
db: db,
|
||||
database: "academy",
|
||||
tableBaseName: "academy_embeddings",
|
||||
bucketsNum: 5,
|
||||
replicationNum: 2,
|
||||
}
|
||||
primeCompatMode(repo, dorisCompatModeLegacy, nil)
|
||||
|
||||
mock.ExpectQuery(`SELECT COUNT\(1\) FROM information_schema.tables`).
|
||||
WithArgs("academy", "academy_embeddings_768").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"c"}).AddRow(0))
|
||||
mock.ExpectExec(`CREATE TABLE IF NOT EXISTS .*academy_embeddings_768.*metric_type"="cosine_distance".*UNIQUE KEY\(id\).*enable_unique_key_merge_on_write.*true`).
|
||||
WillReturnResult(sqlmock.NewResult(0, 0))
|
||||
mock.ExpectQuery(`SHOW INDEX FROM .*academy_embeddings_768.*`).
|
||||
WillReturnRows(
|
||||
sqlmock.NewRows([]string{"Table", "Key_name", "State"}).
|
||||
AddRow("academy_embeddings_768", "idx_emb", "FINISHED"),
|
||||
)
|
||||
|
||||
require.NoError(t, repo.ensureTable(context.Background(), 768))
|
||||
require.Eventually(t, func() bool {
|
||||
return mock.ExpectationsWereMet() == nil
|
||||
}, 2*time.Second, 10*time.Millisecond, "expectations should be met after async ANN poll")
|
||||
}
|
||||
|
||||
func TestBatchSave_SQLShape(t *testing.T) {
|
||||
db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherRegexp))
|
||||
require.NoError(t, err)
|
||||
defer db.Close()
|
||||
|
||||
repo := &dorisRepository{
|
||||
db: db,
|
||||
database: "academy",
|
||||
tableBaseName: "academy_embeddings",
|
||||
}
|
||||
primeCompatMode(repo, dorisCompatModeInnerProductDuplicate, nil)
|
||||
repo.initializedTables.Store(3, true) // 跳过 ensureTable
|
||||
|
||||
mock.ExpectExec(`DELETE FROM .*academy_embeddings_3.* WHERE id IN \(\?\)`).
|
||||
WithArgs("src1").
|
||||
WillReturnResult(sqlmock.NewResult(0, 0))
|
||||
mock.ExpectExec(`INSERT INTO .*academy_embeddings_3.*VALUES \(\?, \?, \?, \?, \?, \?, \?, \?, \?, \[`).
|
||||
WithArgs(
|
||||
"src1", "hello", "src1", 0,
|
||||
"c1", "k1", "kb1", "",
|
||||
true,
|
||||
).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
|
||||
err = repo.BatchSave(context.Background(),
|
||||
[]*types.IndexInfo{{
|
||||
Content: "hello",
|
||||
SourceID: "src1",
|
||||
ChunkID: "c1",
|
||||
KnowledgeID: "k1",
|
||||
KnowledgeBaseID: "kb1",
|
||||
IsEnabled: true,
|
||||
}},
|
||||
map[string]any{
|
||||
fieldEmbedding: map[string][]float32{
|
||||
"src1": {1, 2, 3},
|
||||
},
|
||||
},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
assert.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestBatchSave_SQLShape_LegacyMode(t *testing.T) {
|
||||
db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherRegexp))
|
||||
require.NoError(t, err)
|
||||
defer db.Close()
|
||||
|
||||
repo := &dorisRepository{
|
||||
db: db,
|
||||
database: "academy",
|
||||
tableBaseName: "academy_embeddings",
|
||||
}
|
||||
primeCompatMode(repo, dorisCompatModeLegacy, nil)
|
||||
repo.initializedTables.Store(3, true)
|
||||
|
||||
mock.ExpectExec(`INSERT INTO .*academy_embeddings_3.*VALUES \(\?, \?, \?, \?, \?, \?, \?, \?, \?, \[`).
|
||||
WithArgs(
|
||||
"src1", "hello", "src1", 0,
|
||||
"c1", "k1", "kb1", "",
|
||||
true,
|
||||
).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
|
||||
err = repo.BatchSave(context.Background(),
|
||||
[]*types.IndexInfo{{
|
||||
Content: "hello",
|
||||
SourceID: "src1",
|
||||
ChunkID: "c1",
|
||||
KnowledgeID: "k1",
|
||||
KnowledgeBaseID: "kb1",
|
||||
IsEnabled: true,
|
||||
}},
|
||||
map[string]any{
|
||||
fieldEmbedding: map[string][]float32{
|
||||
"src1": {1, 2, 3},
|
||||
},
|
||||
},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
assert.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestResolveCompatMode_RejectsExistingModeSwitch(t *testing.T) {
|
||||
repo, mock, _, cleanup := newTestRepo(t)
|
||||
defer cleanup()
|
||||
repo.compatModeRequested = dorisCompatModeLegacy
|
||||
|
||||
mock.ExpectQuery(`SELECT TABLE_NAME FROM information_schema.tables`).
|
||||
WithArgs("academy", "academy_embeddings\\_%").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"TABLE_NAME"}).AddRow("academy_embeddings_768"))
|
||||
mock.ExpectQuery(`SHOW CREATE TABLE .*academy_embeddings_768.*`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"Table", "Create Table"}).AddRow(
|
||||
"academy_embeddings_768",
|
||||
"CREATE TABLE `academy_embeddings_768` (id VARCHAR(64)) ENGINE=OLAP DUPLICATE KEY(id) DISTRIBUTED BY HASH(id) BUCKETS 10 PROPERTIES(\"replication_num\"=\"1\")",
|
||||
))
|
||||
|
||||
_, err := repo.resolveCompatMode(context.Background())
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "not interchangeable after academy_embeddings_*")
|
||||
assert.Contains(t, err.Error(), string(dorisCompatModeInnerProductDuplicate))
|
||||
assert.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestResolveCompatMode_AutoPrefersInnerProductDuplicate(t *testing.T) {
|
||||
repo, mock, _, cleanup := newTestRepo(t)
|
||||
defer cleanup()
|
||||
repo.compatModeRequested = dorisCompatModeAuto
|
||||
|
||||
mock.ExpectQuery(`SELECT TABLE_NAME FROM information_schema.tables`).
|
||||
WithArgs("academy", "academy_embeddings\\_%").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"TABLE_NAME"}))
|
||||
mock.ExpectQuery(`SELECT inner_product_approximate\(\[1.0\],\[1.0\]\)`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"v"}).AddRow(1.0))
|
||||
mock.ExpectQuery(`SELECT cosine_distance_approximate\(\[1.0\],\[1.0\]\)`).
|
||||
WillReturnError(errors.New("unsupported"))
|
||||
|
||||
mode, err := repo.resolveCompatMode(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, dorisCompatModeInnerProductDuplicate, mode)
|
||||
assert.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Engine wiring
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestEngineTypeAndSupport(t *testing.T) {
|
||||
repo, _, _, cleanup := newTestRepo(t)
|
||||
defer cleanup()
|
||||
|
||||
assert.Equal(t, types.DorisRetrieverEngineType, repo.EngineType())
|
||||
supports := repo.Support()
|
||||
assert.Contains(t, supports, types.KeywordsRetrieverType)
|
||||
assert.Contains(t, supports, types.VectorRetrieverType)
|
||||
}
|
||||
|
||||
func TestRetrieve_DispatchesByType(t *testing.T) {
|
||||
repo, mock, _, cleanup := newTestRepo(t)
|
||||
defer cleanup()
|
||||
|
||||
// invalid retriever type -> error,不会触发任何 SQL
|
||||
_, err := repo.Retrieve(context.Background(), types.RetrieveParams{
|
||||
RetrieverType: "unknown",
|
||||
})
|
||||
require.Error(t, err)
|
||||
assert.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// regression / utility
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestTranslateSourceID(t *testing.T) {
|
||||
t.Run("plain chunk uses target chunk", func(t *testing.T) {
|
||||
got := translateSourceID("c1", "c1", "tc1")
|
||||
assert.Equal(t, "tc1", got)
|
||||
})
|
||||
t.Run("generated question preserves question id", func(t *testing.T) {
|
||||
got := translateSourceID("c1-q9", "c1", "tc1")
|
||||
assert.Equal(t, "tc1-q9", got)
|
||||
})
|
||||
t.Run("unrecognized source falls back to fresh uuid", func(t *testing.T) {
|
||||
got := translateSourceID("totally-other", "c1", "tc1")
|
||||
assert.NotEqual(t, "totally-other", got)
|
||||
assert.Len(t, got, 36) // UUID 长度
|
||||
})
|
||||
}
|
||||
|
||||
func TestEstimateStorageSize(t *testing.T) {
|
||||
repo, _, _, cleanup := newTestRepo(t)
|
||||
defer cleanup()
|
||||
|
||||
out := repo.EstimateStorageSize(context.Background(),
|
||||
[]*types.IndexInfo{{Content: "hello", ChunkID: "c1", KnowledgeID: "k1", KnowledgeBaseID: "kb1"}},
|
||||
map[string]any{
|
||||
fieldEmbedding: map[string][]float32{
|
||||
"": {1, 2, 3},
|
||||
},
|
||||
},
|
||||
)
|
||||
assert.Greater(t, out, int64(0))
|
||||
}
|
||||
|
||||
// 保证 *sql.Rows 错误不会被吞掉。
|
||||
func TestScanRetrieveRows_Error(t *testing.T) {
|
||||
db, mock, err := sqlmock.New()
|
||||
require.NoError(t, err)
|
||||
defer db.Close()
|
||||
|
||||
mock.ExpectQuery("SELECT 1").
|
||||
WillReturnError(errors.New("boom"))
|
||||
|
||||
rows, err := db.Query("SELECT 1")
|
||||
if err != nil {
|
||||
// query 直接失败也算预期
|
||||
assert.Equal(t, "boom", err.Error())
|
||||
return
|
||||
}
|
||||
_, scanErr := scanRetrieveRows(rows, types.MatchTypeEmbedding)
|
||||
if scanErr != nil {
|
||||
assert.Error(t, scanErr)
|
||||
}
|
||||
}
|
||||
|
||||
// silence unused import warning when sql isn't directly used
|
||||
var _ = sql.ErrNoRows
|
||||
@@ -0,0 +1,310 @@
|
||||
package doris
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"academy/internal/logger"
|
||||
)
|
||||
|
||||
// 默认的桶数 / 副本数。Doris 在 PROPERTIES 不指定时会用集群默认值,
|
||||
// 这里给一个对单机/小集群更友好的保守值。
|
||||
const (
|
||||
defaultBucketsNum = 10
|
||||
defaultReplicationNum = 1
|
||||
|
||||
// ANN 索引就绪轮询的最大等待时间。索引未就绪不阻塞写入路径,
|
||||
// 只阻塞 ensureTable 自身(首次建表场景),所以 30s 是可接受的。
|
||||
annReadyTimeout = 30 * time.Second
|
||||
annReadyPoll = 1 * time.Second
|
||||
)
|
||||
|
||||
// getTableName 返回某个维度对应的物理表名:<base>_<dim>。
|
||||
//
|
||||
// 与 Qdrant/Milvus/Weaviate 的 collection 命名约定一致,
|
||||
// 这样不同 embedding 模型(不同维度)的数据互不冲突。
|
||||
func (r *dorisRepository) getTableName(dimension int) string {
|
||||
return fmt.Sprintf("%s_%d", r.tableBaseName, dimension)
|
||||
}
|
||||
|
||||
// ensureTable 保证目标维度对应的表已经存在;
|
||||
// 不存在则用 CREATE TABLE IF NOT EXISTS 创建,并在创建后轮询 ANN 索引就绪。
|
||||
//
|
||||
// 该方法在每次 Save / BatchSave 之前调用,结果缓存在 initializedTables 中,
|
||||
// 同一进程内同一 dimension 只会真正打一次 SHOW TABLES + DDL。
|
||||
func (r *dorisRepository) ensureTable(ctx context.Context, dimension int) error {
|
||||
if _, ok := r.initializedTables.Load(dimension); ok {
|
||||
return nil
|
||||
}
|
||||
compatMode, err := r.resolveCompatMode(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
log := logger.GetLogger(ctx)
|
||||
tableName := r.getTableName(dimension)
|
||||
|
||||
exists, err := r.tableExists(ctx, tableName)
|
||||
if err != nil {
|
||||
log.Errorf("[Doris] Failed to check table existence: %v", err)
|
||||
return fmt.Errorf("check table existence: %w", err)
|
||||
}
|
||||
|
||||
if !exists {
|
||||
log.Infof("[Doris] Creating table %s with dimension %d in compat mode %s", tableName, dimension, compatMode)
|
||||
if err := r.createTable(ctx, tableName, dimension, compatMode); err != nil {
|
||||
log.Errorf("[Doris] Failed to create table: %v", err)
|
||||
return fmt.Errorf("create table: %w", err)
|
||||
}
|
||||
|
||||
// ANN 索引在 Doris 端异步构建。这里在后台 goroutine 里轮询就绪,
|
||||
// 写入路径不阻塞——索引未就绪期间检索会退化为 brute-force(结果对、速度慢),
|
||||
// 比让首批写入卡 30s 更可接受。
|
||||
go func(tn string) {
|
||||
// 用独立 context(带 timeout),避免请求级 ctx 取消把后台轮询也带走。
|
||||
bgCtx, cancel := context.WithTimeout(context.Background(), annReadyTimeout)
|
||||
defer cancel()
|
||||
if err := r.waitANNReady(bgCtx, tn); err != nil {
|
||||
logger.GetLogger(bgCtx).Warnf(
|
||||
"[Doris] ANN index for %s not ready within %s: %v "+
|
||||
"(queries may fall back to brute force temporarily)",
|
||||
tn, annReadyTimeout, err)
|
||||
return
|
||||
}
|
||||
logger.GetLogger(bgCtx).Infof("[Doris] ANN index for %s ready", tn)
|
||||
}(tableName)
|
||||
}
|
||||
|
||||
r.initializedTables.Store(dimension, true)
|
||||
return nil
|
||||
}
|
||||
|
||||
// tableExists 通过 information_schema 判断表是否存在。
|
||||
//
|
||||
// 不直接用 SHOW TABLES 是因为 Doris 4.1 对 SHOW TABLES LIKE 大小写敏感,
|
||||
// 而 information_schema 与 MySQL 兼容性更好。
|
||||
func (r *dorisRepository) tableExists(ctx context.Context, tableName string) (bool, error) {
|
||||
const q = `SELECT COUNT(1) FROM information_schema.tables
|
||||
WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?`
|
||||
var n int
|
||||
if err := r.db.QueryRowContext(ctx, q, r.database, tableName).Scan(&n); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return n > 0, nil
|
||||
}
|
||||
|
||||
// createTable 发出 CREATE TABLE DDL。Doris DDL 是同步的(除 ANN 索引构建外),
|
||||
// 返回成功即代表表已可写。
|
||||
func (r *dorisRepository) createTable(ctx context.Context, tableName string, dimension int, compatMode dorisCompatMode) error {
|
||||
buckets := r.bucketsNum
|
||||
if buckets <= 0 {
|
||||
buckets = defaultBucketsNum
|
||||
}
|
||||
replication := r.replicationNum
|
||||
if replication <= 0 {
|
||||
replication = defaultReplicationNum
|
||||
}
|
||||
|
||||
ddl := buildCreateTableDDL(tableName, dimension, buckets, replication, compatMode)
|
||||
_, err := r.db.ExecContext(ctx, ddl)
|
||||
if err != nil && compatMode == dorisCompatModeLegacy {
|
||||
return fmt.Errorf(
|
||||
"legacy Doris table creation failed: %w. If your Doris build rejects ANN indexes on UNIQUE KEY tables, set %s=%s before creating embedding tables. %s is not interchangeable after %s_* tables are created",
|
||||
err,
|
||||
envDorisCompatMode,
|
||||
dorisCompatModeInnerProductDuplicate,
|
||||
envDorisCompatMode,
|
||||
r.tableBaseName,
|
||||
)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// buildCreateTableDDL 根据维度生成 CREATE TABLE DDL。
|
||||
//
|
||||
// 关键点:
|
||||
// - DUPLICATE KEY(id):兼容当前 Doris/SelectDB 对 ANN 索引的表模型要求。
|
||||
// Academy 在 Go 端用 delete + insert 保持按 id 替换的写入语义。
|
||||
// - INVERTED 索引覆盖所有过滤字段 + 中文分词的 content 全文索引。
|
||||
// - ANN 索引使用 HNSW + inner_product;Doris 写入/查询前会对向量单位化,
|
||||
// 因此整体仍保持与其他向量库一致的 cosine 相似度语义。
|
||||
//
|
||||
// 注意:DDL 中 dimension / buckets / replication 三个数值字段是 Go 端格式化拼接的,
|
||||
// 不存在 SQL 注入风险(来源都是受控的 IndexConfig int)。
|
||||
func buildCreateTableDDL(tableName string, dimension, buckets, replication int, compatMode dorisCompatMode) string {
|
||||
metricType := "inner_product"
|
||||
keyMode := "DUPLICATE KEY(id)"
|
||||
properties := fmt.Sprintf("\t\"replication_num\"=\"%d\"", replication)
|
||||
if compatMode == dorisCompatModeLegacy {
|
||||
metricType = "cosine_distance"
|
||||
keyMode = "UNIQUE KEY(id)"
|
||||
properties = fmt.Sprintf("\t\"replication_num\"=\"%d\",\n\t\"enable_unique_key_merge_on_write\"=\"true\"", replication)
|
||||
}
|
||||
|
||||
const tpl = `CREATE TABLE IF NOT EXISTS ` + "`%s`" + ` (
|
||||
id VARCHAR(64) NOT NULL,
|
||||
chunk_id VARCHAR(64),
|
||||
knowledge_id VARCHAR(64),
|
||||
knowledge_base_id VARCHAR(64),
|
||||
source_id VARCHAR(255),
|
||||
source_type INT,
|
||||
tag_id VARCHAR(64),
|
||||
is_enabled BOOLEAN,
|
||||
content TEXT,
|
||||
embedding ARRAY<FLOAT> NOT NULL,
|
||||
INDEX idx_chunk (chunk_id) USING INVERTED,
|
||||
INDEX idx_kb (knowledge_base_id) USING INVERTED,
|
||||
INDEX idx_kid (knowledge_id) USING INVERTED,
|
||||
INDEX idx_src (source_id) USING INVERTED,
|
||||
INDEX idx_tag (tag_id) USING INVERTED,
|
||||
INDEX idx_enabled (is_enabled) USING INVERTED,
|
||||
INDEX idx_content (content) USING INVERTED PROPERTIES("parser"="chinese","support_phrase"="true"),
|
||||
INDEX idx_emb (embedding) USING ANN PROPERTIES(
|
||||
"index_type"="hnsw",
|
||||
"metric_type"="%s",
|
||||
"dim"="%d",
|
||||
"max_degree"="32",
|
||||
"ef_construction"="200"
|
||||
)
|
||||
) ENGINE=OLAP
|
||||
%s
|
||||
DISTRIBUTED BY HASH(id) BUCKETS %d
|
||||
PROPERTIES(
|
||||
%s
|
||||
);`
|
||||
return fmt.Sprintf(tpl, tableName, metricType, dimension, keyMode, buckets, properties)
|
||||
}
|
||||
|
||||
// waitANNReady 轮询 SHOW INDEX,等待 ANN 索引进入 FINISHED 状态。
|
||||
//
|
||||
// Doris 的 ANN 索引在建表后会异步构建,期间查询会退化为 brute-force(结果对,速度慢)。
|
||||
// 此处仅做"尽力而为"的等待:到点未就绪只记 warning,不阻塞写入。
|
||||
func (r *dorisRepository) waitANNReady(ctx context.Context, tableName string) error {
|
||||
deadline := time.Now().Add(annReadyTimeout)
|
||||
for {
|
||||
ready, err := r.annIndexReady(ctx, tableName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ready {
|
||||
return nil
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
return fmt.Errorf("ann index not ready within %s", annReadyTimeout)
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-time.After(annReadyPoll):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// annIndexReady 检查 ANN 索引的 State 是否为 FINISHED。
|
||||
//
|
||||
// SHOW INDEX FROM <table> 在 Doris 上返回多列;不同小版本列序略有差异,
|
||||
// 这里以列名匹配(来自 information_schema.statistics + 自定义 view 不可行,
|
||||
// 直接用 SHOW INDEX 然后扫描即可)。
|
||||
//
|
||||
// 兼容策略:如果 SHOW INDEX 返回中找不到 idx_emb 行(极旧版本),视为已就绪,
|
||||
// 避免因为不同 Doris 版本的输出差异把启动卡死。
|
||||
func (r *dorisRepository) annIndexReady(ctx context.Context, tableName string) (bool, error) {
|
||||
rows, err := r.db.QueryContext(ctx,
|
||||
fmt.Sprintf("SHOW INDEX FROM `%s`", tableName))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
cols, err := rows.Columns()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
keyNameIdx, stateIdx := -1, -1
|
||||
for i, c := range cols {
|
||||
switch strings.ToLower(c) {
|
||||
case "key_name":
|
||||
keyNameIdx = i
|
||||
case "state", "index_state":
|
||||
stateIdx = i
|
||||
}
|
||||
}
|
||||
|
||||
for rows.Next() {
|
||||
// 使用 sql.RawBytes 接收以兼容不同列类型。
|
||||
raw := make([]any, len(cols))
|
||||
ptrs := make([]any, len(cols))
|
||||
for i := range raw {
|
||||
ptrs[i] = &raw[i]
|
||||
}
|
||||
if err := rows.Scan(ptrs...); err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
var keyName, state string
|
||||
if keyNameIdx >= 0 {
|
||||
keyName = bytesToString(raw[keyNameIdx])
|
||||
}
|
||||
if stateIdx >= 0 {
|
||||
state = bytesToString(raw[stateIdx])
|
||||
}
|
||||
|
||||
if keyName != "idx_emb" {
|
||||
continue
|
||||
}
|
||||
if stateIdx < 0 {
|
||||
// 旧版本不暴露 state 列,乐观认为已就绪。
|
||||
return true, nil
|
||||
}
|
||||
if !strings.EqualFold(state, "FINISHED") &&
|
||||
!strings.EqualFold(state, "NORMAL") {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
// 走到这里有两种情况:
|
||||
// 1. 找到了 idx_emb 行,且 state 已是 FINISHED/NORMAL(或 stateIdx<0 的旧版本);
|
||||
// 2. 没找到 idx_emb 行(极旧 Doris 不暴露该索引名);
|
||||
// 都视为已就绪,不阻塞。未就绪的分支已在循环内提前 return false。
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// listEmbeddingTables 返回当前 database 下所有 <base>_% 命名的表,
|
||||
// 用于关键词检索 / 跨维度 BatchUpdate。
|
||||
func (r *dorisRepository) listEmbeddingTables(ctx context.Context) ([]string, error) {
|
||||
const q = `SELECT TABLE_NAME FROM information_schema.tables
|
||||
WHERE TABLE_SCHEMA = ? AND TABLE_NAME LIKE ?`
|
||||
rows, err := r.db.QueryContext(ctx, q, r.database, r.tableBaseName+"\\_%")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var names []string
|
||||
for rows.Next() {
|
||||
var n string
|
||||
if err := rows.Scan(&n); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
names = append(names, n)
|
||||
}
|
||||
return names, rows.Err()
|
||||
}
|
||||
|
||||
// bytesToString 把 SHOW INDEX 返回的 raw any(通常是 []byte 或 string)
|
||||
// 安全转成字符串。
|
||||
func bytesToString(v any) string {
|
||||
switch s := v.(type) {
|
||||
case []byte:
|
||||
return string(s)
|
||||
case string:
|
||||
return s
|
||||
case nil:
|
||||
return ""
|
||||
default:
|
||||
return fmt.Sprintf("%v", s)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,512 @@
|
||||
package doris
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"academy/internal/logger"
|
||||
secutils "academy/internal/utils"
|
||||
)
|
||||
|
||||
// Stream Load 相关常量。
|
||||
const (
|
||||
// 单批 Stream Load 的 JSON body 上限(保守值,远小于 Doris 默认 streaming_load_max_mb=10240)。
|
||||
// 主要目的是控制单次 HTTP 请求的尾延迟,超过则自动拆批。
|
||||
streamLoadMaxBatchBytes = 1 << 20 // 1 MiB
|
||||
|
||||
// HTTP 头 Authorization 用 Basic auth;Stream Load 也支持 token,
|
||||
// 这里走最常用的用户名/密码方案与 MySQL 协议保持一致。
|
||||
headerAuthorization = "Authorization"
|
||||
headerExpect = "Expect"
|
||||
headerContentType = "Content-Type"
|
||||
)
|
||||
|
||||
// streamLoadResponse 是 Doris FE/BE 返回的 Stream Load 结果体。
|
||||
//
|
||||
// 关键字段:Status 应为 "Success" 或 "Publish Timeout"(后者表示数据已写入但发布事务超时,
|
||||
// 仍视为成功)。其它状态都视为失败。
|
||||
type streamLoadResponse struct {
|
||||
TxnId int64 `json:"TxnId"`
|
||||
Label string `json:"Label"`
|
||||
Status string `json:"Status"`
|
||||
Message string `json:"Message"`
|
||||
NumberTotalRows int64 `json:"NumberTotalRows"`
|
||||
NumberLoadedRows int64 `json:"NumberLoadedRows"`
|
||||
NumberFilteredRows int64 `json:"NumberFilteredRows"`
|
||||
NumberUnselectedRows int64 `json:"NumberUnselectedRows"`
|
||||
LoadBytes int64 `json:"LoadBytes"`
|
||||
LoadTimeMs int64 `json:"LoadTimeMs"`
|
||||
BeginTxnTimeMs int64 `json:"BeginTxnTimeMs"`
|
||||
StreamLoadPutTimeMs int64 `json:"StreamLoadPutTimeMs"`
|
||||
ReadDataTimeMs int64 `json:"ReadDataTimeMs"`
|
||||
WriteDataTimeMs int64 `json:"WriteDataTimeMs"`
|
||||
CommitAndPublishTimeMs int64 `json:"CommitAndPublishTimeMs"`
|
||||
ErrorURL string `json:"ErrorURL"`
|
||||
}
|
||||
|
||||
// streamLoadURL 拼装某张表的 Stream Load HTTP 端点。
|
||||
func (r *dorisRepository) streamLoadURL(table string) string {
|
||||
return fmt.Sprintf("%s/api/%s/%s/_stream_load",
|
||||
r.feHTTPBase, url.PathEscape(r.database), url.PathEscape(table))
|
||||
}
|
||||
|
||||
// newDorisStreamLoadHTTPClient protects both the initial FE request and every
|
||||
// FE -> BE redirect at connection time. Doris requires Basic auth to survive
|
||||
// the 307 redirect, so redirect targets on another host must be explicitly
|
||||
// trusted through the SSRF whitelist before credentials are forwarded.
|
||||
func newDorisStreamLoadHTTPClient() *http.Client {
|
||||
cfg := secutils.DefaultSSRFSafeHTTPClientConfig()
|
||||
// Stream Load calls carry their own context deadline. Preserve the previous
|
||||
// client behaviour instead of imposing the generic 30-second HTTP timeout.
|
||||
cfg.Timeout = 0
|
||||
|
||||
client := secutils.NewSSRFSafeHTTPClient(cfg)
|
||||
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
|
||||
if len(via) >= cfg.MaxRedirects {
|
||||
return fmt.Errorf("stopped after %d redirects", cfg.MaxRedirects)
|
||||
}
|
||||
if len(via) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stream Load deliberately replays PUT bodies to a BE. Keep this
|
||||
// exception local to Doris; generic clients must not replay requests
|
||||
// across origins. Every cross-origin destination must be trusted.
|
||||
source := via[0].URL
|
||||
sameOrigin := strings.EqualFold(source.Scheme, req.URL.Scheme) &&
|
||||
strings.EqualFold(source.Host, req.URL.Host)
|
||||
if !sameOrigin && !secutils.IsSSRFWhitelisted(req.URL.Hostname()) {
|
||||
return fmt.Errorf("%w: stream load target host %q is not trusted to receive credentials",
|
||||
secutils.ErrSSRFRedirectBlocked, req.URL.Hostname())
|
||||
}
|
||||
if strings.EqualFold(source.Scheme, "https") && !strings.EqualFold(req.URL.Scheme, "https") {
|
||||
return fmt.Errorf("%w: stream load HTTPS downgrade is forbidden", secutils.ErrSSRFRedirectBlocked)
|
||||
}
|
||||
if err := secutils.ValidateURLForSSRF(req.URL.String()); err != nil {
|
||||
return fmt.Errorf("%w: %w", secutils.ErrSSRFRedirectBlocked, err)
|
||||
}
|
||||
|
||||
// The shared transport still validates each URL and connection. Preserve
|
||||
// load options and restore Basic auth only after checking the destination.
|
||||
req.Header.Set(headerAuthorization, via[0].Header.Get(headerAuthorization))
|
||||
return nil
|
||||
}
|
||||
return client
|
||||
}
|
||||
|
||||
// partialUpdateRows 把若干行通过 Stream Load 的 partial update 模式写回目标表。
|
||||
//
|
||||
// columns 是参与本次 partial update 的列(必须包含 UNIQUE KEY 列,即 "id")。
|
||||
// rows 中每一项是一个与 columns 等长的字段值数组。
|
||||
//
|
||||
// 实现要点:
|
||||
// 1. 用 JSON 数组的 body 形式,header 加 strip_outer_array=true。
|
||||
// 2. 设置 partial_columns=true、merge_type=APPEND,触发 Doris 的 partial update 模式
|
||||
// (Doris 4.1 + UNIQUE KEY MoW 表的标准玩法)。
|
||||
// 3. 按 streamLoadMaxBatchBytes 自动拆批,避免单次过大。
|
||||
// 4. 处理 307:Doris 的 FE 会 redirect 到 BE,net/http 默认会跟随;
|
||||
// 这里需要保证 GetBody 可重发(已通过 bytes.NewReader 构造 Body 满足)。
|
||||
func (r *dorisRepository) partialUpdateRows(ctx context.Context,
|
||||
table string, columns []string, rows []map[string]any,
|
||||
) error {
|
||||
if len(rows) == 0 {
|
||||
return nil
|
||||
}
|
||||
for _, batch := range chunkRows(rows, streamLoadMaxBatchBytes) {
|
||||
if err := r.streamLoadOnce(ctx, table, columns, batch); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// streamLoadOnce 发出一次 Stream Load HTTP 请求。
|
||||
func (r *dorisRepository) streamLoadOnce(ctx context.Context,
|
||||
table string, columns []string, rows []map[string]any,
|
||||
) error {
|
||||
log := logger.GetLogger(ctx)
|
||||
if len(rows) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
body, err := json.Marshal(rows)
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal stream load body: %w", err)
|
||||
}
|
||||
|
||||
url := r.streamLoadURL(table)
|
||||
// Validate at the final outbound boundary as well as when user-supplied
|
||||
// vector-store configuration is created. This covers stored/env configs and
|
||||
// keeps the tainted value from reaching http.Client.Do unchecked.
|
||||
if err := secutils.ValidateURLForSSRF(url); err != nil {
|
||||
return fmt.Errorf("stream load URL blocked by SSRF validation: %w", err)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPut, url, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return fmt.Errorf("build stream load request: %w", err)
|
||||
}
|
||||
|
||||
// GetBody 让 redirect 时可以重新读 body(FE -> BE 的 307 需要重发 PUT body)。
|
||||
bodyCopy := append([]byte(nil), body...)
|
||||
req.GetBody = func() (io.ReadCloser, error) {
|
||||
return io.NopCloser(bytes.NewReader(bodyCopy)), nil
|
||||
}
|
||||
req.ContentLength = int64(len(body))
|
||||
|
||||
auth := base64.StdEncoding.EncodeToString([]byte(r.username + ":" + r.password))
|
||||
req.Header.Set(headerAuthorization, "Basic "+auth)
|
||||
req.Header.Set(headerExpect, "100-continue")
|
||||
req.Header.Set(headerContentType, "application/json")
|
||||
req.Header.Set("format", "json")
|
||||
req.Header.Set("strip_outer_array", "true")
|
||||
req.Header.Set("partial_columns", "true")
|
||||
req.Header.Set("columns", strings.Join(columns, ","))
|
||||
req.Header.Set("merge_type", "APPEND")
|
||||
|
||||
resp, err := r.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("stream load HTTP: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBody, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read stream load response: %w", err)
|
||||
}
|
||||
if resp.StatusCode/100 != 2 {
|
||||
return fmt.Errorf("stream load HTTP %d: %s", resp.StatusCode, string(respBody))
|
||||
}
|
||||
|
||||
var result streamLoadResponse
|
||||
if err := json.Unmarshal(respBody, &result); err != nil {
|
||||
return fmt.Errorf("decode stream load response: %w (raw=%s)", err, string(respBody))
|
||||
}
|
||||
|
||||
switch result.Status {
|
||||
case "Success", "Publish Timeout":
|
||||
log.Infof("[Doris] Stream load %s OK: rows=%d, loaded=%d, label=%s",
|
||||
table, result.NumberTotalRows, result.NumberLoadedRows, result.Label)
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("stream load failed: status=%s msg=%s err_url=%s",
|
||||
result.Status, result.Message, result.ErrorURL)
|
||||
}
|
||||
}
|
||||
|
||||
// chunkRows 把行按累积 JSON 体大小切分,每段不超过 maxBytes。
|
||||
//
|
||||
// 注意:JSON 序列化的实际开销大约是 marshal 后的字节数,而单行 marshal
|
||||
// 加上逗号 + 数组括号约等于本估算。这里用粗略估计避免每段都 marshal。
|
||||
func chunkRows(rows []map[string]any, maxBytes int) [][]map[string]any {
|
||||
if len(rows) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var (
|
||||
out [][]map[string]any
|
||||
curr []map[string]any
|
||||
size int
|
||||
header = 2 // "[" + "]"
|
||||
)
|
||||
|
||||
for _, row := range rows {
|
||||
raw, err := json.Marshal(row)
|
||||
if err != nil {
|
||||
// marshal 失败时把这一行单独成段,由上层 streamLoadOnce 再次 marshal 报错。
|
||||
if len(curr) > 0 {
|
||||
out = append(out, curr)
|
||||
}
|
||||
out = append(out, []map[string]any{row})
|
||||
curr = nil
|
||||
size = 0
|
||||
continue
|
||||
}
|
||||
// 加上逗号位(除第一行之外)。
|
||||
need := len(raw)
|
||||
if len(curr) > 0 {
|
||||
need++
|
||||
}
|
||||
if size+need+header > maxBytes && len(curr) > 0 {
|
||||
out = append(out, curr)
|
||||
curr = nil
|
||||
size = 0
|
||||
}
|
||||
curr = append(curr, row)
|
||||
size += need
|
||||
}
|
||||
if len(curr) > 0 {
|
||||
out = append(out, curr)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 业务面方法:BatchUpdateChunkEnabledStatus / BatchUpdateChunkTagID
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// BatchUpdateChunkEnabledStatus 批量更新 chunk 的 is_enabled 字段。
|
||||
// legacy 模式走 Stream Load partial update;inner_product_duplicate 模式改为读整行后 replaceRows 写回。
|
||||
func (r *dorisRepository) BatchUpdateChunkEnabledStatus(ctx context.Context,
|
||||
chunkStatusMap map[string]bool,
|
||||
) error {
|
||||
if len(chunkStatusMap) == 0 {
|
||||
return nil
|
||||
}
|
||||
compatMode, err := r.resolveCompatMode(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !compatMode.usesRewriteChunkUpdates() {
|
||||
return r.batchUpdateChunkEnabledStatusLegacy(ctx, chunkStatusMap)
|
||||
}
|
||||
|
||||
chunkIDs := make([]string, 0, len(chunkStatusMap))
|
||||
for id := range chunkStatusMap {
|
||||
chunkIDs = append(chunkIDs, id)
|
||||
}
|
||||
|
||||
return r.rewriteChunkRows(ctx, chunkIDs, func(row *DorisVectorEmbedding) bool {
|
||||
enabled, ok := chunkStatusMap[row.ChunkID]
|
||||
if !ok || row.IsEnabled == enabled {
|
||||
return false
|
||||
}
|
||||
row.IsEnabled = enabled
|
||||
return true
|
||||
}, "rewrite is_enabled")
|
||||
}
|
||||
|
||||
// BatchUpdateChunkTagID 批量更新 chunk 的 tag_id 字段。逻辑与 EnabledStatus 一致。
|
||||
func (r *dorisRepository) BatchUpdateChunkTagID(ctx context.Context,
|
||||
chunkTagMap map[string]string,
|
||||
) error {
|
||||
if len(chunkTagMap) == 0 {
|
||||
return nil
|
||||
}
|
||||
compatMode, err := r.resolveCompatMode(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !compatMode.usesRewriteChunkUpdates() {
|
||||
return r.batchUpdateChunkTagIDLegacy(ctx, chunkTagMap)
|
||||
}
|
||||
|
||||
chunkIDs := make([]string, 0, len(chunkTagMap))
|
||||
for id := range chunkTagMap {
|
||||
chunkIDs = append(chunkIDs, id)
|
||||
}
|
||||
|
||||
return r.rewriteChunkRows(ctx, chunkIDs, func(row *DorisVectorEmbedding) bool {
|
||||
tagID, ok := chunkTagMap[row.ChunkID]
|
||||
if !ok || row.TagID == tagID {
|
||||
return false
|
||||
}
|
||||
row.TagID = tagID
|
||||
return true
|
||||
}, "rewrite tag_id")
|
||||
}
|
||||
|
||||
func (r *dorisRepository) rewriteChunkRows(ctx context.Context,
|
||||
chunkIDs []string,
|
||||
mutate func(*DorisVectorEmbedding) bool,
|
||||
action string,
|
||||
) error {
|
||||
if len(chunkIDs) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
tables, err := r.listEmbeddingTables(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("list tables: %w", err)
|
||||
}
|
||||
|
||||
for _, table := range tables {
|
||||
rows, err := r.loadRowsByChunkIDs(ctx, table, chunkIDs)
|
||||
if err != nil {
|
||||
return fmt.Errorf("load chunk rows from %s: %w", table, err)
|
||||
}
|
||||
|
||||
updated := make([]*DorisVectorEmbedding, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
if !mutate(row) {
|
||||
continue
|
||||
}
|
||||
updated = append(updated, row)
|
||||
}
|
||||
if len(updated) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
if err := r.replaceRows(ctx, table, updated); err != nil {
|
||||
return fmt.Errorf("%s in %s: %w", action, table, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *dorisRepository) batchUpdateChunkEnabledStatusLegacy(ctx context.Context,
|
||||
chunkStatusMap map[string]bool,
|
||||
) error {
|
||||
chunkIDs := make([]string, 0, len(chunkStatusMap))
|
||||
for id := range chunkStatusMap {
|
||||
chunkIDs = append(chunkIDs, id)
|
||||
}
|
||||
|
||||
mapping, err := r.lookupChunkRowKeys(ctx, chunkIDs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
byTable := make(map[string][]map[string]any)
|
||||
for chunkID, locations := range mapping {
|
||||
enabled, ok := chunkStatusMap[chunkID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
for _, loc := range locations {
|
||||
byTable[loc.table] = append(byTable[loc.table], map[string]any{
|
||||
fieldID: loc.id,
|
||||
fieldIsEnabled: enabled,
|
||||
})
|
||||
}
|
||||
}
|
||||
for table, rows := range byTable {
|
||||
if err := r.partialUpdateRows(ctx, table, []string{fieldID, fieldIsEnabled}, rows); err != nil {
|
||||
return fmt.Errorf("partial update is_enabled in %s: %w", table, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *dorisRepository) batchUpdateChunkTagIDLegacy(ctx context.Context,
|
||||
chunkTagMap map[string]string,
|
||||
) error {
|
||||
chunkIDs := make([]string, 0, len(chunkTagMap))
|
||||
for id := range chunkTagMap {
|
||||
chunkIDs = append(chunkIDs, id)
|
||||
}
|
||||
|
||||
mapping, err := r.lookupChunkRowKeys(ctx, chunkIDs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
byTable := make(map[string][]map[string]any)
|
||||
for chunkID, locations := range mapping {
|
||||
tagID, ok := chunkTagMap[chunkID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
for _, loc := range locations {
|
||||
byTable[loc.table] = append(byTable[loc.table], map[string]any{
|
||||
fieldID: loc.id,
|
||||
fieldTagID: tagID,
|
||||
})
|
||||
}
|
||||
}
|
||||
for table, rows := range byTable {
|
||||
if err := r.partialUpdateRows(ctx, table, []string{fieldID, fieldTagID}, rows); err != nil {
|
||||
return fmt.Errorf("partial update tag_id in %s: %w", table, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *dorisRepository) loadRowsByChunkIDs(ctx context.Context,
|
||||
table string, chunkIDs []string,
|
||||
) ([]*DorisVectorEmbedding, error) {
|
||||
if len(chunkIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
placeholders := make([]string, len(chunkIDs))
|
||||
args := make([]any, len(chunkIDs))
|
||||
for i, v := range chunkIDs {
|
||||
placeholders[i] = "?"
|
||||
args[i] = v
|
||||
}
|
||||
|
||||
stmt := fmt.Sprintf(
|
||||
"SELECT %s FROM `%s` WHERE %s IN (%s)",
|
||||
strings.Join(columnsForCopy, ", "),
|
||||
table,
|
||||
fieldChunkID,
|
||||
strings.Join(placeholders, ", "),
|
||||
)
|
||||
rows, err := r.db.QueryContext(ctx, stmt, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
batch, err := scanCopyRows(rows)
|
||||
_ = rows.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return batch, nil
|
||||
}
|
||||
|
||||
// rowLocation 表示某行在哪个表里、主键 id 是什么。
|
||||
type rowLocation struct {
|
||||
table string
|
||||
id string
|
||||
}
|
||||
|
||||
// lookupChunkRowKeys 查询给定的 chunkIDs 在所有 <base>_<dim> 表中的物理位置:
|
||||
// - key:chunk_id
|
||||
// - value:[(table, id), ...],因为同一 chunk 可能在多个维度的表里都有副本。
|
||||
//
|
||||
// 跨表查询使用 listEmbeddingTables 列出的所有匹配表;每张表执行一次
|
||||
// SELECT id, chunk_id FROM <table> WHERE chunk_id IN (?, ?, ...)。
|
||||
func (r *dorisRepository) lookupChunkRowKeys(ctx context.Context,
|
||||
chunkIDs []string,
|
||||
) (map[string][]rowLocation, error) {
|
||||
if len(chunkIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
tables, err := r.listEmbeddingTables(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list tables: %w", err)
|
||||
}
|
||||
if len(tables) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
placeholders := make([]string, len(chunkIDs))
|
||||
args := make([]any, len(chunkIDs))
|
||||
for i, v := range chunkIDs {
|
||||
placeholders[i] = "?"
|
||||
args[i] = v
|
||||
}
|
||||
|
||||
out := make(map[string][]rowLocation)
|
||||
for _, table := range tables {
|
||||
stmt := fmt.Sprintf(
|
||||
"SELECT %s, %s FROM `%s` WHERE %s IN (%s)",
|
||||
fieldID, fieldChunkID, table, fieldChunkID, strings.Join(placeholders, ", "),
|
||||
)
|
||||
rows, err := r.db.QueryContext(ctx, stmt, args...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("lookup chunk row keys in %s: %w", table, err)
|
||||
}
|
||||
for rows.Next() {
|
||||
var id, chunkID string
|
||||
if err := rows.Scan(&id, &chunkID); err != nil {
|
||||
_ = rows.Close()
|
||||
return nil, fmt.Errorf("scan row keys: %w", err)
|
||||
}
|
||||
out[chunkID] = append(out[chunkID], rowLocation{table: table, id: id})
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
_ = rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
_ = rows.Close()
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package doris
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"net/http"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// dorisRepository 是 Apache Doris 4.1 的检索引擎仓储实现。
|
||||
//
|
||||
// 通信通道:
|
||||
// - 读写主链路:MySQL 协议(database/sql + go-sql-driver/mysql),FE 默认 9030 端口。
|
||||
// - Stream Load:HTTP(FE 默认 8030 端口),legacy 模式用于 partial update。
|
||||
//
|
||||
// 表结构按维度分表:<tableBaseName>_<dim>。
|
||||
// 兼容模式由 DORIS_COMPAT_MODE 决定:
|
||||
// - legacy:UNIQUE KEY(id) + cosine_distance ANN + Stream Load partial update
|
||||
// - inner_product_duplicate:DUPLICATE KEY(id) + normalized inner product + delete/insert rewrite
|
||||
//
|
||||
// 该设置在 embedding 表创建后不可直接互换;切换模式前需要重建这些表。
|
||||
//
|
||||
// 与 Qdrant/Milvus/Weaviate 一样,initializedTables 缓存"已确保存在"的维度,
|
||||
// 避免每次写入都打 SHOW TABLES。
|
||||
type dorisRepository struct {
|
||||
db *sql.DB
|
||||
|
||||
httpClient *http.Client
|
||||
// fe HTTP base,例如 "http://doris-fe:8030"。Stream Load 路径
|
||||
// 由 streamLoadURL(table) 拼接:<feHTTPBase>/api/<database>/<table>/_stream_load。
|
||||
feHTTPBase string
|
||||
|
||||
username string
|
||||
password string
|
||||
database string
|
||||
|
||||
tableBaseName string
|
||||
bucketsNum int // 0 -> default 10
|
||||
replicationNum int // 0 -> default 1
|
||||
compatModeRequested dorisCompatMode
|
||||
compatModeResolved dorisCompatMode
|
||||
compatResolveOnce sync.Once
|
||||
compatResolveErr error
|
||||
|
||||
// 已经确保过 ensureTable 的维度集合:dim -> true。
|
||||
initializedTables sync.Map
|
||||
}
|
||||
|
||||
// DorisVectorEmbedding 是落到 Doris 表里的一行的领域模型。
|
||||
//
|
||||
// 字段顺序与 schema.go 中的 INSERT 列序保持一致,
|
||||
// 调整时需要同时更新 createInsert 与 columns。
|
||||
type DorisVectorEmbedding struct {
|
||||
ID string
|
||||
Content string
|
||||
SourceID string
|
||||
SourceType int
|
||||
ChunkID string
|
||||
KnowledgeID string
|
||||
KnowledgeBaseID string
|
||||
TagID string
|
||||
IsEnabled bool
|
||||
Embedding []float32
|
||||
}
|
||||
|
||||
// DorisVectorEmbeddingWithScore 是检索结果的领域模型,
|
||||
// Score 在向量检索时按当前 compat mode 计算,在关键词检索时统一赋 1.0。
|
||||
type DorisVectorEmbeddingWithScore struct {
|
||||
DorisVectorEmbedding
|
||||
Score float64
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package elasticsearch
|
||||
|
||||
import (
|
||||
"maps"
|
||||
"slices"
|
||||
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// VectorEmbedding defines the Elasticsearch document structure for vector embeddings
|
||||
type VectorEmbedding struct {
|
||||
Content string `json:"content" gorm:"column:content;not null"` // Text content of the chunk
|
||||
SourceID string `json:"source_id" gorm:"column:source_id;not null"` // ID of the source document
|
||||
SourceType int `json:"source_type" gorm:"column:source_type;not null"` // Type of the source document
|
||||
ChunkID string `json:"chunk_id" gorm:"column:chunk_id"` // Unique ID of the text chunk
|
||||
KnowledgeID string `json:"knowledge_id" gorm:"column:knowledge_id"` // ID of the knowledge item
|
||||
KnowledgeBaseID string `json:"knowledge_base_id" gorm:"column:knowledge_base_id"` // ID of the knowledge base
|
||||
TagID string `json:"tag_id" gorm:"column:tag_id"` // Tag ID for categorization
|
||||
Embedding []float32 `json:"embedding" gorm:"column:embedding;not null"` // Vector embedding of the content
|
||||
IsEnabled bool `json:"is_enabled"` // Whether the chunk is enabled
|
||||
IsRecommended bool `json:"is_recommended"` // Whether the chunk is recommended
|
||||
}
|
||||
|
||||
// VectorEmbeddingWithScore extends VectorEmbedding with similarity score
|
||||
type VectorEmbeddingWithScore struct {
|
||||
VectorEmbedding
|
||||
Score float64 // Similarity score from vector search
|
||||
}
|
||||
|
||||
// ToDBVectorEmbedding converts IndexInfo to Elasticsearch document format
|
||||
func ToDBVectorEmbedding(embedding *types.IndexInfo, additionalParams map[string]interface{}) *VectorEmbedding {
|
||||
vector := &VectorEmbedding{
|
||||
Content: embedding.Content,
|
||||
SourceID: embedding.SourceID,
|
||||
SourceType: int(embedding.SourceType),
|
||||
ChunkID: embedding.ChunkID,
|
||||
KnowledgeID: embedding.KnowledgeID,
|
||||
KnowledgeBaseID: embedding.KnowledgeBaseID,
|
||||
TagID: embedding.TagID,
|
||||
IsEnabled: embedding.IsEnabled,
|
||||
IsRecommended: embedding.IsRecommended,
|
||||
}
|
||||
// Add embedding data if available in additionalParams
|
||||
if additionalParams != nil && slices.Contains(slices.Collect(maps.Keys(additionalParams)), "embedding") {
|
||||
if embeddingMap, ok := additionalParams["embedding"].(map[string][]float32); ok {
|
||||
vector.Embedding = embeddingMap[embedding.SourceID]
|
||||
}
|
||||
}
|
||||
// Get is_enabled from additionalParams if available
|
||||
if additionalParams != nil {
|
||||
if chunkEnabledMap, ok := additionalParams["chunk_enabled"].(map[string]bool); ok {
|
||||
if enabled, exists := chunkEnabledMap[embedding.ChunkID]; exists {
|
||||
vector.IsEnabled = enabled
|
||||
}
|
||||
}
|
||||
}
|
||||
return vector
|
||||
}
|
||||
|
||||
// FromDBVectorEmbeddingWithScore converts Elasticsearch document to IndexWithScore domain model
|
||||
func FromDBVectorEmbeddingWithScore(id string,
|
||||
embedding *VectorEmbeddingWithScore,
|
||||
matchType types.MatchType,
|
||||
) *types.IndexWithScore {
|
||||
return &types.IndexWithScore{
|
||||
ID: id,
|
||||
SourceID: embedding.SourceID,
|
||||
SourceType: types.SourceType(embedding.SourceType),
|
||||
ChunkID: embedding.ChunkID,
|
||||
KnowledgeID: embedding.KnowledgeID,
|
||||
KnowledgeBaseID: embedding.KnowledgeBaseID,
|
||||
TagID: embedding.TagID,
|
||||
Content: embedding.Content,
|
||||
Score: embedding.Score,
|
||||
MatchType: matchType,
|
||||
IsEnabled: embedding.IsEnabled,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package v7
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
typesLocal "academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"github.com/elastic/go-elasticsearch/v7"
|
||||
)
|
||||
|
||||
// bulkReasonSentinel stands for document content that a per-item error.reason
|
||||
// can carry; the error returned to the caller must never include it.
|
||||
const bulkReasonSentinel = "LEAK-SENTINEL-DOC-BODY"
|
||||
|
||||
// fakeBulkServer answers every request the v7 repository makes while BatchSave
|
||||
// runs, and returns body for the _bulk call.
|
||||
type fakeBulkServer struct {
|
||||
body string
|
||||
calls int
|
||||
}
|
||||
|
||||
func (f *fakeBulkServer) handler() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch {
|
||||
case strings.HasSuffix(r.URL.Path, "/_bulk"):
|
||||
f.calls++
|
||||
_, _ = io.WriteString(w, f.body)
|
||||
case strings.HasSuffix(r.URL.Path, "/_mapping"):
|
||||
_, _ = io.WriteString(w,
|
||||
`{"xwrag_default":{"mappings":{"properties":{"chunk_id":{"type":"keyword"}}}}}`)
|
||||
case r.Method == http.MethodHead:
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
default:
|
||||
_, _ = io.WriteString(w,
|
||||
`{"acknowledged":true,"shards_acknowledged":true,"index":"xwrag_default"}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// newBulkTestRepository builds the repository through its public constructor
|
||||
// against a fake Elasticsearch that answers _bulk with body.
|
||||
func newBulkTestRepository(t *testing.T, body string) (interfaces.RetrieveEngineRepository, *fakeBulkServer) {
|
||||
t.Helper()
|
||||
|
||||
fake := &fakeBulkServer{body: body}
|
||||
server := httptest.NewServer(fake.handler())
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
client, err := elasticsearch.NewClient(
|
||||
elasticsearch.Config{Addresses: []string{server.URL}, DisableRetry: true},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
|
||||
return NewElasticsearchEngineRepository(client, nil, nil), fake
|
||||
}
|
||||
|
||||
func bulkTestIndexInfos() []*typesLocal.IndexInfo {
|
||||
return []*typesLocal.IndexInfo{
|
||||
{
|
||||
Content: "alpha", SourceID: "src-1", SourceType: typesLocal.ChunkSourceType,
|
||||
ChunkID: "chunk-1", KnowledgeID: "k-1", KnowledgeBaseID: "kb-1", IsEnabled: true,
|
||||
},
|
||||
{
|
||||
Content: "beta", SourceID: "src-2", SourceType: typesLocal.ChunkSourceType,
|
||||
ChunkID: "chunk-2", KnowledgeID: "k-1", KnowledgeBaseID: "kb-1", IsEnabled: true,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func bulkTestParams() map[string]any {
|
||||
return map[string]any{
|
||||
"embedding": map[string][]float32{"src-1": {0.1, 0.2}, "src-2": {0.3, 0.4}},
|
||||
}
|
||||
}
|
||||
|
||||
// TestBatchSaveReportsPerItemBulkErrors is a regression test for #3832:
|
||||
// Elasticsearch answers an accepted _bulk request with HTTP 200, so a document
|
||||
// rejected for a mapping mismatch, a read-only index or an item-level
|
||||
// rejection is visible only in the response body. BatchSave must surface those
|
||||
// per-item failures instead of logging a warning and reporting success.
|
||||
func TestBatchSaveReportsPerItemBulkErrors(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
body string
|
||||
wantContains []string
|
||||
}{
|
||||
{
|
||||
name: "all documents rejected",
|
||||
body: `{"took":1,"errors":true,"items":[` +
|
||||
`{"index":{"_id":"chunk-1","status":400,` +
|
||||
`"error":{"type":"mapper_parsing_exception","reason":"` + bulkReasonSentinel + `"}}},` +
|
||||
`{"index":{"_id":"chunk-2","status":429,` +
|
||||
`"error":{"type":"es_rejected_execution_exception","reason":"` + bulkReasonSentinel + `"}}}]}`,
|
||||
wantContains: []string{
|
||||
"2/2 documents failed",
|
||||
"chunk-1", "mapper_parsing_exception",
|
||||
"chunk-2", "es_rejected_execution_exception",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "partial failure",
|
||||
body: `{"took":1,"errors":true,"items":[` +
|
||||
`{"index":{"_id":"chunk-1","status":201,"result":"created"}},` +
|
||||
`{"index":{"_id":"chunk-2","status":400,` +
|
||||
`"error":{"type":"cluster_block_exception","reason":"` + bulkReasonSentinel + `"}}}]}`,
|
||||
wantContains: []string{"1/2 documents failed", "chunk-2", "cluster_block_exception"},
|
||||
},
|
||||
{
|
||||
name: "malformed response body",
|
||||
body: `{"took":1`,
|
||||
wantContains: []string{"failed to parse bulk response"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
repo, fake := newBulkTestRepository(t, tc.body)
|
||||
|
||||
err := repo.BatchSave(context.Background(), bulkTestIndexInfos(), bulkTestParams())
|
||||
|
||||
require.Positive(t, fake.calls, "the _bulk endpoint was never called")
|
||||
require.Error(t, err)
|
||||
for _, want := range tc.wantContains {
|
||||
assert.Contains(t, err.Error(), want)
|
||||
}
|
||||
assert.NotContains(t, err.Error(), bulkReasonSentinel,
|
||||
"the returned error must not carry error.reason")
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("all documents accepted", func(t *testing.T) {
|
||||
repo, fake := newBulkTestRepository(t, `{"took":1,"errors":false,"items":[`+
|
||||
`{"index":{"_id":"chunk-1","status":201,"result":"created"}},`+
|
||||
`{"index":{"_id":"chunk-2","status":201,"result":"created"}}]}`)
|
||||
|
||||
err := repo.BatchSave(context.Background(), bulkTestIndexInfos(), bulkTestParams())
|
||||
|
||||
require.Positive(t, fake.calls, "the _bulk endpoint was never called")
|
||||
require.NoError(t, err)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package v7
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/elastic/go-elasticsearch/v7"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// copySourceHits covers every source_id shape CopyIndices remaps: a regular
|
||||
// chunk row, a generated-question row sharing that chunk, a row with an
|
||||
// unrelated source_id (remapped to a fresh uuid), and a legacy row written
|
||||
// before is_enabled existed.
|
||||
const copySourceHits = `[
|
||||
{"_index":"vectors","_id":"d1","_score":1,"_source":{"content":"chunk","source_id":"c1","source_type":0,
|
||||
"chunk_id":"c1","knowledge_id":"k1","knowledge_base_id":"kb-src","embedding":[0.1,0.2],"is_enabled":true}},
|
||||
{"_index":"vectors","_id":"d2","_score":1,"_source":{"content":"question","source_id":"c1-q1","source_type":1,
|
||||
"chunk_id":"c1","knowledge_id":"k1","knowledge_base_id":"kb-src","embedding":[0.3,0.4],"is_enabled":true}},
|
||||
{"_index":"vectors","_id":"d3","_score":1,"_source":{"content":"summary","source_id":"img-9","source_type":2,
|
||||
"chunk_id":"c2","knowledge_id":"k1","knowledge_base_id":"kb-src","embedding":[0.5,0.6],"is_enabled":false}},
|
||||
{"_index":"vectors","_id":"d4","_score":1,"_source":{"content":"legacy","source_id":"c3","source_type":0,
|
||||
"chunk_id":"c3","knowledge_id":"k1","knowledge_base_id":"kb-src","embedding":[0.7,0.8]}}
|
||||
]`
|
||||
|
||||
type copiedDoc struct {
|
||||
Content string `json:"content"`
|
||||
SourceID string `json:"source_id"`
|
||||
SourceType int `json:"source_type"`
|
||||
ChunkID string `json:"chunk_id"`
|
||||
KnowledgeID string `json:"knowledge_id"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||
Embedding []float32 `json:"embedding"`
|
||||
IsEnabled *bool `json:"is_enabled"`
|
||||
}
|
||||
|
||||
// fakeCopyServer serves one page of copySourceHits and records the search
|
||||
// query and every document sent through _bulk.
|
||||
type fakeCopyServer struct {
|
||||
mu sync.Mutex
|
||||
searchQuery string
|
||||
docs []copiedDoc
|
||||
}
|
||||
|
||||
func (f *fakeCopyServer) handler(t *testing.T) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("X-Elastic-Product", "Elasticsearch")
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
switch r.URL.Path {
|
||||
case "/":
|
||||
_, _ = w.Write([]byte(`{"version":{"number":"7.17.0","build_flavor":"default"},` +
|
||||
`"tagline":"You Know, for Search"}`))
|
||||
case "/vectors/_search":
|
||||
f.searchQuery = string(body)
|
||||
_, _ = w.Write([]byte(`{"took":1,"timed_out":false,` +
|
||||
`"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},` +
|
||||
`"hits":{"total":{"value":4,"relation":"eq"},"hits":` + copySourceHits + `}}`))
|
||||
case "/vectors/_bulk":
|
||||
sc := bufio.NewScanner(bytes.NewReader(body))
|
||||
sc.Buffer(make([]byte, 0, 1<<20), 1<<20)
|
||||
for sc.Scan() {
|
||||
line := sc.Bytes()
|
||||
var probe map[string]json.RawMessage
|
||||
require.NoError(t, json.Unmarshal(line, &probe))
|
||||
if _, ok := probe["content"]; !ok {
|
||||
continue // action line
|
||||
}
|
||||
var doc copiedDoc
|
||||
require.NoError(t, json.Unmarshal(line, &doc))
|
||||
f.docs = append(f.docs, doc)
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"took":1,"errors":false,"items":[]}`))
|
||||
default:
|
||||
t.Errorf("unexpected path: %s", r.URL.Path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCopyIndicesKeepsVectorsAndEnabledState(t *testing.T) {
|
||||
fake := &fakeCopyServer{}
|
||||
server := httptest.NewServer(fake.handler(t))
|
||||
defer server.Close()
|
||||
client, err := elasticsearch.NewClient(
|
||||
elasticsearch.Config{Addresses: []string{server.URL}, DisableRetry: true},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
repo := &elasticsearchRepository{client: client, index: "vectors"}
|
||||
|
||||
err = repo.CopyIndices(context.Background(), "kb-src",
|
||||
map[string]string{"k1": "tk1"},
|
||||
map[string]string{"c1": "t1", "c2": "t2", "c3": "t3"},
|
||||
"kb-dst", 2, "manual")
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.NotContains(t, fake.searchQuery, "is_enabled",
|
||||
"the copy scan must include disabled source rows so they stay disabled, not vanish")
|
||||
|
||||
require.Len(t, fake.docs, 4)
|
||||
byContent := make(map[string]copiedDoc, len(fake.docs))
|
||||
for _, d := range fake.docs {
|
||||
byContent[d.Content] = d
|
||||
assert.Equal(t, "tk1", d.KnowledgeID)
|
||||
assert.Equal(t, "kb-dst", d.KnowledgeBaseID)
|
||||
require.NotNil(t, d.IsEnabled, "is_enabled must be written for %q", d.Content)
|
||||
}
|
||||
|
||||
chunk := byContent["chunk"]
|
||||
assert.Equal(t, "t1", chunk.ChunkID)
|
||||
assert.Equal(t, "t1", chunk.SourceID)
|
||||
assert.Equal(t, 0, chunk.SourceType)
|
||||
assert.Equal(t, []float32{0.1, 0.2}, chunk.Embedding)
|
||||
assert.True(t, *chunk.IsEnabled)
|
||||
|
||||
question := byContent["question"]
|
||||
assert.Equal(t, "t1", question.ChunkID)
|
||||
assert.Equal(t, "t1-q1", question.SourceID)
|
||||
assert.Equal(t, 1, question.SourceType)
|
||||
assert.Equal(t, []float32{0.3, 0.4}, question.Embedding)
|
||||
assert.True(t, *question.IsEnabled)
|
||||
|
||||
summary := byContent["summary"]
|
||||
assert.Equal(t, "t2", summary.ChunkID)
|
||||
assert.NotEqual(t, "img-9", summary.SourceID)
|
||||
assert.False(t, strings.HasPrefix(summary.SourceID, "t2"), "unrelated source ids get a fresh uuid")
|
||||
assert.Equal(t, 2, summary.SourceType)
|
||||
assert.Equal(t, []float32{0.5, 0.6}, summary.Embedding)
|
||||
assert.False(t, *summary.IsEnabled)
|
||||
|
||||
legacy := byContent["legacy"]
|
||||
assert.Equal(t, "t3", legacy.SourceID)
|
||||
assert.Equal(t, []float32{0.7, 0.8}, legacy.Embedding)
|
||||
assert.True(t, *legacy.IsEnabled, "a source row without is_enabled is enabled for retrieval")
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package v7
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func (e *elasticsearchRepository) MoveKnowledgeIndices(
|
||||
ctx context.Context,
|
||||
sourceKB, targetKB, knowledgeID string,
|
||||
_ []string,
|
||||
_ int,
|
||||
_ string,
|
||||
) error {
|
||||
body, err := json.Marshal(map[string]any{
|
||||
"query": map[string]any{"bool": map[string]any{"filter": []any{
|
||||
map[string]any{"term": map[string]any{e.idField("knowledge_base_id"): sourceKB}},
|
||||
map[string]any{"term": map[string]any{e.idField("knowledge_id"): knowledgeID}},
|
||||
}}},
|
||||
"script": map[string]any{
|
||||
"lang": "painless",
|
||||
"source": "ctx._source.knowledge_base_id = params.target; ctx._source.tag_id = ''",
|
||||
"params": map[string]any{"target": targetKB},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := e.client.UpdateByQuery(
|
||||
[]string{e.index},
|
||||
e.client.UpdateByQuery.WithContext(ctx),
|
||||
e.client.UpdateByQuery.WithBody(bytes.NewReader(body)),
|
||||
e.client.UpdateByQuery.WithRefresh(true),
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
if resp.IsError() {
|
||||
return fmt.Errorf("move indices: %s", resp.String())
|
||||
}
|
||||
var result struct {
|
||||
Total *int64 `json:"total"`
|
||||
Updated *int64 `json:"updated"`
|
||||
TimedOut bool `json:"timed_out"`
|
||||
Conflicts int `json:"version_conflicts"`
|
||||
Failures []json.RawMessage `json:"failures"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
return err
|
||||
}
|
||||
if result.Total == nil || result.Updated == nil || *result.Total < 0 || *result.Total != *result.Updated ||
|
||||
result.TimedOut || result.Conflicts != 0 || len(result.Failures) != 0 {
|
||||
return fmt.Errorf("move indices was incomplete")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package v7
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/elastic/go-elasticsearch/v7"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestMoveIndicesRequiresCompleteCounts(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name, body string
|
||||
fails bool
|
||||
}{
|
||||
{"complete", `{"total":100,"updated":100}`, false},
|
||||
{"empty retry", `{"total":0,"updated":0}`, false},
|
||||
{"partial", `{"total":100,"updated":40}`, true},
|
||||
{"missing total", `{"updated":40}`, true},
|
||||
{"missing updated", `{"total":40}`, true},
|
||||
{"missing counts", `{}`, true},
|
||||
{"negative", `{"total":-1,"updated":-1}`, true},
|
||||
{"conflict", `{"total":1,"updated":1,"version_conflicts":1}`, true},
|
||||
{"timeout", `{"total":1,"updated":1,"timed_out":true}`, true},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("X-Elastic-Product", "Elasticsearch")
|
||||
if r.URL.Path == "/" {
|
||||
_, _ = w.Write(
|
||||
[]byte(
|
||||
`{"version":{"number":"7.17.0","build_flavor":"default"},"tagline":"You Know, for Search"}`,
|
||||
),
|
||||
)
|
||||
return
|
||||
}
|
||||
if r.URL.Path != "/vectors/_update_by_query" {
|
||||
t.Errorf("unexpected path: %s", r.URL.Path)
|
||||
}
|
||||
_, _ = w.Write([]byte(tt.body))
|
||||
}))
|
||||
defer server.Close()
|
||||
client, err := elasticsearch.NewClient(
|
||||
elasticsearch.Config{Addresses: []string{server.URL}, DisableRetry: true},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
repo := &elasticsearchRepository{client: client, index: "vectors"}
|
||||
err = repo.MoveKnowledgeIndices(context.Background(), "source", "target", "doc", nil, 3, "file")
|
||||
if tt.fails {
|
||||
require.Error(t, err)
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+52
@@ -0,0 +1,52 @@
|
||||
package v7
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
typesLocal "academy/internal/types"
|
||||
)
|
||||
|
||||
// Regression test for #3156: the script_score source must floor the cosine
|
||||
// similarity at 0. An unclamped negative cosine makes Lucene reject the whole
|
||||
// search request ("script_score script returned an invalid score ... Must be a
|
||||
// non-negative score!"), turning one dissimilar document into a full vector
|
||||
// retrieval outage (all shards failed).
|
||||
func TestVectorScoreScriptSourceClampsNegativeCosine(t *testing.T) {
|
||||
require.Equal(t,
|
||||
"Math.max(cosineSimilarity(params.query_vector,'embedding'), 0.0)",
|
||||
vectorScoreScriptSource)
|
||||
}
|
||||
|
||||
// The marshaled query body must carry the clamped script source end to end.
|
||||
func TestBuildVectorSearchQueryClampsScriptScore(t *testing.T) {
|
||||
e := &elasticsearchRepository{}
|
||||
params := typesLocal.RetrieveParams{
|
||||
Embedding: []float32{-1, 0},
|
||||
Threshold: 0.15,
|
||||
TopK: 5,
|
||||
KnowledgeBaseIDs: []string{"kb-1"},
|
||||
}
|
||||
|
||||
query, err := e.buildVectorSearchQuery(context.Background(), params)
|
||||
require.NoError(t, err)
|
||||
|
||||
var body struct {
|
||||
Query struct {
|
||||
ScriptScore struct {
|
||||
Script struct {
|
||||
Source string `json:"source"`
|
||||
} `json:"script"`
|
||||
MinScore float64 `json:"min_score"`
|
||||
} `json:"script_score"`
|
||||
} `json:"query"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal([]byte(query), &body))
|
||||
require.Equal(t,
|
||||
"Math.max(cosineSimilarity(params.query_vector,'embedding'), 0.0)",
|
||||
body.Query.ScriptScore.Script.Source)
|
||||
require.InDelta(t, 0.15, body.Query.ScriptScore.MinScore, 1e-6)
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package v8
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
typesLocal "academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"github.com/elastic/go-elasticsearch/v8"
|
||||
)
|
||||
|
||||
// bulkReasonSentinel stands for document content that a per-item error.reason
|
||||
// can carry; the error returned to the caller must never include it.
|
||||
const bulkReasonSentinel = "LEAK-SENTINEL-DOC-BODY"
|
||||
|
||||
// fakeBulkServer answers every request the v8 repository makes while BatchSave
|
||||
// runs, and returns body for the _bulk call.
|
||||
type fakeBulkServer struct {
|
||||
body string
|
||||
calls int
|
||||
}
|
||||
|
||||
func (f *fakeBulkServer) handler() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("X-Elastic-Product", "Elasticsearch")
|
||||
switch {
|
||||
case strings.HasSuffix(r.URL.Path, "/_bulk"):
|
||||
f.calls++
|
||||
_, _ = io.WriteString(w, f.body)
|
||||
case strings.HasSuffix(r.URL.Path, "/_mapping"):
|
||||
_, _ = io.WriteString(w,
|
||||
`{"xwrag_default":{"mappings":{"properties":{"chunk_id":{"type":"keyword"}}}}}`)
|
||||
case r.Method == http.MethodHead:
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
default:
|
||||
_, _ = io.WriteString(w,
|
||||
`{"acknowledged":true,"shards_acknowledged":true,"index":"xwrag_default"}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// newBulkTestRepository builds the repository through its public constructor
|
||||
// against a fake Elasticsearch that answers _bulk with body.
|
||||
func newBulkTestRepository(t *testing.T, body string) (interfaces.RetrieveEngineRepository, *fakeBulkServer) {
|
||||
t.Helper()
|
||||
|
||||
fake := &fakeBulkServer{body: body}
|
||||
server := httptest.NewServer(fake.handler())
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
client, err := elasticsearch.NewTypedClient(
|
||||
elasticsearch.Config{Addresses: []string{server.URL}, DisableRetry: true},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
|
||||
return NewElasticsearchEngineRepository(client, nil, nil), fake
|
||||
}
|
||||
|
||||
func bulkTestIndexInfos() []*typesLocal.IndexInfo {
|
||||
return []*typesLocal.IndexInfo{
|
||||
{
|
||||
Content: "alpha", SourceID: "src-1", SourceType: typesLocal.ChunkSourceType,
|
||||
ChunkID: "chunk-1", KnowledgeID: "k-1", KnowledgeBaseID: "kb-1", IsEnabled: true,
|
||||
},
|
||||
{
|
||||
Content: "beta", SourceID: "src-2", SourceType: typesLocal.ChunkSourceType,
|
||||
ChunkID: "chunk-2", KnowledgeID: "k-1", KnowledgeBaseID: "kb-1", IsEnabled: true,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func bulkTestParams() map[string]any {
|
||||
return map[string]any{
|
||||
"embedding": map[string][]float32{"src-1": {0.1, 0.2}, "src-2": {0.3, 0.4}},
|
||||
}
|
||||
}
|
||||
|
||||
// TestBatchSaveReportsPerItemBulkErrors is a regression test for #3832:
|
||||
// Elasticsearch answers an accepted _bulk request with HTTP 200, so a document
|
||||
// rejected for a mapping mismatch, a read-only index or an item-level
|
||||
// rejection is visible only in the response body. BatchSave must surface those
|
||||
// per-item failures to the caller.
|
||||
func TestBatchSaveReportsPerItemBulkErrors(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
body string
|
||||
wantContains []string
|
||||
}{
|
||||
{
|
||||
name: "all documents rejected",
|
||||
body: `{"took":1,"errors":true,"items":[` +
|
||||
`{"create":{"_id":"chunk-1","status":400,` +
|
||||
`"error":{"type":"mapper_parsing_exception","reason":"` + bulkReasonSentinel + `"}}},` +
|
||||
`{"create":{"_id":"chunk-2","status":429,` +
|
||||
`"error":{"type":"es_rejected_execution_exception","reason":"` + bulkReasonSentinel + `"}}}]}`,
|
||||
wantContains: []string{
|
||||
"2/2 documents failed",
|
||||
"chunk-1", "mapper_parsing_exception",
|
||||
"chunk-2", "es_rejected_execution_exception",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "partial failure",
|
||||
body: `{"took":1,"errors":true,"items":[` +
|
||||
`{"create":{"_id":"chunk-1","status":201,"result":"created"}},` +
|
||||
`{"create":{"_id":"chunk-2","status":400,` +
|
||||
`"error":{"type":"cluster_block_exception","reason":"` + bulkReasonSentinel + `"}}}]}`,
|
||||
wantContains: []string{"1/2 documents failed", "chunk-2", "cluster_block_exception"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
repo, fake := newBulkTestRepository(t, tc.body)
|
||||
|
||||
err := repo.BatchSave(context.Background(), bulkTestIndexInfos(), bulkTestParams())
|
||||
|
||||
require.Positive(t, fake.calls, "the _bulk endpoint was never called")
|
||||
require.Error(t, err)
|
||||
for _, want := range tc.wantContains {
|
||||
assert.Contains(t, err.Error(), want)
|
||||
}
|
||||
assert.NotContains(t, err.Error(), bulkReasonSentinel,
|
||||
"the returned error must not carry error.reason")
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("all documents accepted", func(t *testing.T) {
|
||||
repo, fake := newBulkTestRepository(t, `{"took":1,"errors":false,"items":[`+
|
||||
`{"create":{"_id":"chunk-1","status":201,"result":"created"}},`+
|
||||
`{"create":{"_id":"chunk-2","status":201,"result":"created"}}]}`)
|
||||
|
||||
err := repo.BatchSave(context.Background(), bulkTestIndexInfos(), bulkTestParams())
|
||||
|
||||
require.Positive(t, fake.calls, "the _bulk endpoint was never called")
|
||||
require.NoError(t, err)
|
||||
})
|
||||
}
|
||||
Loaded 100 of 5767 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user