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,294 @@
|
||||
# Resource access boundaries
|
||||
|
||||
`access` contains shared permission resolution without depending on Gin or the
|
||||
application service implementations. HTTP adapters keep parameter parsing, status
|
||||
codes, RBAC rollout behavior, and response projection at their existing boundaries.
|
||||
|
||||
| Entry point | Shared rule | Additional boundary |
|
||||
| --- | --- | --- |
|
||||
| Resource mutations with URL/body KB selectors | `CheckOwnershipOrRole`: creator at Contributor or above, or sufficient tenant role | API-key capabilities, KB scope and tenant visibility remain separate checks |
|
||||
| KB/document detail and content routes | `ResolveKB`: own tenant, organization share, then read-only shared agent | Tenant role/ownership guards and API-key capabilities |
|
||||
| Shared documents, chunks, search targets and suggestions | `KBSharePermissions`: organization grants only | Existing user requirements and caller-specific filtering/error behavior |
|
||||
| FAQ and tag service reads | `resolveKBReadTenant`: execution tenant or organization share | Direct cross-tenant calls require a user; no implicit agent fallback |
|
||||
| KB list, document search and batch restoration with `agent_id` | Shared-agent lookup, then `SharedAgentKBScope` | API-key intersection; dynamic list/search selections also apply capability filtering |
|
||||
| Wiki fixer source tenant | Organization Editor permission | Built-in fixer only; exactly one KB |
|
||||
| Message file shared-KB fallback | Organization Viewer permission | Persisted message reference, exact resource handle, KB/resource owner match |
|
||||
| KB file proxy | `ResolveKBFile`: exact Viewer grant and current explicit KB binding | Owner tenant and exports namespace; original uploads retain their separate download permission |
|
||||
| Message file proxy | `ResolveMessageFile`: session ownership and exact persisted output reference | Current shared-agent or organization-KB permission for source-owned resources |
|
||||
| Message artifact download | `ResolveMessageArtifact`: session ownership and persisted artifact index | Session-owned output remains accessible; source-owned output rechecks current sharing |
|
||||
| FAQ and tag mutations | `RequireKBWrite`: exact Editor operation grant | API-key ingest capability and KB scope; tenant-role/creator checks remain at the admission boundary |
|
||||
|
||||
## Ownership and write roles
|
||||
|
||||
URL middleware and body-based handlers use the same lazy ownership decision.
|
||||
The middleware adapter resolves identity, RBAC rollout configuration and the
|
||||
configuration-gated superuser flag. API-key principals, sufficient roles,
|
||||
cross-tenant superusers and disabled enforcement skip the creator lookup.
|
||||
API keys still require their route capabilities and allowed KB scope.
|
||||
|
||||
When a lookup is needed, it must check tenant visibility before returning the
|
||||
creator. An empty creator never matches an empty user. Middleware passes missing
|
||||
resources to the handler, reports lookup failures as 503 and audits only actual
|
||||
policy denials. Body-based handlers retain their existing 404/403/500 mapping.
|
||||
KB, initialization, Wiki and body-based KB lookups share the same tenant check.
|
||||
|
||||
## Caller and resource tenant
|
||||
|
||||
`types.Caller` holds the authenticated tenant, user and tenant role. Auth records
|
||||
it once; `KBRequest.Caller` and `KBAccess.Caller` use that same identity. The
|
||||
legacy `TenantIDContextKey` continues to scope repository/model execution, so
|
||||
existing storage APIs do not need a coordinated signature migration.
|
||||
|
||||
Use `types.WithExecutionTenant` to switch execution tenants. It captures the
|
||||
caller first, even when identity is missing, and grants no access by itself.
|
||||
Use `KBAccess.Context` after authorization to carry both the exact KB grant and
|
||||
its execution tenant, or `WithGrant` to carry the grant without switching yet.
|
||||
Grants bind the KB ID, owner tenant, caller and resolved permission; changing
|
||||
execution tenant cannot turn a Viewer grant into Editor or expose another KB.
|
||||
HTTP adapters retain Gin's caller keys for existing handlers.
|
||||
|
||||
Service reads use `KBPermissions` to check caller ownership, exact upstream
|
||||
grants, then organization shares for the original caller. This check also applies
|
||||
to documents/chunks returned by the initial tenant-scoped batch query, not just
|
||||
rows found during cross-tenant expansion. Search preflight, result enrichment,
|
||||
FAQ/tag reads, search targets and suggestion scopes follow the same boundary.
|
||||
General document search enumerates the caller's own/shared KBs; its execution
|
||||
tenant is not a new identity.
|
||||
|
||||
After authorizing a shared agent, `WithSharedAgent` carries its configured,
|
||||
source-tenant-bound read scope into the pipeline. An arbitrary execution switch
|
||||
cannot substitute for that grant. `logger.CloneContext` preserves the caller and
|
||||
resource grants for detached work within the operation. Context grants contain
|
||||
immutable snapshots; deriving a context does not mutate a sibling search branch.
|
||||
They are not persisted as authority for subsequent requests. API-key scope is
|
||||
reapplied when consuming any grant.
|
||||
|
||||
## Organization shares
|
||||
|
||||
`KBSharePermissions` fixes the caller tenant and role for one operation and caches
|
||||
the granular decision per KB. Reading many documents/chunks from one KB therefore
|
||||
queries its membership once. Both denied decisions and errors are cached within
|
||||
that operation. The next request creates a new resolver and observes revocations.
|
||||
The resolver is not a process-wide cache and is not shared between goroutines.
|
||||
|
||||
The share service remains responsible for the role cap across share permission,
|
||||
organization membership and caller tenant role. The resolver returns lookup errors
|
||||
so strict search preflight can report an infrastructure failure while best-effort
|
||||
result expansion can omit inaccessible rows. `ResolveKB` retains its independent
|
||||
read-only agent fallback when organization resolution cannot grant access.
|
||||
|
||||
## Shared-agent KB scope
|
||||
|
||||
A scope is created only after looking up an accessible shared agent. `all` means
|
||||
all KBs in that agent's tenant; `selected` means its explicit nonempty ID set.
|
||||
`none`, unknown modes and empty selections authorize no KBs. A nil/empty ID slice
|
||||
never implicitly grants an entire tenant. Specifying an agent does not permit
|
||||
falling back to a different shared agent.
|
||||
|
||||
These rules do not replace message/session ownership, persisted file-reference
|
||||
validation, resource binding, Agent tool search-target restrictions, or embed/IM
|
||||
capability checks. Raw tenant files and message files have different authorization
|
||||
contracts and must not be admitted by a generic KB grant alone.
|
||||
|
||||
## FAQ and tag writes
|
||||
|
||||
FAQ/tag service mutations consume an explicit Editor grant; setting an execution
|
||||
tenant or supplying a KB ID is insufficient. `ResolveKB` keeps the effective
|
||||
permission used for response projection, but caps its context grant to the
|
||||
requested operation. Thus an owner read does not mint a reusable write grant.
|
||||
HTTP routes retain their existing role/creator admission checks. API-key ingest
|
||||
capability and KB scope are reapplied when consuming a write grant.
|
||||
|
||||
Trusted FAQ-import, data-source sync and automatic-tagging workers use
|
||||
`WithKBTaskWrite` after loading and validating their target KB and child-resource
|
||||
bindings. This represents continuation of an admitted job, not renewed user
|
||||
authorization on every retry. It carries exactly one KB, preserves the caller
|
||||
or its absence, survives in-operation context cloning, and grants no tenant-wide
|
||||
role. Services use the KB owner's TenantInfo for model/index configuration.
|
||||
|
||||
Batch FAQ updates resolve all source/destination tags, entries and exclusions
|
||||
before mutation. Batch deletion also resolves all parent documents first.
|
||||
Tag-only batch updates use the same plan. Tag groups execute in ascending seq_id
|
||||
order, then explicit entry updates override only their specified fields.
|
||||
Import retains per-entry content-validation results, but out-of-scope resource
|
||||
references are rejected before admission and checked again in the worker.
|
||||
This preflight prevents partial writes caused by invalid resource selections;
|
||||
it does not add a transaction across the database, task queue and search index.
|
||||
|
||||
## File authorization and transport
|
||||
|
||||
File resolvers return request-local `FileAccess` locators before any storage
|
||||
reader is opened. The KB catalog accepts only explicit resource bindings to live
|
||||
documents in the exact live KB. Registered physical aliases resolve to the same
|
||||
resource ID; chunk/wiki text is never authorization evidence. Historical files
|
||||
without explicit bindings fail closed and need a trusted migration. A same-tenant
|
||||
path or handle prefix cannot replace a KB binding. Message evidence comes from
|
||||
persisted content, references, images, artifacts and tool results; tool arguments
|
||||
do not prove that the message returned a file. The organization-shared KB
|
||||
fallback also checks the catalog for an independent live KB/file binding;
|
||||
retrieval text and a currently shared KB ID alone are insufficient.
|
||||
|
||||
Source-owned shared-agent files also require the current live agent share.
|
||||
KB sources need an explicit live KB binding allowed by the agent's current
|
||||
`all`/`selected` selection and the caller's API-key KB scope; `none`, unknown
|
||||
modes, removed KB selections and deleted sources fail closed. Independently
|
||||
generated artifacts remain accessible when explicitly bound to the exact
|
||||
authorized message as an artifact. Mentioning a file in message text or the
|
||||
artifact list does not create that binding. Caller-owned artifacts retain their
|
||||
session ownership contract.
|
||||
|
||||
The storage adapter uses the authorized owner and backend. The shared
|
||||
`filetransport` package owns response headers, safe inline/download disposition,
|
||||
streaming and reader closure. Seekable readers use standard HTTP Range and HEAD
|
||||
handling; streaming-only backends return full content with `Accept-Ranges: none`
|
||||
without buffering the object (RFC 9110 sections 14.2 and 14.3). Permission-controlled responses use `private, no-store` so a later
|
||||
request rechecks current access. Tenant-wide and signed-token file routes keep
|
||||
their own authorization and caching contracts.
|
||||
|
||||
## Document and chunk writes
|
||||
|
||||
Document metadata, manual content, reparse, document tags/folders, image edits, chunk mutations
|
||||
and generated-question edits consume explicit Editor grants after loading the
|
||||
persisted document/KB binding. Full chunk objects cannot reparent existing rows.
|
||||
Batch inputs are deduplicated and fully validated, including missing IDs and
|
||||
each KB's grant, before writes. Text edits also check the parent/image-child
|
||||
relationships that they will modify. Body-based HTTP routes explicitly resolve
|
||||
an Editor operation; a previously cached owner read is not a write admission.
|
||||
|
||||
Document deletion shares a preflight plan and executor for single and batch
|
||||
calls. The plan validates every selection and KB, loads owner TenantInfo and
|
||||
routing metadata, and captures image references before marking rows as deleting.
|
||||
Index/graph failures leave the document and original file available for retry.
|
||||
Wiki deletion collects all chunk types before deleting chunks, so parent, image
|
||||
and summary citations are removed along with text citations.
|
||||
Physical file cleanup remains best effort after database deletion; this does not
|
||||
introduce a transaction across database, indexes and storage or durable blob GC.
|
||||
|
||||
New queued deletion payloads pin `knowledge_base_id` as well as tenant and exact
|
||||
document IDs. Workers consume a private cleanup scope bound to those references,
|
||||
not general KB write permission; already deleted IDs are successful no-ops.
|
||||
A moved document rejects the batch before side effects. Pre-upgrade payloads that
|
||||
omit the KB are accepted only when remaining rows resolve to one same-tenant KB;
|
||||
they cannot reconstruct the KB that existed at enqueue time. Failure callbacks
|
||||
skip rejected scopes and condition status updates on tenant, KB and deleting
|
||||
state. Scope/identity errors are not retried; infrastructure failures are.
|
||||
|
||||
Single/batch delete, clear-content and batch-reparse admission reject already
|
||||
moving documents with HTTP 409 before enqueue. Workers recheck current state;
|
||||
a deletion conflict is terminal for that admitted task, so retries cannot
|
||||
follow a document into a different KB. This does not serialize admission with
|
||||
a concurrent move. Synchronous metadata/image/chunk/summary handlers preserve
|
||||
application 403/409 errors, including wrapped errors.
|
||||
|
||||
Batch reparse and batch document tags resolve an Editor operation and apply the
|
||||
same creator-or-Admin admission policy as single-document writes, respecting
|
||||
RBAC rollout/API-key behavior. Batch reparse payloads likewise carry the admitted
|
||||
KB ID. Workers validate the whole batch before any submission and use exactly one `WithKBTaskWrite` grant;
|
||||
each reparse reload consumes that grant and rejects a document still moving.
|
||||
Missing/mixed/moved selections fail without submitting earlier batch members.
|
||||
Legacy reparse payloads can reconstruct only a present, single-KB binding.
|
||||
|
||||
Session-history, temporary-KB and clone cleanup use exact server-derived
|
||||
references from their already admitted operations. These cleanup contexts cannot
|
||||
be used for document/chunk updates or additional IDs. Parsing and enrichment
|
||||
workers use repositories for their internal persistence and rollback; they must
|
||||
keep their existing task ownership checks, abort checks and resource bindings.
|
||||
Repository access is not an incoming-request authorization API.
|
||||
|
||||
## Clone and move operations
|
||||
|
||||
`WithKBTransfer` admits the exact source/target pair after HTTP role/creator
|
||||
checks. Clone consumes source Viewer, target Editor and the API-key
|
||||
`manage_kbs` capability; move consumes Editor on both sides and `ingest`.
|
||||
Both operations remain within one tenant. Creating a clone reserves its target
|
||||
ID before enqueue and carries its creator into the worker. The ID of a new
|
||||
resource is not checked against an existing-resource API-key allow-list.
|
||||
|
||||
Workers reload both KBs, validate their owners and consume a private pair grant.
|
||||
Document/FAQ plans validate all selected resources, chunks, parents and tags
|
||||
before destructive work. Lifecycle reads include every chunk type and indexing
|
||||
state. A document's `_knowledge_transfer` metadata records task identity and
|
||||
progress; retries reuse the reserved target, replace incomplete clones, skip
|
||||
completed vector moves and retry outstanding wiki cleanup/parser enqueue.
|
||||
This field is internal operation state, not caller-supplied custom metadata.
|
||||
For `reparse`, transfer `done` means target binding and parser admission are
|
||||
complete, not that parsing has finished. `ParseStatus` remains the parser's
|
||||
state. `reparse_pending` already admits the target parser; extending the
|
||||
`moving` write guard to that phase would also block legitimate worker writes.
|
||||
Locking all writes until parsing finishes is a separate processing/concurrency
|
||||
contract, including ordinary reparses, and is not provided by this transfer marker.
|
||||
|
||||
Failed clone chunk/index writes attempt rollback after conditionally claiming
|
||||
the original destination. Rollback failures are returned, references retained
|
||||
when cleanup is uncertain, and later retries replace the failed copy. Accounting
|
||||
is committed only after the clone succeeds. FAQ containers do not inherit the
|
||||
source document's transfer marker.
|
||||
|
||||
Source wiki cleanup starts only after the document ownership CAS succeeds.
|
||||
The transfer checkpoint preserves source chunk IDs and summary before reparse
|
||||
removes them. Retract page lists are persisted before page source refs are removed, so queue
|
||||
failures retain retry evidence. Cleanup errors propagate; redelivery resumes cleanup after a
|
||||
committed move without repeating vector/chunk relocation. These retries do not
|
||||
provide a distributed transaction or recovery after retries are exhausted.
|
||||
|
||||
Vector reuse relocates KB metadata while preserving physical vector/chunk IDs.
|
||||
Weaviate and Milvus drain the first source-filtered page until a follow-up query
|
||||
is empty, avoiding offset limits/skipped rows. Repeated IDs or partial failures
|
||||
return errors and leave the document checkpoint pending for retry.
|
||||
OpenSearch selects the entire source KB/document pair, even without DB chunks,
|
||||
and rejects version conflicts, timeouts and partial failures before DB relocation.
|
||||
OpenSearch and Elasticsearch 7/8 require present non-negative `total`/`updated`
|
||||
counts with `updated == total`; their move scripts do not skip/delete documents.
|
||||
A zero/zero result allows a retry after metadata already reached the target.
|
||||
Reparse cleanup loads and validates the source KB before touching any backend,
|
||||
reusing its storage binding throughout; a failed/missing lookup cannot fall
|
||||
back to the tenant default store.
|
||||
Vector reuse never copies vectors and then deletes by the same document ID. Source and
|
||||
target must use the same vector store for reuse, and the same concrete file
|
||||
storage instance for either mode. Doris ANN tables cannot safely replace rows
|
||||
without a delete/insert gap, so their moves require `reparse`. Clone still
|
||||
requires compatible embedding models and vector stores; a move also retains
|
||||
the existing same-model requirement. This is not a cross-storage migration API.
|
||||
|
||||
Conditional document checkpoints bind tenant, KB, status and the stored update
|
||||
time. They keep storage accounting in the same database transaction and read
|
||||
back timestamp precision. Delete stops when its checkpoint no longer matches.
|
||||
Ordinary document/chunk writes reject a document in the `moving` phase. Parser
|
||||
admission and failure callbacks verify the task's persisted tenant/KB binding;
|
||||
table-summary failure cleanup also stops if its document changed.
|
||||
|
||||
## Follow-up work outside this refactor
|
||||
|
||||
These are separate follow-ups, not capabilities provided by this package:
|
||||
|
||||
1. **Complete worker contracts and concurrency control.** Audit enrichment,
|
||||
table-summary, multimodal, wiki and indexing workers end to end. Standardize
|
||||
payload resource bindings, processing-attempt IDs and conditional writes,
|
||||
including operations admitted before a concurrent move. Do not replace
|
||||
these checks with an execution-tenant switch or a blanket task write grant.
|
||||
2. **Durable recovery across systems.** Add a transactional outbox and explicit
|
||||
recovery/cancellation for exhausted transfer tasks. Current retries use the
|
||||
same admitted task identity; a new move request is not a resume API. Database,
|
||||
queue, vector, graph and blob operations are not one atomic transaction.
|
||||
Physical file cleanup remains best effort and needs durable garbage collection.
|
||||
3. **External-backend integration coverage.** Exercise clone/move, partial
|
||||
backend failures, retries, pagination and search/edit behavior against live
|
||||
PostgreSQL, Elasticsearch 7/8, OpenSearch, Qdrant, Milvus, Weaviate,
|
||||
TencentVectorDB and Doris. Local SQLite vector tests and backend compilation
|
||||
do not establish this coverage. Doris ANN vector reuse remains unsupported.
|
||||
4. **Finish service-layer migration.** Apply explicit operation grants to the
|
||||
remaining KB configuration/duplicate/delete, wiki and resource-administration
|
||||
service methods, preserving their existing route admission policies. Keep
|
||||
user/organization membership, embed, IM and signed-resource contracts separate.
|
||||
5. **Trusted legacy file migration.** Backfill historical file bindings from
|
||||
verified provenance, not arbitrary chunk/wiki mentions. Unbound historical
|
||||
files now fail closed; request-path text fallback has been removed. Migrate
|
||||
old queued payloads and transfer records without captured source wiki refs.
|
||||
A legacy delete task without a KB ID can reconstruct only its present
|
||||
unambiguous binding, not its original enqueue-time binding.
|
||||
|
||||
No public request schema or database column migration is required by this
|
||||
refactor. Internal service interfaces require operation contexts, queued payloads
|
||||
add optional scope fields, and malformed/out-of-scope batch selections now fail
|
||||
before mutation instead of being silently skipped. Callers must also handle a
|
||||
409 for document edits/deletes while a move is in progress.
|
||||
@@ -0,0 +1,94 @@
|
||||
package access
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// Context grants contain values, not mutable KB objects. Deriving a context
|
||||
// copies the grant slice so parallel search branches cannot widen each other.
|
||||
type kbGrant struct {
|
||||
caller types.Caller
|
||||
kbID string
|
||||
tenantID uint64
|
||||
permission types.OrgMemberRole
|
||||
task bool
|
||||
}
|
||||
|
||||
type agentGrant struct {
|
||||
caller types.Caller
|
||||
scope types.SharedAgentKBScope
|
||||
}
|
||||
|
||||
// WithSharedAgent scopes execution after the caller has authorized this exact
|
||||
// agent. Only its configured KBs receive read access; other source-tenant KBs
|
||||
// and the source tenant's organization memberships are not inherited.
|
||||
func WithSharedAgent(ctx context.Context, agent *types.CustomAgent) context.Context {
|
||||
grant := agentGrant{caller: types.CallerFromContext(ctx), scope: types.NewSharedAgentKBScope(agent)}
|
||||
ctx = context.WithValue(ctx, types.SharedAgentGrantContextKey, grant)
|
||||
if agent == nil {
|
||||
return ctx
|
||||
}
|
||||
return types.WithExecutionTenant(ctx, agent.TenantID)
|
||||
}
|
||||
|
||||
// HasKBGrant checks only previously resolved resource access. It never infers
|
||||
// ownership from the execution tenant, and always reapplies API-key scope.
|
||||
func HasKBGrant(ctx context.Context, kbID string, tenantID uint64, required types.OrgMemberRole) bool {
|
||||
if !required.IsValid() || types.AuthorizeTenantAPIKeyKnowledgeBases(ctx, kbID) != nil {
|
||||
return false
|
||||
}
|
||||
caller := types.CallerFromContext(ctx)
|
||||
if kbID == "" || tenantID == 0 {
|
||||
return false
|
||||
}
|
||||
grants, _ := ctx.Value(types.KBGrantsContextKey).([]kbGrant)
|
||||
for _, grant := range grants {
|
||||
if (caller.TenantID != 0 || grant.task) && grant.caller == caller && grant.kbID == kbID &&
|
||||
grant.tenantID == tenantID &&
|
||||
grant.permission.HasPermission(required) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
grant, ok := ctx.Value(types.SharedAgentGrantContextKey).(agentGrant)
|
||||
return ok && caller.TenantID != 0 && required == types.OrgRoleViewer && grant.caller == caller &&
|
||||
grant.scope.Allows(kbID, tenantID)
|
||||
}
|
||||
|
||||
// KBPermissions combines caller ownership, exact context grants and organization
|
||||
// shares for one service operation. Pass nil shares when that entry point does
|
||||
// not permit organization expansion (for example, a caller without a user).
|
||||
type KBPermissions struct {
|
||||
ctx context.Context
|
||||
caller types.Caller
|
||||
shares *KBSharePermissions
|
||||
}
|
||||
|
||||
// NewKBPermissions resolves reads for one caller and operation.
|
||||
func NewKBPermissions(ctx context.Context, shares KBShareLookup) *KBPermissions {
|
||||
caller := types.CallerFromContext(ctx)
|
||||
return &KBPermissions{
|
||||
ctx: ctx,
|
||||
caller: caller,
|
||||
shares: NewKBSharePermissions(ctx, shares, caller.TenantID, caller.Role),
|
||||
}
|
||||
}
|
||||
|
||||
// Check combines caller ownership, exact grants and organization sharing.
|
||||
func (p *KBPermissions) Check(kbID string, ownerTenantID uint64, required types.OrgMemberRole) (bool, error) {
|
||||
if kbID == "" || ownerTenantID == 0 || !required.IsValid() {
|
||||
return false, nil
|
||||
}
|
||||
if err := types.AuthorizeTenantAPIKeyKnowledgeBases(p.ctx, kbID); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if (p.caller.TenantID == ownerTenantID && required == types.OrgRoleViewer) ||
|
||||
HasKBGrant(p.ctx, kbID, ownerTenantID, required) {
|
||||
return true, nil
|
||||
}
|
||||
if p.caller.TenantID == 0 || p.caller.TenantID == ownerTenantID {
|
||||
return false, nil
|
||||
}
|
||||
return p.shares.Check(kbID, required)
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package access
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"academy/internal/logger"
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func callerContext() context.Context {
|
||||
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1))
|
||||
ctx = context.WithValue(ctx, types.UserIDContextKey, "user")
|
||||
return context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleContributor)
|
||||
}
|
||||
|
||||
func TestKBGrantSurvivesExecutionSwitchAndDetachWithoutWidening(t *testing.T) {
|
||||
ctx := callerContext()
|
||||
kb := &types.KnowledgeBase{ID: "shared", TenantID: 2}
|
||||
grant, err := ResolveKB(
|
||||
ctx,
|
||||
KBRequest{Caller: types.CallerFromContext(ctx)},
|
||||
kb,
|
||||
types.OrgRoleViewer,
|
||||
&shareLookup{permission: types.OrgRoleViewer},
|
||||
nil,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
ctx = grant.Context(ctx)
|
||||
require.Equal(t, uint64(2), types.MustTenantIDFromContext(ctx))
|
||||
ctx = logger.CloneContext(types.WithExecutionTenant(ctx, 3))
|
||||
require.Equal(
|
||||
t,
|
||||
types.Caller{TenantID: 1, UserID: "user", Role: types.TenantRoleContributor},
|
||||
types.CallerFromContext(ctx),
|
||||
)
|
||||
require.True(t, HasKBGrant(ctx, "shared", 2, types.OrgRoleViewer))
|
||||
// A later mutation of the service model cannot mutate the captured grant.
|
||||
kb.ID = "private"
|
||||
require.False(t, HasKBGrant(ctx, "private", 2, types.OrgRoleViewer))
|
||||
require.False(t, HasKBGrant(ctx, "shared", 3, types.OrgRoleViewer))
|
||||
require.False(t, HasKBGrant(ctx, "shared", 2, types.OrgRoleEditor))
|
||||
for _, caller := range []types.Caller{
|
||||
{TenantID: 9, UserID: "user", Role: types.TenantRoleContributor},
|
||||
{TenantID: 1, UserID: "other", Role: types.TenantRoleContributor},
|
||||
{TenantID: 1, UserID: "user", Role: types.TenantRoleViewer},
|
||||
} {
|
||||
otherCtx := types.WithCaller(ctx, caller)
|
||||
require.False(t, HasKBGrant(otherCtx, "shared", 2, types.OrgRoleViewer))
|
||||
require.Equal(
|
||||
t,
|
||||
caller,
|
||||
types.CallerFromContext(grant.Context(otherCtx)),
|
||||
"reusing a grant cannot impersonate its caller",
|
||||
)
|
||||
require.Equal(
|
||||
t,
|
||||
uint64(3),
|
||||
types.MustTenantIDFromContext(grant.Context(otherCtx)),
|
||||
"a caller mismatch must not change execution scope",
|
||||
)
|
||||
}
|
||||
narrowed := types.WithTenantAPIKeyScope(
|
||||
ctx,
|
||||
types.TenantAPIKeyScope{KnowledgeBaseIDs: types.StringArray{"another"}},
|
||||
)
|
||||
require.False(t, HasKBGrant(narrowed, "shared", 2, types.OrgRoleViewer))
|
||||
}
|
||||
|
||||
func TestExecutionTenantDoesNotGrantOwnershipOrChangeShareIdentity(t *testing.T) {
|
||||
ctx := types.WithExecutionTenant(callerContext(), 2)
|
||||
shares := &shareLookup{}
|
||||
allowed, err := NewKBPermissions(ctx, shares).Check("private", 2, types.OrgRoleViewer)
|
||||
require.NoError(t, err)
|
||||
require.False(t, allowed)
|
||||
require.Equal(t, uint64(1), shares.caller)
|
||||
require.Equal(t, types.TenantRoleContributor, shares.role)
|
||||
ctx = types.WithExecutionTenant(context.Background(), 2)
|
||||
allowed, err = NewKBPermissions(ctx, nil).Check("private", 2, types.OrgRoleViewer)
|
||||
require.NoError(t, err)
|
||||
require.False(t, allowed, "an absent caller must not become the execution tenant")
|
||||
}
|
||||
|
||||
func TestSharedAgentGrantPreservesConfiguredScopeAcrossDetach(t *testing.T) {
|
||||
for _, mode := range []string{"all", "selected", "none", "unknown"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
agent := &types.CustomAgent{
|
||||
TenantID: 2,
|
||||
Config: types.CustomAgentConfig{KBSelectionMode: mode, KnowledgeBases: []string{"selected"}},
|
||||
}
|
||||
ctx := logger.CloneContext(WithSharedAgent(callerContext(), agent))
|
||||
require.Equal(t, uint64(1), types.CallerFromContext(ctx).TenantID)
|
||||
require.Equal(t, uint64(2), types.MustTenantIDFromContext(ctx))
|
||||
require.Equal(t, mode == "all" || mode == "selected", HasKBGrant(ctx, "selected", 2, types.OrgRoleViewer))
|
||||
require.Equal(t, mode == "all", HasKBGrant(ctx, "other", 2, types.OrgRoleViewer))
|
||||
require.False(t, HasKBGrant(ctx, "selected", 3, types.OrgRoleViewer))
|
||||
require.False(t, HasKBGrant(ctx, "selected", 2, types.OrgRoleEditor))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestKBGrantBranchesRemainIndependent(t *testing.T) {
|
||||
base := callerContext()
|
||||
grant := &KBAccess{Caller: types.CallerFromContext(base), EffectiveTenantID: 2, Permission: types.OrgRoleViewer}
|
||||
grant.KnowledgeBase = &types.KnowledgeBase{ID: "first", TenantID: 2}
|
||||
first := grant.WithGrant(base)
|
||||
grant.KnowledgeBase = &types.KnowledgeBase{ID: "second", TenantID: 2}
|
||||
second := grant.WithGrant(base)
|
||||
require.True(t, HasKBGrant(first, "first", 2, types.OrgRoleViewer))
|
||||
require.False(t, HasKBGrant(first, "second", 2, types.OrgRoleViewer))
|
||||
require.True(t, HasKBGrant(second, "second", 2, types.OrgRoleViewer))
|
||||
require.False(t, HasKBGrant(second, "first", 2, types.OrgRoleViewer))
|
||||
}
|
||||
|
||||
func TestKBPermissionsOwnerShortcutOnlyGrantsRead(t *testing.T) {
|
||||
roles := []types.TenantRole{types.TenantRoleViewer, types.TenantRoleContributor, types.TenantRoleAdmin}
|
||||
for _, role := range roles {
|
||||
ctx := context.WithValue(callerContext(), types.TenantRoleContextKey, role)
|
||||
permissions := NewKBPermissions(ctx, nil)
|
||||
for _, required := range []types.OrgMemberRole{types.OrgRoleViewer, types.OrgRoleEditor, types.OrgRoleAdmin} {
|
||||
allowed, err := permissions.Check("kb", 1, required)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, required == types.OrgRoleViewer, allowed)
|
||||
}
|
||||
grant := &KBAccess{
|
||||
Caller: types.CallerFromContext(ctx),
|
||||
KnowledgeBase: &types.KnowledgeBase{ID: "kb", TenantID: 1},
|
||||
EffectiveTenantID: 1,
|
||||
Permission: types.OrgRoleEditor,
|
||||
}
|
||||
permissions = NewKBPermissions(grant.Context(ctx), nil)
|
||||
allowed, err := permissions.Check("kb", 1, types.OrgRoleEditor)
|
||||
require.NoError(t, err)
|
||||
require.True(t, allowed)
|
||||
allowed, err = permissions.Check("kb", 1, types.OrgRoleAdmin)
|
||||
require.NoError(t, err)
|
||||
require.False(t, allowed)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
package access
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
secutils "academy/internal/utils"
|
||||
)
|
||||
|
||||
// FileAccess is a request-local result, produced before storage is opened.
|
||||
// Physical locators are not a substitute for KB/message authorization.
|
||||
type FileAccess struct {
|
||||
OwnerTenantID uint64
|
||||
Path string
|
||||
Filename string
|
||||
StorageBackendID string
|
||||
}
|
||||
|
||||
// FileCatalog resolves logical references to their stored owner and locator.
|
||||
type FileCatalog interface {
|
||||
ResolvePath(context.Context, string) (string, *types.StoredResource, error)
|
||||
}
|
||||
|
||||
func resolveFile(
|
||||
ctx context.Context,
|
||||
catalog FileCatalog,
|
||||
reference string,
|
||||
) (FileAccess, *types.StoredResource, error) {
|
||||
file := FileAccess{Path: reference, Filename: reference}
|
||||
if catalog == nil {
|
||||
if _, resource := types.ParseResourcePath(reference); resource {
|
||||
return file, nil, ErrNotFound
|
||||
}
|
||||
return file, nil, nil
|
||||
}
|
||||
path, resource, err := catalog.ResolvePath(ctx, reference)
|
||||
if err != nil {
|
||||
return file, nil, ErrNotFound
|
||||
}
|
||||
file.Path = path
|
||||
file.Filename = path
|
||||
if resource != nil {
|
||||
file.OwnerTenantID = resource.TenantID
|
||||
file.StorageBackendID = resource.StorageBackendID
|
||||
if strings.TrimSpace(resource.OriginalName) != "" {
|
||||
file.Filename = resource.OriginalName
|
||||
}
|
||||
}
|
||||
return file, resource, nil
|
||||
}
|
||||
|
||||
// ResolveKBFile requires the route's exact KB grant and an independent live
|
||||
// explicit binding check. Rewriting the execution tenant is insufficient.
|
||||
func ResolveKBFile(
|
||||
ctx context.Context,
|
||||
grant *KBAccess,
|
||||
kbID, reference string,
|
||||
catalog FileCatalog,
|
||||
bindings interfaces.KBResourceLookup,
|
||||
) (FileAccess, error) {
|
||||
var empty FileAccess
|
||||
if grant == nil || grant.KnowledgeBase == nil || grant.KnowledgeBase.ID != kbID ||
|
||||
grant.Caller != types.CallerFromContext(ctx) || !grant.Permission.HasPermission(types.OrgRoleViewer) {
|
||||
return empty, ErrForbidden
|
||||
}
|
||||
if err := types.AuthorizeTenantAPIKeyKnowledgeBases(ctx, kbID); err != nil {
|
||||
return empty, err
|
||||
}
|
||||
file, resource, err := resolveFile(ctx, catalog, reference)
|
||||
if err != nil {
|
||||
return empty, err
|
||||
}
|
||||
owner := grant.EffectiveTenantID
|
||||
if owner == 0 || (resource != nil && resource.TenantID != owner) {
|
||||
return empty, ErrForbidden
|
||||
}
|
||||
if err := secutils.ValidateKBScopedStoragePath(file.Path, owner); err != nil {
|
||||
return empty, ErrForbidden
|
||||
}
|
||||
if bindings == nil {
|
||||
return empty, ErrForbidden
|
||||
}
|
||||
bound, err := bindings.IsReferencedByKnowledgeBase(ctx, owner, kbID, reference)
|
||||
if err != nil {
|
||||
return empty, fmt.Errorf("check KB file binding: %w", err)
|
||||
}
|
||||
if !bound {
|
||||
return empty, ErrForbidden
|
||||
}
|
||||
file.OwnerTenantID = owner
|
||||
return file, nil
|
||||
}
|
||||
|
||||
// artifactRefState says whether a reference names one of this message's
|
||||
// artifacts, and if so whether the user has deleted it.
|
||||
type artifactRefState int
|
||||
|
||||
const (
|
||||
artifactRefNone artifactRefState = iota
|
||||
artifactRefLive
|
||||
artifactRefDeleted
|
||||
)
|
||||
|
||||
// artifactReferenceState resolves a reference against the message's artifacts.
|
||||
// A live row anywhere in the list wins over a tombstone: the same file can be
|
||||
// attached twice at different positions, and one of them still being there
|
||||
// means the message really does still offer it.
|
||||
func artifactReferenceState(message *types.Message, reference string) artifactRefState {
|
||||
state := artifactRefNone
|
||||
for _, artifact := range message.Artifacts {
|
||||
if artifact.URL != reference {
|
||||
continue
|
||||
}
|
||||
if !artifact.Deleted() {
|
||||
return artifactRefLive
|
||||
}
|
||||
state = artifactRefDeleted
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
// MessageReferencesFile examines only persisted rendering/output fields. Tool
|
||||
// arguments and request metadata are not evidence of a returned file.
|
||||
func MessageReferencesFile(message *types.Message, reference string) bool {
|
||||
if message == nil {
|
||||
return false
|
||||
}
|
||||
// Artifacts are checked before the answer text, and a deleted one is a hard
|
||||
// no. Deleting a generated file does not rewrite the answer that produced
|
||||
// it, so its `resource://` handle is still sitting in message.Content; if
|
||||
// the text were consulted first, the message-scoped file proxy would keep
|
||||
// serving a file the user deleted — including to a shared-agent visitor,
|
||||
// and including the case where the bytes survived because a knowledge entry
|
||||
// still holds them. Those other owners have their own access paths.
|
||||
switch artifactReferenceState(message, reference) {
|
||||
case artifactRefDeleted:
|
||||
return false
|
||||
case artifactRefLive:
|
||||
return true
|
||||
}
|
||||
if types.ContainsStorageReference(message.Content, reference) {
|
||||
return true
|
||||
}
|
||||
for _, value := range []interface{}{message.KnowledgeReferences, message.Images} {
|
||||
data, _ := json.Marshal(value)
|
||||
if types.ContainsStorageReference(string(data), reference) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
for _, step := range message.AgentSteps {
|
||||
for _, call := range step.ToolCalls {
|
||||
if call.Result == nil {
|
||||
continue
|
||||
}
|
||||
data, _ := json.Marshal(call.Result)
|
||||
if types.ContainsStorageReference(string(data), reference) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ResolveMessageFile loads the session-authorized message using the original
|
||||
// caller and rechecks its current sharing relationships on every request.
|
||||
func ResolveMessageFile(ctx context.Context, sessionID, messageID, reference string, messages MessageFileLookup,
|
||||
agents SharedAgentFileLookup, catalog FileCatalog, kbShares MessageKBShareAuthorizer,
|
||||
) (FileAccess, error) {
|
||||
caller := types.CallerFromContext(ctx)
|
||||
if caller.TenantID == 0 {
|
||||
return FileAccess{}, ErrUnauthorized
|
||||
}
|
||||
if messages == nil {
|
||||
return FileAccess{}, ErrNotFound
|
||||
}
|
||||
ctx = types.WithExecutionTenant(ctx, caller.TenantID)
|
||||
message, err := messages.GetMessage(ctx, sessionID, messageID)
|
||||
if err != nil || message == nil {
|
||||
return FileAccess{}, ErrNotFound
|
||||
}
|
||||
return AuthorizeMessageFile(ctx, message, reference, agents, catalog, kbShares)
|
||||
}
|
||||
|
||||
// AuthorizeMessageFile also serves index-based artifact downloads after their
|
||||
// session/message lookup. It never accepts an unchecked client message.
|
||||
func AuthorizeMessageFile(ctx context.Context, message *types.Message, reference string, agents SharedAgentFileLookup,
|
||||
catalog FileCatalog, kbShares MessageKBShareAuthorizer,
|
||||
) (FileAccess, error) {
|
||||
caller := types.CallerFromContext(ctx)
|
||||
if caller.TenantID == 0 {
|
||||
return FileAccess{}, ErrUnauthorized
|
||||
}
|
||||
if !MessageReferencesFile(message, reference) {
|
||||
return FileAccess{}, ErrForbidden
|
||||
}
|
||||
file, resource, err := resolveFile(ctx, catalog, reference)
|
||||
if err != nil {
|
||||
return FileAccess{}, err
|
||||
}
|
||||
owner := message.AgentTenantID
|
||||
if resource != nil {
|
||||
owner = resource.TenantID
|
||||
}
|
||||
if owner == 0 {
|
||||
return FileAccess{}, ErrForbidden
|
||||
}
|
||||
if message.Role == "user" && owner != caller.TenantID {
|
||||
return FileAccess{}, ErrForbidden
|
||||
}
|
||||
if kbShares.Bindings == nil {
|
||||
kbShares.Bindings, _ = catalog.(interfaces.KBResourceLookup)
|
||||
}
|
||||
kbAuthorized := false
|
||||
if resource != nil && message.AgentTenantID != 0 && message.AgentTenantID != owner {
|
||||
kbAuthorized = kbShares.resourceAccessibleViaSharedKB(ctx, message, resource, caller.TenantID, caller.Role)
|
||||
if !kbAuthorized {
|
||||
return FileAccess{}, ErrForbidden
|
||||
}
|
||||
}
|
||||
if owner != caller.TenantID && !kbAuthorized {
|
||||
if message.AgentTenantID == 0 {
|
||||
kbAuthorized = kbShares.resourceAccessibleViaSharedKB(ctx, message, resource, caller.TenantID, caller.Role)
|
||||
}
|
||||
if !kbAuthorized {
|
||||
if message.AgentID == "" || agents == nil {
|
||||
return FileAccess{}, ErrForbidden
|
||||
}
|
||||
agent, err := agents.GetSharedAgentForTenant(ctx, caller.TenantID, caller.Role, message.AgentID, owner)
|
||||
if err != nil || agent == nil || agent.TenantID != owner {
|
||||
return FileAccess{}, ErrForbidden
|
||||
}
|
||||
bindings, ok := catalog.(interfaces.MessageFileBindingLookup)
|
||||
if !ok {
|
||||
return FileAccess{}, ErrForbidden
|
||||
}
|
||||
origins, err := bindings.GetMessageFileBindings(ctx, owner, reference, message.ID)
|
||||
if err != nil || origins == nil {
|
||||
return FileAccess{}, ErrForbidden
|
||||
}
|
||||
allowed := origins.MessageArtifact
|
||||
scope := types.NewSharedAgentKBScope(agent)
|
||||
for _, kbID := range origins.KnowledgeBaseIDs {
|
||||
if scope.Allows(kbID, owner) && types.AuthorizeTenantAPIKeyKnowledgeBases(ctx, kbID) == nil {
|
||||
allowed = true
|
||||
}
|
||||
}
|
||||
if !allowed {
|
||||
return FileAccess{}, ErrForbidden
|
||||
}
|
||||
}
|
||||
}
|
||||
if resource == nil {
|
||||
if err := secutils.ValidateStoragePathTenant(file.Path, owner); err != nil {
|
||||
return FileAccess{}, ErrForbidden
|
||||
}
|
||||
}
|
||||
file.OwnerTenantID = owner
|
||||
return file, nil
|
||||
}
|
||||
|
||||
// ResolveMessageArtifact selects a persisted artifact after session ownership
|
||||
// was checked. Session-owned output stays downloadable independently of the
|
||||
// agent; source-owned output still requires its current sharing permission.
|
||||
func ResolveMessageArtifact(ctx context.Context, message *types.Message, index int, agents SharedAgentFileLookup,
|
||||
catalog FileCatalog, kbShares MessageKBShareAuthorizer,
|
||||
) (FileAccess, error) {
|
||||
caller := types.CallerFromContext(ctx)
|
||||
if caller.TenantID == 0 {
|
||||
return FileAccess{}, ErrUnauthorized
|
||||
}
|
||||
if message == nil || index < 0 || index >= len(message.Artifacts) {
|
||||
return FileAccess{}, ErrNotFound
|
||||
}
|
||||
artifact := message.Artifacts[index]
|
||||
// Tombstones keep their slot so the indices of later artifacts stay put;
|
||||
// they are not downloadable through any path, shared or owned.
|
||||
if artifact.Deleted() {
|
||||
return FileAccess{}, ErrNotFound
|
||||
}
|
||||
file, resource, err := resolveFile(ctx, catalog, artifact.URL)
|
||||
if err != nil {
|
||||
return FileAccess{}, err
|
||||
}
|
||||
if (resource != nil && resource.TenantID == caller.TenantID) ||
|
||||
(resource == nil && secutils.ValidateStoragePathTenant(file.Path, caller.TenantID) == nil) {
|
||||
file.OwnerTenantID = caller.TenantID
|
||||
file.Filename = artifact.FileName
|
||||
return file, nil
|
||||
}
|
||||
file, err = AuthorizeMessageFile(ctx, message, artifact.URL, agents, catalog, kbShares)
|
||||
file.Filename = artifact.FileName
|
||||
return file, err
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
package access
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type fileCatalog struct{ resource *types.StoredResource }
|
||||
|
||||
func (c fileCatalog) ResolvePath(_ context.Context, ref string) (string, *types.StoredResource, error) {
|
||||
if c.resource == nil {
|
||||
return ref, nil, nil
|
||||
}
|
||||
return c.resource.PhysicalPath, c.resource, nil
|
||||
}
|
||||
|
||||
type fileBinding struct {
|
||||
allowed bool
|
||||
err error
|
||||
kb string
|
||||
tenant uint64
|
||||
}
|
||||
|
||||
func (b *fileBinding) IsReferencedByKnowledgeBase(_ context.Context, tenant uint64, kb, _ string) (bool, error) {
|
||||
b.kb, b.tenant = kb, tenant
|
||||
return b.allowed, b.err
|
||||
}
|
||||
|
||||
type fileMessages struct {
|
||||
message *types.Message
|
||||
tenant uint64
|
||||
}
|
||||
|
||||
func (m *fileMessages) GetMessage(ctx context.Context, _, _ string) (*types.Message, error) {
|
||||
m.tenant = types.MustTenantIDFromContext(ctx)
|
||||
return m.message, nil
|
||||
}
|
||||
|
||||
func TestKBFilesRequireExactGrantAndBinding(t *testing.T) {
|
||||
base := callerContext()
|
||||
grant := &KBAccess{
|
||||
Caller: types.CallerFromContext(base),
|
||||
KnowledgeBase: &types.KnowledgeBase{ID: "kb", TenantID: 2},
|
||||
EffectiveTenantID: 2,
|
||||
Permission: types.OrgRoleViewer,
|
||||
}
|
||||
ctx := grant.Context(base)
|
||||
bindings := &fileBinding{allowed: true}
|
||||
const ref = "resource://AbCdEfGhIjKlMnOpQrStUv"
|
||||
catalog := fileCatalog{
|
||||
&types.StoredResource{TenantID: 2, PhysicalPath: "local://2/exports/a.png", OriginalName: "a.png"},
|
||||
}
|
||||
file, err := ResolveKBFile(ctx, grant, "kb", ref, catalog, bindings)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, uint64(2), file.OwnerTenantID)
|
||||
require.Equal(t, "kb", bindings.kb)
|
||||
require.Equal(t, uint64(2), bindings.tenant)
|
||||
bindings.allowed = false
|
||||
_, err = ResolveKBFile(ctx, grant, "kb", ref, catalog, bindings)
|
||||
require.ErrorIs(t, err, ErrForbidden, "a same-tenant file still needs an exact KB binding")
|
||||
bindings.allowed = true
|
||||
_, err = ResolveKBFile(ctx, grant, "another", ref, catalog, bindings)
|
||||
require.ErrorIs(t, err, ErrForbidden)
|
||||
_, err = ResolveKBFile(ctx, nil, "kb", ref, catalog, bindings)
|
||||
require.ErrorIs(t, err, ErrForbidden, "execution tenant alone is not a grant")
|
||||
bindings.err = errors.New("database unavailable")
|
||||
_, err = ResolveKBFile(ctx, grant, "kb", ref, catalog, bindings)
|
||||
require.ErrorIs(t, err, bindings.err)
|
||||
}
|
||||
|
||||
func TestMessageFilesRequireReferenceAndRecheckRevocation(t *testing.T) {
|
||||
const ref = "resource://AbCdEfGhIjKlMnOpQrStUv"
|
||||
messages := &fileMessages{
|
||||
message: &types.Message{ID: "message", AgentID: "agent", AgentTenantID: 2, Role: "assistant"},
|
||||
}
|
||||
agents := &agentLookup{agent: &types.CustomAgent{ID: "agent", TenantID: 2}}
|
||||
catalog := artifactFileCatalog{
|
||||
fileCatalog{&types.StoredResource{TenantID: 2, PhysicalPath: "local://2/exports/a.png"}},
|
||||
}
|
||||
ctx := types.WithExecutionTenant(callerContext(), 2)
|
||||
_, err := ResolveMessageFile(ctx, "session", "message", ref, messages, agents, catalog, MessageKBShareAuthorizer{})
|
||||
require.ErrorIs(t, err, ErrForbidden)
|
||||
messages.message.Content = ""
|
||||
_, err = ResolveMessageFile(ctx, "session", "message", ref, messages, agents, catalog, MessageKBShareAuthorizer{})
|
||||
require.ErrorIs(t, err, ErrForbidden, "a longer handle is not the requested handle")
|
||||
messages.message.Content = ""
|
||||
_, err = ResolveMessageFile(ctx, "session", "message", ref, messages, agents, catalog, MessageKBShareAuthorizer{})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, uint64(1), messages.tenant, "session lookup must use the caller")
|
||||
agents.agent = nil
|
||||
_, err = ResolveMessageFile(ctx, "session", "message", ref, messages, agents, catalog, MessageKBShareAuthorizer{})
|
||||
require.ErrorIs(t, err, ErrForbidden, "historical references cannot bypass share revocation")
|
||||
}
|
||||
|
||||
func TestMessageArtifactsKeepSessionOwnershipSeparateFromAgentOutput(t *testing.T) {
|
||||
const ref = "resource://AbCdEfGhIjKlMnOpQrStUv"
|
||||
message := &types.Message{
|
||||
AgentID: "agent",
|
||||
AgentTenantID: 2,
|
||||
Artifacts: types.MessageArtifacts{{URL: ref, FileName: "report.pdf"}},
|
||||
}
|
||||
catalog := fileCatalog{&types.StoredResource{TenantID: 1, PhysicalPath: "local://1/exports/report.pdf"}}
|
||||
file, err := ResolveMessageArtifact(callerContext(), message, 0, nil, catalog, MessageKBShareAuthorizer{})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, uint64(1), file.OwnerTenantID)
|
||||
catalog.resource.TenantID = 2
|
||||
catalog.resource.PhysicalPath = "local://2/exports/report.pdf"
|
||||
_, err = ResolveMessageArtifact(callerContext(), message, 0, nil, catalog, MessageKBShareAuthorizer{})
|
||||
require.ErrorIs(t, err, ErrForbidden)
|
||||
}
|
||||
|
||||
type messageFileKBs struct{ kb *types.KnowledgeBase }
|
||||
|
||||
func (k messageFileKBs) GetKnowledgeBasesByIDsOnly(context.Context, []string) ([]*types.KnowledgeBase, error) {
|
||||
return []*types.KnowledgeBase{k.kb}, nil
|
||||
}
|
||||
|
||||
func TestMessageSharedKBFilesRequireLiveBinding(t *testing.T) {
|
||||
const ref = "resource://AbCdEfGhIjKlMnOpQrStUv"
|
||||
message := &types.Message{
|
||||
AgentTenantID: 1, Role: "assistant",
|
||||
KnowledgeReferences: types.References{{KnowledgeBaseID: "shared", Content: ref}},
|
||||
}
|
||||
catalog := fileCatalog{&types.StoredResource{
|
||||
Handle: "AbCdEfGhIjKlMnOpQrStUv", TenantID: 2, PhysicalPath: "local://2/exports/a.png",
|
||||
}}
|
||||
binding := &fileBinding{allowed: true}
|
||||
shares := &shareLookup{permission: types.OrgRoleViewer}
|
||||
authorizer := MessageKBShareAuthorizer{
|
||||
ShareGuard: shares, KBs: messageFileKBs{kb: &types.KnowledgeBase{ID: "shared", TenantID: 2}}, Bindings: binding,
|
||||
}
|
||||
_, err := AuthorizeMessageFile(callerContext(), message, ref, nil, catalog, authorizer)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "shared", binding.kb)
|
||||
require.Equal(t, uint64(2), binding.tenant)
|
||||
binding.allowed = false
|
||||
_, err = AuthorizeMessageFile(callerContext(), message, ref, nil, catalog, authorizer)
|
||||
require.ErrorIs(t, err, ErrForbidden, "retrieval text alone must not authorize an unrelated same-tenant resource")
|
||||
binding.allowed = true
|
||||
binding.err = errors.New("binding lookup unavailable")
|
||||
_, err = AuthorizeMessageFile(callerContext(), message, ref, nil, catalog, authorizer)
|
||||
require.ErrorIs(t, err, ErrForbidden)
|
||||
binding.err = nil
|
||||
authorizer.Bindings = nil
|
||||
_, err = AuthorizeMessageFile(callerContext(), message, ref, nil, catalog, authorizer)
|
||||
require.ErrorIs(t, err, ErrForbidden, "missing live lookup must fail closed")
|
||||
}
|
||||
|
||||
// This fixture represents a catalog claim made by the artifact collector.
|
||||
type artifactFileCatalog struct{ fileCatalog }
|
||||
|
||||
func (artifactFileCatalog) GetMessageFileBindings(
|
||||
_ context.Context,
|
||||
_ uint64,
|
||||
_, messageID string,
|
||||
) (*types.MessageFileBindings, error) {
|
||||
return &types.MessageFileBindings{MessageArtifact: messageID == "message"}, nil
|
||||
}
|
||||
|
||||
// Deleting a generated file does not rewrite the answer that produced it, so
|
||||
// its handle stays in message.Content. The message-scoped file proxy must not
|
||||
// treat that leftover text as permission to keep serving the file — including
|
||||
// when the bytes survived because a knowledge entry still holds them, and
|
||||
// including for a shared-agent visitor who never had delete rights.
|
||||
func TestDeletedArtifactIsNotServedFromTheAnswerText(t *testing.T) {
|
||||
const ref = "resource://AbCdEfGhIjKlMnOpQrStUv"
|
||||
deletedAt := time.Now()
|
||||
messages := &fileMessages{message: &types.Message{
|
||||
ID: "message", AgentID: "agent", AgentTenantID: 2, Role: "assistant",
|
||||
Content: "",
|
||||
Artifacts: types.MessageArtifacts{{URL: ref, FileName: "report.pdf"}},
|
||||
}}
|
||||
agents := &agentLookup{agent: &types.CustomAgent{ID: "agent", TenantID: 2}}
|
||||
catalog := artifactFileCatalog{
|
||||
fileCatalog{&types.StoredResource{TenantID: 2, PhysicalPath: "local://2/exports/report.pdf"}},
|
||||
}
|
||||
ctx := types.WithExecutionTenant(callerContext(), 2)
|
||||
|
||||
_, err := ResolveMessageFile(ctx, "session", "message", ref, messages, agents, catalog, MessageKBShareAuthorizer{})
|
||||
require.NoError(t, err, "a live artifact is served as before")
|
||||
|
||||
messages.message.Artifacts[0].DeletedAt = &deletedAt
|
||||
_, err = ResolveMessageFile(ctx, "session", "message", ref, messages, agents, catalog, MessageKBShareAuthorizer{})
|
||||
require.ErrorIs(t, err, ErrForbidden, "the handle left in the answer text must not re-authorize a deleted file")
|
||||
|
||||
// The index-addressed artifact download agrees.
|
||||
_, err = ResolveMessageArtifact(ctx, messages.message, 0, agents, catalog, MessageKBShareAuthorizer{})
|
||||
require.ErrorIs(t, err, ErrNotFound)
|
||||
}
|
||||
|
||||
// The same file can be attached twice at different positions. One of them
|
||||
// still being live means the message really does still offer it.
|
||||
func TestOneLiveCopyKeepsTheFileServable(t *testing.T) {
|
||||
const ref = "resource://AbCdEfGhIjKlMnOpQrStUv"
|
||||
deletedAt := time.Now()
|
||||
message := &types.Message{
|
||||
ID: "message", AgentTenantID: 1, Role: "assistant",
|
||||
Content: "",
|
||||
Artifacts: types.MessageArtifacts{
|
||||
{URL: ref, FileName: "report.pdf", DeletedAt: &deletedAt},
|
||||
{URL: ref, FileName: "report.pdf"},
|
||||
},
|
||||
}
|
||||
require.True(t, MessageReferencesFile(message, ref))
|
||||
|
||||
message.Artifacts[1].DeletedAt = &deletedAt
|
||||
require.False(t, MessageReferencesFile(message, ref), "with every copy deleted the message no longer offers it")
|
||||
}
|
||||
|
||||
// A reference the message never produced as an artifact keeps its old path:
|
||||
// knowledge-base images and user attachments are authorized by the text.
|
||||
func TestNonArtifactReferencesStillAuthorizeFromContent(t *testing.T) {
|
||||
const kbImage = "resource://ZzZzZzZzZzZzZzZzZzZzZz"
|
||||
deletedAt := time.Now()
|
||||
message := &types.Message{
|
||||
ID: "message", AgentTenantID: 1, Role: "assistant",
|
||||
Content: "",
|
||||
Artifacts: types.MessageArtifacts{{URL: "resource://AbCdEfGhIjKlMnOpQrStUv", DeletedAt: &deletedAt}},
|
||||
}
|
||||
require.True(t, MessageReferencesFile(message, kbImage))
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package access
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
apperrors "academy/internal/errors"
|
||||
"academy/internal/logger"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// AuthorizeKBAccess rejects multi-KB searches whose scope includes a KB
|
||||
// that the original caller is not entitled to read. Exact upstream grants
|
||||
// support shared KB/agent execution; other foreign KBs need an organization
|
||||
// permission check for the caller via KBPermissions, applying the 3-D cap
|
||||
// (share role + caller's tenant-org role + tenant Viewer cap) introduced
|
||||
// in Plan 3 of #1303.
|
||||
//
|
||||
// Returning NotFound rather than Forbidden avoids leaking the existence
|
||||
// of unauthorized KB IDs that the caller could not otherwise observe.
|
||||
// Structured logs record the rejection with the offending kb_id (always
|
||||
// safe — KB IDs are UUIDs without sensitive content) and the requesting
|
||||
// tenant for audit.
|
||||
func AuthorizeKBAccess(
|
||||
ctx context.Context,
|
||||
shares KBShareLookup,
|
||||
kbs []*types.KnowledgeBase,
|
||||
) error {
|
||||
if len(kbs) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
kbIDs := make([]string, 0, len(kbs))
|
||||
for _, kb := range kbs {
|
||||
kbIDs = append(kbIDs, kb.ID)
|
||||
}
|
||||
if err := types.AuthorizeTenantAPIKeyKnowledgeBases(ctx, kbIDs...); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
requestTenantID := types.CallerFromContext(ctx).TenantID
|
||||
permissions := NewKBPermissions(ctx, shares)
|
||||
|
||||
for _, kb := range kbs {
|
||||
hasPermission, permErr := permissions.Check(kb.ID, kb.TenantID, types.OrgRoleViewer)
|
||||
if permErr != nil {
|
||||
logger.ErrorWithFields(ctx, permErr, map[string]interface{}{
|
||||
"caller_tenant_id": requestTenantID,
|
||||
"kb_tenant_id": kb.TenantID,
|
||||
"kb_id": kb.ID,
|
||||
"reason": "shared-KB permission lookup failed",
|
||||
})
|
||||
return apperrors.NewInternalServerError("failed to verify knowledge base access")
|
||||
}
|
||||
if !hasPermission {
|
||||
logger.WarnWithFields(ctx, logger.Fields{
|
||||
"caller_tenant_id": requestTenantID,
|
||||
"kb_tenant_id": kb.TenantID,
|
||||
"kb_id": kb.ID,
|
||||
"reason": "tenant lacks viewer permission for foreign-tenant KB",
|
||||
}, "search scope rejected: unauthorized foreign-tenant KB")
|
||||
return apperrors.NewNotFoundError("knowledge base not found")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package access
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// KBSharePermissions resolves organization grants for one caller during one
|
||||
// operation. It deliberately does not grant tenant ownership or shared-agent
|
||||
// access. Callers retain their own policy for lookup failures (abort or filter).
|
||||
// Create a new instance for each operation; it is not a cross-request cache and
|
||||
// must not be shared between goroutines.
|
||||
type KBSharePermissions struct {
|
||||
ctx context.Context
|
||||
lookup KBShareLookup
|
||||
tenantID uint64
|
||||
role types.TenantRole
|
||||
results map[string]kbSharePermission
|
||||
}
|
||||
|
||||
type kbSharePermission struct {
|
||||
role types.OrgMemberRole
|
||||
shared bool
|
||||
err error
|
||||
}
|
||||
|
||||
// NewKBSharePermissions creates a request-local permission cache.
|
||||
func NewKBSharePermissions(
|
||||
ctx context.Context,
|
||||
lookup KBShareLookup,
|
||||
tenantID uint64,
|
||||
role types.TenantRole,
|
||||
) *KBSharePermissions {
|
||||
return &KBSharePermissions{
|
||||
ctx: ctx,
|
||||
lookup: lookup,
|
||||
tenantID: tenantID,
|
||||
role: role,
|
||||
results: make(map[string]kbSharePermission),
|
||||
}
|
||||
}
|
||||
|
||||
// Permission caches both grants and failures so multiple documents/chunks in a
|
||||
// KB observe the same decision, without repeating the membership queries.
|
||||
func (p *KBSharePermissions) Permission(kbID string) (types.OrgMemberRole, bool, error) {
|
||||
if kbID == "" || p.tenantID == 0 || p.lookup == nil {
|
||||
return "", false, nil
|
||||
}
|
||||
result, ok := p.results[kbID]
|
||||
if !ok {
|
||||
result.role, result.shared, result.err = p.lookup.CheckTenantKBPermission(p.ctx, kbID, p.tenantID, p.role)
|
||||
p.results[kbID] = result
|
||||
}
|
||||
return result.role, result.shared, result.err
|
||||
}
|
||||
|
||||
// Check tests the required role against the cached organization permission.
|
||||
func (p *KBSharePermissions) Check(kbID string, required types.OrgMemberRole) (bool, error) {
|
||||
role, shared, err := p.Permission(kbID)
|
||||
return err == nil && shared && role.IsValid() && required.IsValid() && role.HasPermission(required), err
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package access
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type permissionLookupFunc func(context.Context, string, uint64, types.TenantRole) (types.OrgMemberRole, bool, error)
|
||||
|
||||
func (f permissionLookupFunc) CheckTenantKBPermission(
|
||||
ctx context.Context,
|
||||
id string,
|
||||
tenant uint64,
|
||||
role types.TenantRole,
|
||||
) (types.OrgMemberRole, bool, error) {
|
||||
return f(ctx, id, tenant, role)
|
||||
}
|
||||
|
||||
func TestKBSharePermissionsCachePerOperation(t *testing.T) {
|
||||
calls := map[string]int{}
|
||||
granted := true
|
||||
lookup := permissionLookupFunc(
|
||||
func(_ context.Context, kb string, tenant uint64, role types.TenantRole) (types.OrgMemberRole, bool, error) {
|
||||
require.Equal(t, uint64(1), tenant)
|
||||
require.Equal(t, types.TenantRoleContributor, role)
|
||||
calls[kb]++
|
||||
return types.OrgRoleEditor, granted, nil
|
||||
},
|
||||
)
|
||||
permissions := NewKBSharePermissions(context.Background(), lookup, 1, types.TenantRoleContributor)
|
||||
for _, required := range []types.OrgMemberRole{types.OrgRoleViewer, types.OrgRoleEditor, types.OrgRoleAdmin} {
|
||||
allowed, err := permissions.Check("kb", required)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, required != types.OrgRoleAdmin, allowed)
|
||||
}
|
||||
require.Equal(t, 1, calls["kb"], "different minimum roles share the same membership lookup")
|
||||
_, err := permissions.Check("other", types.OrgRoleViewer)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, calls["other"])
|
||||
granted = false
|
||||
fresh := NewKBSharePermissions(context.Background(), lookup, 1, types.TenantRoleContributor)
|
||||
allowed, err := fresh.Check("kb", types.OrgRoleViewer)
|
||||
require.NoError(t, err)
|
||||
require.False(t, allowed, "a new operation must observe share revocation")
|
||||
require.Equal(t, 2, calls["kb"])
|
||||
}
|
||||
|
||||
func TestKBSharePermissionsCachesFailuresWithoutGranting(t *testing.T) {
|
||||
failure := errors.New("database unavailable")
|
||||
calls := 0
|
||||
lookup := permissionLookupFunc(
|
||||
func(context.Context, string, uint64, types.TenantRole) (types.OrgMemberRole, bool, error) {
|
||||
calls++
|
||||
return types.OrgRoleAdmin, true, failure
|
||||
},
|
||||
)
|
||||
permissions := NewKBSharePermissions(context.Background(), lookup, 1, types.TenantRoleAdmin)
|
||||
for i := 0; i < 3; i++ {
|
||||
allowed, err := permissions.Check("kb", types.OrgRoleViewer)
|
||||
require.False(t, allowed)
|
||||
require.ErrorIs(t, err, failure, "callers must retain the infrastructure error")
|
||||
}
|
||||
require.Equal(t, 1, calls)
|
||||
}
|
||||
|
||||
func TestKBSharePermissionsMissingLookupAndInvalidRolesDeny(t *testing.T) {
|
||||
permissions := NewKBSharePermissions(context.Background(), nil, 1, types.TenantRoleAdmin)
|
||||
allowed, err := permissions.Check("kb", types.OrgRoleViewer)
|
||||
require.NoError(t, err)
|
||||
require.False(t, allowed)
|
||||
lookup := permissionLookupFunc(
|
||||
func(context.Context, string, uint64, types.TenantRole) (types.OrgMemberRole, bool, error) {
|
||||
return types.OrgRoleEditor, true, nil
|
||||
},
|
||||
)
|
||||
permissions = NewKBSharePermissions(context.Background(), lookup, 1, types.TenantRoleAdmin)
|
||||
allowed, err = permissions.Check("kb", "unknown")
|
||||
require.NoError(t, err)
|
||||
require.False(t, allowed)
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
package access
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// KBTransferOperation selects the source and destination permission contract.
|
||||
type KBTransferOperation string
|
||||
|
||||
// Supported knowledge-base transfer operations.
|
||||
const (
|
||||
KBTransferClone KBTransferOperation = "clone"
|
||||
KBTransferMove KBTransferOperation = "move"
|
||||
)
|
||||
|
||||
type kbTransferGrant struct {
|
||||
caller types.Caller
|
||||
tenant uint64
|
||||
source, target, taskID, creatorID string
|
||||
operation KBTransferOperation
|
||||
create bool
|
||||
}
|
||||
|
||||
// WithKBTransfer admits a pair of resources after the entry point has resolved
|
||||
// the source and destination grants and applied its creator/role policy. A new
|
||||
// clone destination must be a server-reserved ID; it is not an existing KB.
|
||||
func WithKBTransfer(
|
||||
ctx context.Context,
|
||||
source, target *types.KnowledgeBase,
|
||||
operation KBTransferOperation,
|
||||
taskID string,
|
||||
create bool,
|
||||
) (context.Context, error) {
|
||||
caller := types.CallerFromContext(ctx)
|
||||
if taskID == "" {
|
||||
return ctx, ErrForbidden
|
||||
}
|
||||
if err := validateTransferPair(source, target, caller.TenantID, operation, create); err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
if err := transferAPIScope(ctx, source.ID, target.ID, operation, create); err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
required := types.OrgRoleViewer
|
||||
if operation == KBTransferMove {
|
||||
required = types.OrgRoleEditor
|
||||
}
|
||||
if !HasKBGrant(ctx, source.ID, source.TenantID, required) ||
|
||||
(!create && !HasKBGrant(ctx, target.ID, target.TenantID, types.OrgRoleEditor)) {
|
||||
return ctx, ErrForbidden
|
||||
}
|
||||
return withTransferGrant(ctx, source, target, operation, taskID, create, false), nil
|
||||
}
|
||||
|
||||
// WithKBTransferTask continues an admitted task. Both KBs must first be loaded
|
||||
// with their persisted owners (or a reserved new clone destination). This scope
|
||||
// cannot authorize a different pair or upgrade the worker into a tenant user.
|
||||
func WithKBTransferTask(
|
||||
ctx context.Context,
|
||||
source, target *types.KnowledgeBase,
|
||||
expectedTenant uint64,
|
||||
operation KBTransferOperation,
|
||||
taskID string,
|
||||
create bool,
|
||||
) (context.Context, error) {
|
||||
if taskID == "" {
|
||||
return ctx, ErrForbidden
|
||||
}
|
||||
if err := validateTransferPair(source, target, expectedTenant, operation, create); err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
ctx = types.WithExecutionTenant(ctx, expectedTenant)
|
||||
return withTransferGrant(ctx, source, target, operation, taskID, create, true), nil
|
||||
}
|
||||
|
||||
func withTransferGrant(
|
||||
ctx context.Context,
|
||||
source, target *types.KnowledgeBase,
|
||||
operation KBTransferOperation,
|
||||
taskID string,
|
||||
create, task bool,
|
||||
) context.Context {
|
||||
caller := types.CallerFromContext(ctx)
|
||||
grant := kbTransferGrant{
|
||||
caller: caller,
|
||||
tenant: source.TenantID,
|
||||
source: source.ID,
|
||||
target: target.ID,
|
||||
taskID: taskID,
|
||||
creatorID: target.CreatorID,
|
||||
operation: operation,
|
||||
create: create,
|
||||
}
|
||||
required := types.OrgRoleViewer
|
||||
if operation == KBTransferMove {
|
||||
required = types.OrgRoleEditor
|
||||
}
|
||||
ctx = context.WithValue(ctx, types.KBGrantsContextKey, []kbGrant{
|
||||
{caller: caller, kbID: source.ID, tenantID: source.TenantID, permission: required, task: task},
|
||||
{caller: caller, kbID: target.ID, tenantID: target.TenantID, permission: types.OrgRoleEditor, task: task},
|
||||
})
|
||||
return context.WithValue(ctx, types.KBTransferContextKey, grant)
|
||||
}
|
||||
|
||||
// RequireKBTransfer consumes the exact caller, operation and resource-pair grant.
|
||||
func RequireKBTransfer(ctx context.Context, source, target *types.KnowledgeBase, operation KBTransferOperation) error {
|
||||
grant, ok := ctx.Value(types.KBTransferContextKey).(kbTransferGrant)
|
||||
if !ok || grant.caller != types.CallerFromContext(ctx) || grant.operation != operation {
|
||||
return ErrForbidden
|
||||
}
|
||||
if err := validateTransferPair(source, target, grant.tenant, operation, grant.create); err != nil {
|
||||
return err
|
||||
}
|
||||
if grant.source != source.ID || grant.target != target.ID {
|
||||
return ErrForbidden
|
||||
}
|
||||
return transferAPIScope(ctx, source.ID, target.ID, operation, grant.create)
|
||||
}
|
||||
|
||||
// CloneDestination exposes only the destination already admitted by the
|
||||
// request/worker; CopyKnowledgeBase cannot turn an empty ID into ambient write.
|
||||
func CloneDestination(ctx context.Context, sourceID string) (id string, create bool, creatorID string, err error) {
|
||||
g, ok := ctx.Value(types.KBTransferContextKey).(kbTransferGrant)
|
||||
if !ok || g.caller != types.CallerFromContext(ctx) || g.operation != KBTransferClone || g.source != sourceID {
|
||||
return "", false, "", ErrForbidden
|
||||
}
|
||||
return g.target, g.create, g.creatorID, nil
|
||||
}
|
||||
|
||||
// TransferTaskID returns the admitted operation identity for retry checkpoints.
|
||||
func TransferTaskID(ctx context.Context) string {
|
||||
g, ok := ctx.Value(types.KBTransferContextKey).(kbTransferGrant)
|
||||
if !ok || g.caller != types.CallerFromContext(ctx) {
|
||||
return ""
|
||||
}
|
||||
return g.taskID
|
||||
}
|
||||
|
||||
func validateTransferPair(
|
||||
source, target *types.KnowledgeBase,
|
||||
tenant uint64,
|
||||
operation KBTransferOperation,
|
||||
create bool,
|
||||
) error {
|
||||
if source == nil || target == nil || tenant == 0 || source.ID == "" || target.ID == "" ||
|
||||
source.TenantID != tenant ||
|
||||
target.TenantID != tenant {
|
||||
return ErrForbidden
|
||||
}
|
||||
if source.ID == target.ID {
|
||||
return fmt.Errorf("source and target knowledge bases must differ")
|
||||
}
|
||||
if operation != KBTransferClone && operation != KBTransferMove || create && operation != KBTransferClone {
|
||||
return ErrForbidden
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func transferAPIScope(
|
||||
ctx context.Context,
|
||||
sourceID, targetID string,
|
||||
operation KBTransferOperation,
|
||||
create bool,
|
||||
) error {
|
||||
ids := []string{sourceID}
|
||||
if !create {
|
||||
ids = append(ids, targetID)
|
||||
}
|
||||
if err := types.AuthorizeTenantAPIKeyKnowledgeBases(ctx, ids...); err != nil {
|
||||
return err
|
||||
}
|
||||
capability := types.APIKeyCapabilityManageKnowledgeBases
|
||||
if operation == KBTransferMove {
|
||||
capability = types.APIKeyCapabilityIngest
|
||||
}
|
||||
if scope, ok := types.TenantAPIKeyScopeFromContext(ctx); ok && !scope.FullAccess &&
|
||||
!scope.HasCapability(capability) {
|
||||
return ErrForbidden
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ValidateKBTransferCompatibility is shared by synchronous admission and task
|
||||
// execution, so invalid modes/configurations fail before resource mutations.
|
||||
func ValidateKBTransferCompatibility(
|
||||
source, target *types.KnowledgeBase,
|
||||
operation KBTransferOperation,
|
||||
mode string,
|
||||
tenant *types.Tenant,
|
||||
) error {
|
||||
if source == nil || target == nil {
|
||||
return ErrNotFound
|
||||
}
|
||||
if source.ID == target.ID {
|
||||
return fmt.Errorf("source and target knowledge bases must differ")
|
||||
}
|
||||
if source.Type != target.Type {
|
||||
return fmt.Errorf("source and target knowledge bases must have the same type")
|
||||
}
|
||||
if source.EmbeddingModelID != target.EmbeddingModelID {
|
||||
return fmt.Errorf("source and target knowledge bases use different embedding models")
|
||||
}
|
||||
if operation == KBTransferMove && mode != "reuse_vectors" && mode != "reparse" {
|
||||
return fmt.Errorf("unknown move mode: %s", mode)
|
||||
}
|
||||
if (operation == KBTransferClone || mode == "reuse_vectors") && !source.SharesStoreWith(target) {
|
||||
return fmt.Errorf("source and target knowledge bases use different vector stores; use reparse mode for moves")
|
||||
}
|
||||
// A move retains file paths too, so resolving them through another storage
|
||||
// instance would make the document unreadable, even when vectors are reparsed.
|
||||
defaultID, defaultProvider := "", ""
|
||||
if tenant != nil {
|
||||
if tenant.DefaultStorageBackendID != nil {
|
||||
defaultID = *tenant.DefaultStorageBackendID
|
||||
}
|
||||
if tenant.StorageEngineConfig != nil {
|
||||
defaultProvider = tenant.StorageEngineConfig.DefaultProvider
|
||||
}
|
||||
}
|
||||
if !source.SharesStorageBackendWith(target, defaultID, defaultProvider) {
|
||||
return fmt.Errorf("source and target knowledge bases use different storage instances")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package access
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"academy/internal/logger"
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestTransferAdmissionRequiresIndependentGrants(t *testing.T) {
|
||||
source, target := &types.KnowledgeBase{ID: "source", TenantID: 1}, &types.KnowledgeBase{ID: "target", TenantID: 1}
|
||||
ctx := types.WithCaller(
|
||||
context.Background(),
|
||||
types.Caller{TenantID: 1, UserID: "user", Role: types.TenantRoleAdmin},
|
||||
)
|
||||
_, err := WithKBTransfer(ctx, source, target, KBTransferMove, "task", false)
|
||||
require.ErrorIs(t, err, ErrForbidden)
|
||||
request := KBRequest{Caller: types.CallerFromContext(ctx)}
|
||||
sourceRead, err := ResolveKB(ctx, request, source, types.OrgRoleViewer, nil, nil)
|
||||
require.NoError(t, err)
|
||||
targetRead, err := ResolveKB(ctx, request, target, types.OrgRoleViewer, nil, nil)
|
||||
require.NoError(t, err)
|
||||
reads := targetRead.WithGrant(sourceRead.WithGrant(ctx))
|
||||
_, err = WithKBTransfer(reads, source, target, KBTransferClone, "task", false)
|
||||
require.ErrorIs(t, err, ErrForbidden, "owner read projection must not authorize target replacement")
|
||||
targetWrite, err := ResolveKB(ctx, request, target, types.OrgRoleEditor, nil, nil)
|
||||
require.NoError(t, err)
|
||||
cloneCtx, err := WithKBTransfer(targetWrite.WithGrant(reads), source, target, KBTransferClone, "task", false)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, RequireKBTransfer(logger.CloneContext(cloneCtx), source, target, KBTransferClone))
|
||||
require.False(t, HasKBGrant(cloneCtx, source.ID, 1, types.OrgRoleEditor))
|
||||
_, err = WithKBTransfer(targetWrite.WithGrant(reads), source, target, KBTransferMove, "task", false)
|
||||
require.ErrorIs(t, err, ErrForbidden)
|
||||
}
|
||||
|
||||
func TestTransferTaskScopeIsExactAndDoesNotCreateCaller(t *testing.T) {
|
||||
source, target := &types.KnowledgeBase{ID: "source", TenantID: 7}, &types.KnowledgeBase{ID: "target", TenantID: 7}
|
||||
ctx, err := WithKBTransferTask(context.Background(), source, target, 7, KBTransferMove, "task", false)
|
||||
require.NoError(t, err)
|
||||
ctx = logger.CloneContext(ctx)
|
||||
require.Zero(t, types.CallerFromContext(ctx).TenantID)
|
||||
require.NoError(t, RequireKBTransfer(ctx, source, target, KBTransferMove))
|
||||
require.ErrorIs(t, RequireKBTransfer(ctx, source, target, KBTransferClone), ErrForbidden)
|
||||
require.ErrorIs(
|
||||
t,
|
||||
RequireKBTransfer(ctx, source, &types.KnowledgeBase{ID: "third", TenantID: 7}, KBTransferMove),
|
||||
ErrForbidden,
|
||||
)
|
||||
require.False(t, HasKBGrant(ctx, "third", 7, types.OrgRoleViewer))
|
||||
_, err = WithKBTransferTask(
|
||||
ctx,
|
||||
source,
|
||||
&types.KnowledgeBase{ID: "target", TenantID: 8},
|
||||
7,
|
||||
KBTransferMove,
|
||||
"task",
|
||||
false,
|
||||
)
|
||||
require.ErrorIs(t, err, ErrForbidden)
|
||||
changed := types.WithCaller(ctx, types.Caller{TenantID: 7, UserID: "different"})
|
||||
require.ErrorIs(t, RequireKBTransfer(changed, source, target, KBTransferMove), ErrForbidden)
|
||||
}
|
||||
|
||||
func TestTransferAPICapabilitiesRemainSeparate(t *testing.T) {
|
||||
source, target := &types.KnowledgeBase{ID: "source", TenantID: 1}, &types.KnowledgeBase{ID: "target", TenantID: 1}
|
||||
for _, tc := range []struct {
|
||||
operation KBTransferOperation
|
||||
capability string
|
||||
create bool
|
||||
ids []string
|
||||
allowed bool
|
||||
}{
|
||||
{KBTransferClone, "manage_kbs", false, []string{"source", "target"}, true},
|
||||
{KBTransferClone, "ingest", false, []string{"source", "target"}, false},
|
||||
{KBTransferMove, "ingest", false, []string{"source", "target"}, true},
|
||||
{KBTransferMove, "manage_kbs", false, []string{"source", "target"}, false},
|
||||
{KBTransferMove, "ingest", false, []string{"source"}, false},
|
||||
{KBTransferClone, "manage_kbs", true, []string{"source"}, true},
|
||||
} {
|
||||
t.Run(
|
||||
fmt.Sprintf("%s/%s/create=%v/ids=%d", tc.operation, tc.capability, tc.create, len(tc.ids)),
|
||||
func(t *testing.T) {
|
||||
ctx, err := WithKBTransferTask(context.Background(), source, target, 1, tc.operation, "task", tc.create)
|
||||
require.NoError(t, err)
|
||||
ctx = types.WithTenantAPIKeyScope(
|
||||
ctx,
|
||||
types.TenantAPIKeyScope{Capabilities: types.StringArray{tc.capability}, KnowledgeBaseIDs: tc.ids},
|
||||
)
|
||||
require.Equal(t, tc.allowed, RequireKBTransfer(ctx, source, target, tc.operation) == nil)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package access
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// RequireKBWrite consumes an explicit operation grant. Tenant ownership and
|
||||
// role checks belong to the entry point that resolved the grant; an execution
|
||||
// tenant alone, or a shared-agent/read grant, never authorizes a mutation.
|
||||
func RequireKBWrite(ctx context.Context, kb *types.KnowledgeBase) error {
|
||||
if kb == nil || kb.ID == "" || kb.TenantID == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
if scope, ok := types.TenantAPIKeyScopeFromContext(ctx); ok && !scope.FullAccess &&
|
||||
!scope.HasCapability(types.APIKeyCapabilityIngest) {
|
||||
return ErrForbidden
|
||||
}
|
||||
if !HasKBGrant(ctx, kb.ID, kb.TenantID, types.OrgRoleEditor) {
|
||||
return ErrForbidden
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// WithKBTaskWrite is for trusted workers continuing an admitted operation.
|
||||
// The worker supplies a server-loaded KB and verifies its child-resource
|
||||
// bindings before any side effects. It grants only this KB, preserves the
|
||||
// original caller (including an absent caller), and never creates an Admin.
|
||||
// This is a task execution grant, not a way to authorize an incoming request.
|
||||
func WithKBTaskWrite(ctx context.Context, kb *types.KnowledgeBase, expectedTenant uint64) (context.Context, error) {
|
||||
if kb == nil || kb.ID == "" || expectedTenant == 0 || kb.TenantID != expectedTenant {
|
||||
return ctx, ErrForbidden
|
||||
}
|
||||
ctx = types.WithExecutionTenant(ctx, expectedTenant)
|
||||
grant := kbGrant{
|
||||
caller: types.CallerFromContext(ctx),
|
||||
kbID: kb.ID,
|
||||
tenantID: expectedTenant,
|
||||
permission: types.OrgRoleEditor,
|
||||
task: true,
|
||||
}
|
||||
// A worker gets exactly one scope, without inheriting another task's KBs.
|
||||
return context.WithValue(ctx, types.KBGrantsContextKey, []kbGrant{grant}), nil
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package access
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"academy/internal/logger"
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestKBWriteConsumesOperationGrant(t *testing.T) {
|
||||
ctx := callerContext()
|
||||
kb := &types.KnowledgeBase{ID: "kb", TenantID: types.CallerFromContext(ctx).TenantID}
|
||||
read, err := ResolveKB(ctx, KBRequest{Caller: types.CallerFromContext(ctx)}, kb, types.OrgRoleViewer, nil, nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, types.OrgRoleAdmin, read.Permission, "owner permission projection remains unchanged")
|
||||
require.ErrorIs(t, RequireKBWrite(read.Context(ctx), kb), ErrForbidden, "an owner read does not grant mutation")
|
||||
require.ErrorIs(t, RequireKBWrite(types.WithExecutionTenant(ctx, kb.TenantID), kb), ErrForbidden)
|
||||
write, err := ResolveKB(ctx, KBRequest{Caller: types.CallerFromContext(ctx)}, kb, types.OrgRoleEditor, nil, nil)
|
||||
require.NoError(t, err)
|
||||
ctx = logger.CloneContext(write.Context(ctx))
|
||||
require.NoError(t, RequireKBWrite(ctx, kb))
|
||||
require.ErrorIs(t, RequireKBWrite(ctx, &types.KnowledgeBase{ID: "other", TenantID: kb.TenantID}), ErrForbidden)
|
||||
require.ErrorIs(t, RequireKBWrite(ctx, &types.KnowledgeBase{ID: kb.ID, TenantID: kb.TenantID + 1}), ErrForbidden)
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
scope types.TenantAPIKeyScope
|
||||
allowed bool
|
||||
}{
|
||||
{"retrieve only", types.TenantAPIKeyScope{Capabilities: types.StringArray{"retrieve"}}, false},
|
||||
{
|
||||
"ingest",
|
||||
types.TenantAPIKeyScope{
|
||||
Capabilities: types.StringArray{"ingest"},
|
||||
KnowledgeBaseIDs: types.StringArray{"kb"},
|
||||
},
|
||||
true,
|
||||
},
|
||||
|
||||
{
|
||||
"wrong KB",
|
||||
types.TenantAPIKeyScope{
|
||||
Capabilities: types.StringArray{"ingest"},
|
||||
KnowledgeBaseIDs: types.StringArray{"other"},
|
||||
},
|
||||
false,
|
||||
},
|
||||
|
||||
{"full access", types.TenantAPIKeyScope{FullAccess: true}, true},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := RequireKBWrite(types.WithTenantAPIKeyScope(ctx, tt.scope), kb)
|
||||
require.Equal(t, tt.allowed, err == nil)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestKBTaskWriteIsExplicitAndBounded(t *testing.T) {
|
||||
kb := &types.KnowledgeBase{ID: "kb", TenantID: 7}
|
||||
base := context.Background()
|
||||
ctx, err := WithKBTaskWrite(base, kb, 7)
|
||||
require.NoError(t, err)
|
||||
ctx = logger.CloneContext(ctx)
|
||||
require.Zero(t, types.CallerFromContext(ctx).TenantID, "a worker must not impersonate the tenant owner")
|
||||
require.NoError(t, RequireKBWrite(ctx, kb))
|
||||
allowed, err := NewKBPermissions(ctx, nil).Check("kb", 7, types.OrgRoleViewer)
|
||||
require.NoError(t, err)
|
||||
require.True(t, allowed, "a scoped write task can read its KB")
|
||||
allowed, err = NewKBPermissions(ctx, nil).Check("other", 7, types.OrgRoleViewer)
|
||||
require.NoError(t, err)
|
||||
require.False(t, allowed)
|
||||
require.ErrorIs(t, RequireKBWrite(ctx, &types.KnowledgeBase{ID: "other", TenantID: 7}), ErrForbidden)
|
||||
_, err = WithKBTaskWrite(base, kb, 8)
|
||||
require.ErrorIs(t, err, ErrForbidden)
|
||||
_, err = WithKBTaskWrite(base, kb, 0)
|
||||
require.ErrorIs(t, err, ErrForbidden)
|
||||
require.False(t, HasKBGrant(base, "kb", 7, types.OrgRoleEditor), "the parent context stays unmodified")
|
||||
request := callerContext()
|
||||
task, err := WithKBTaskWrite(request, kb, 7)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, types.CallerFromContext(request), types.CallerFromContext(task))
|
||||
changed := types.WithCaller(task, types.Caller{TenantID: 99, UserID: "another"})
|
||||
require.ErrorIs(t, RequireKBWrite(changed, kb), ErrForbidden)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package access
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
apperrors "academy/internal/errors"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// RejectMovingKnowledge is shared by admission and persisted service checks.
|
||||
// Admission prevents misleading task acceptance; workers must recheck after
|
||||
// enqueue because a move can claim the document in the intervening window.
|
||||
func RejectMovingKnowledge(knowledge *types.Knowledge) error {
|
||||
if knowledge == nil {
|
||||
return apperrors.NewNotFoundError("knowledge not found")
|
||||
}
|
||||
fields := map[string]json.RawMessage{}
|
||||
if len(knowledge.Metadata) != 0 {
|
||||
if err := json.Unmarshal(knowledge.Metadata, &fields); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
raw := fields[types.KnowledgeTransferMetadataKey]
|
||||
if len(raw) == 0 {
|
||||
return nil
|
||||
}
|
||||
var state struct {
|
||||
Operation KBTransferOperation `json:"operation"`
|
||||
Phase string `json:"phase"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &state); err != nil {
|
||||
return err
|
||||
}
|
||||
if state.Operation == KBTransferMove && state.Phase == "moving" {
|
||||
return apperrors.NewConflictError("knowledge has an unfinished move; retry the move first")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
// Package access resolves resource permissions independently of HTTP routing.
|
||||
// Tenant roles, API-key capabilities, and resource ownership guards remain
|
||||
// separate checks; a KB grant does not replace them.
|
||||
package access
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// Resource access errors retain distinct adapter response mappings.
|
||||
var (
|
||||
ErrUnauthorized = errors.New("kb_access: unauthorized")
|
||||
ErrNotFound = errors.New("kb_access: not found")
|
||||
ErrForbidden = errors.New("kb_access: forbidden")
|
||||
ErrInvalidAgentSource = errors.New("kb_access: invalid agent source")
|
||||
)
|
||||
|
||||
// KBRequest keeps the authenticated caller separate from the resource tenant.
|
||||
// AgentSourceTenantID is parsed only when the explicit-agent fallback is used.
|
||||
type KBRequest struct {
|
||||
Caller types.Caller
|
||||
AgentID string
|
||||
AgentSourceTenantID string
|
||||
}
|
||||
|
||||
// KBAccess binds a resolved resource permission to its original caller.
|
||||
type KBAccess struct {
|
||||
KnowledgeBase *types.KnowledgeBase
|
||||
Caller types.Caller
|
||||
EffectiveTenantID uint64
|
||||
Permission types.OrgMemberRole
|
||||
// A read resolution must not mint a write grant even for the KB owner.
|
||||
operationPermission types.OrgMemberRole
|
||||
}
|
||||
|
||||
// Context scopes resource operations without changing the authenticated caller.
|
||||
func (a *KBAccess) Context(ctx context.Context) context.Context {
|
||||
if a == nil || a.KnowledgeBase == nil {
|
||||
return ctx
|
||||
}
|
||||
scoped := a.WithGrant(ctx)
|
||||
if types.CallerFromContext(scoped) != a.Caller.Normalize() {
|
||||
return ctx
|
||||
}
|
||||
return types.WithExecutionTenant(scoped, a.EffectiveTenantID)
|
||||
}
|
||||
|
||||
// WithGrant carries this authorization without changing execution scope.
|
||||
func (a *KBAccess) WithGrant(ctx context.Context) context.Context {
|
||||
if a == nil || a.KnowledgeBase == nil {
|
||||
return ctx
|
||||
}
|
||||
caller := a.Caller.Normalize()
|
||||
if existing, ok := ctx.Value(types.CallerContextKey).(types.Caller); ok && existing != caller {
|
||||
return ctx // A grant cannot replace an already authenticated caller.
|
||||
}
|
||||
grants, _ := ctx.Value(types.KBGrantsContextKey).([]kbGrant)
|
||||
permission := a.Permission
|
||||
if a.operationPermission.IsValid() && permission.HasPermission(a.operationPermission) {
|
||||
permission = a.operationPermission
|
||||
}
|
||||
grants = append(
|
||||
append([]kbGrant(nil), grants...),
|
||||
kbGrant{caller: caller, kbID: a.KnowledgeBase.ID, tenantID: a.EffectiveTenantID, permission: permission},
|
||||
)
|
||||
return context.WithValue(types.WithCaller(ctx, caller), types.KBGrantsContextKey, grants)
|
||||
}
|
||||
|
||||
// KBShareLookup resolves organization sharing with the caller role cap.
|
||||
type KBShareLookup interface {
|
||||
CheckTenantKBPermission(context.Context, string, uint64, types.TenantRole) (types.OrgMemberRole, bool, error)
|
||||
}
|
||||
|
||||
// SharedAgentLookup verifies access to a particular shared agent.
|
||||
type SharedAgentLookup interface {
|
||||
GetSharedAgentForTenant(context.Context, uint64, types.TenantRole, string, ...uint64) (*types.CustomAgent, error)
|
||||
}
|
||||
|
||||
// AgentShareLookup also supports read access through any reachable agent.
|
||||
type AgentShareLookup interface {
|
||||
SharedAgentLookup
|
||||
TenantCanAccessKBViaSomeSharedAgent(context.Context, uint64, types.TenantRole, *types.KnowledgeBase) (bool, error)
|
||||
}
|
||||
|
||||
// ResolveKB authorizes a server-loaded KB (or a document's persisted KB/tenant
|
||||
// reference). Its tenant is authoritative; resolving the owner from a share
|
||||
// record again would add a lookup and a second source of truth. It never treats
|
||||
// an effective resource tenant as the caller.
|
||||
// Share lookup errors do not grant access; an independent agent grant may still
|
||||
// allow reading. An explicit agent selector never falls back to another agent.
|
||||
func ResolveKB(ctx context.Context, request KBRequest, kb *types.KnowledgeBase, required types.OrgMemberRole,
|
||||
shares KBShareLookup, agents AgentShareLookup,
|
||||
) (*KBAccess, error) {
|
||||
if request.Caller.TenantID == 0 {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
if kb == nil || kb.ID == "" {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err := types.AuthorizeTenantAPIKeyKnowledgeBases(ctx, kb.ID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
request.Caller = request.Caller.Normalize()
|
||||
if caller, ok := ctx.Value(types.CallerContextKey).(types.Caller); ok && caller != request.Caller {
|
||||
return nil, ErrForbidden
|
||||
}
|
||||
grant := func(permission types.OrgMemberRole) (*KBAccess, error) {
|
||||
return &KBAccess{
|
||||
KnowledgeBase: kb, Caller: request.Caller,
|
||||
EffectiveTenantID: kb.TenantID, Permission: permission, operationPermission: required,
|
||||
}, nil
|
||||
}
|
||||
if kb.TenantID == request.Caller.TenantID {
|
||||
return grant(types.OrgRoleAdmin)
|
||||
}
|
||||
if shares != nil {
|
||||
permissions := NewKBSharePermissions(ctx, shares, request.Caller.TenantID, request.Caller.Role)
|
||||
permission, shared, err := permissions.Permission(kb.ID)
|
||||
if err == nil && shared && permission.HasPermission(required) {
|
||||
return grant(permission)
|
||||
}
|
||||
}
|
||||
if required != types.OrgRoleViewer || agents == nil {
|
||||
return nil, ErrForbidden
|
||||
}
|
||||
if request.AgentID != "" {
|
||||
source, err := types.ParseAgentSourceTenantID(request.AgentSourceTenantID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %s", ErrInvalidAgentSource, err)
|
||||
}
|
||||
agent, err := agents.GetSharedAgentForTenant(
|
||||
ctx,
|
||||
request.Caller.TenantID,
|
||||
request.Caller.Role,
|
||||
request.AgentID,
|
||||
source,
|
||||
)
|
||||
if err == nil && types.SharedAgentIncludesKB(agent, kb) {
|
||||
return grant(types.OrgRoleViewer)
|
||||
}
|
||||
} else {
|
||||
allowed,
|
||||
err := agents.TenantCanAccessKBViaSomeSharedAgent(ctx,
|
||||
request.Caller.TenantID,
|
||||
request.Caller.Role,
|
||||
kb)
|
||||
if err == nil && allowed {
|
||||
return grant(types.OrgRoleViewer)
|
||||
}
|
||||
}
|
||||
return nil, ErrForbidden
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
package access
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type shareLookup struct {
|
||||
permission types.OrgMemberRole
|
||||
err error
|
||||
caller uint64
|
||||
role types.TenantRole
|
||||
}
|
||||
|
||||
func (s *shareLookup) CheckTenantKBPermission(
|
||||
_ context.Context,
|
||||
_ string,
|
||||
caller uint64,
|
||||
role types.TenantRole,
|
||||
) (types.OrgMemberRole, bool, error) {
|
||||
s.caller, s.role = caller, role
|
||||
return s.permission, s.permission != "", s.err
|
||||
}
|
||||
|
||||
type agentLookup struct {
|
||||
agent *types.CustomAgent
|
||||
any bool
|
||||
err error
|
||||
anyCalls int
|
||||
source uint64
|
||||
}
|
||||
|
||||
func (s *agentLookup) GetSharedAgentForTenant(
|
||||
_ context.Context,
|
||||
_ uint64,
|
||||
_ types.TenantRole,
|
||||
_ string,
|
||||
source ...uint64,
|
||||
) (*types.CustomAgent, error) {
|
||||
s.source = source[0]
|
||||
return s.agent, s.err
|
||||
}
|
||||
|
||||
func (s *agentLookup) TenantCanAccessKBViaSomeSharedAgent(
|
||||
context.Context,
|
||||
uint64,
|
||||
types.TenantRole,
|
||||
*types.KnowledgeBase,
|
||||
) (bool, error) {
|
||||
s.anyCalls++
|
||||
return s.any, s.err
|
||||
}
|
||||
|
||||
func TestResolveKBPermissionMatrix(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
own bool
|
||||
permission types.OrgMemberRole
|
||||
required types.OrgMemberRole
|
||||
shareError bool
|
||||
agentID, source, mode string
|
||||
selected []string
|
||||
wrongTenant, missingAgent, agentError, anyAgent bool
|
||||
want types.OrgMemberRole
|
||||
wantErr error
|
||||
}{
|
||||
{name: "own KB", own: true, required: types.OrgRoleEditor, want: types.OrgRoleAdmin},
|
||||
{
|
||||
name: "organization reader",
|
||||
permission: types.OrgRoleViewer,
|
||||
required: types.OrgRoleViewer,
|
||||
want: types.OrgRoleViewer,
|
||||
},
|
||||
|
||||
{
|
||||
name: "organization editor",
|
||||
permission: types.OrgRoleEditor,
|
||||
required: types.OrgRoleEditor,
|
||||
want: types.OrgRoleEditor,
|
||||
},
|
||||
|
||||
{
|
||||
name: "reader cannot write",
|
||||
permission: types.OrgRoleViewer,
|
||||
required: types.OrgRoleEditor,
|
||||
wantErr: ErrForbidden,
|
||||
},
|
||||
|
||||
{
|
||||
name: "share lookup fails closed",
|
||||
permission: types.OrgRoleEditor,
|
||||
shareError: true,
|
||||
required: types.OrgRoleViewer,
|
||||
wantErr: ErrForbidden,
|
||||
},
|
||||
|
||||
{
|
||||
name: "independent agent grant after share error",
|
||||
shareError: true,
|
||||
anyAgent: true,
|
||||
required: types.OrgRoleViewer,
|
||||
want: types.OrgRoleViewer,
|
||||
},
|
||||
|
||||
{name: "any shared agent read", anyAgent: true, required: types.OrgRoleViewer, want: types.OrgRoleViewer},
|
||||
{name: "any agent cannot write", anyAgent: true, required: types.OrgRoleEditor, wantErr: ErrForbidden},
|
||||
{
|
||||
name: "agent lookup error",
|
||||
anyAgent: true,
|
||||
agentError: true,
|
||||
required: types.OrgRoleViewer,
|
||||
wantErr: ErrForbidden,
|
||||
},
|
||||
|
||||
{
|
||||
name: "explicit all",
|
||||
agentID: "agent",
|
||||
source: "2",
|
||||
mode: "all",
|
||||
required: types.OrgRoleViewer,
|
||||
want: types.OrgRoleViewer,
|
||||
},
|
||||
|
||||
{
|
||||
name: "explicit selected",
|
||||
agentID: "agent",
|
||||
mode: "selected",
|
||||
selected: []string{"kb"},
|
||||
required: types.OrgRoleViewer,
|
||||
want: types.OrgRoleViewer,
|
||||
},
|
||||
|
||||
{
|
||||
name: "selection miss does not fall back",
|
||||
agentID: "agent",
|
||||
mode: "selected",
|
||||
selected: []string{"other"},
|
||||
anyAgent: true,
|
||||
required: types.OrgRoleViewer,
|
||||
wantErr: ErrForbidden,
|
||||
},
|
||||
|
||||
{
|
||||
name: "none does not fall back",
|
||||
agentID: "agent",
|
||||
mode: "none",
|
||||
anyAgent: true,
|
||||
required: types.OrgRoleViewer,
|
||||
wantErr: ErrForbidden,
|
||||
},
|
||||
|
||||
{
|
||||
name: "unknown mode denied",
|
||||
agentID: "agent",
|
||||
mode: "invalid",
|
||||
required: types.OrgRoleViewer,
|
||||
wantErr: ErrForbidden,
|
||||
},
|
||||
|
||||
{
|
||||
name: "tenant mismatch denied",
|
||||
agentID: "agent",
|
||||
mode: "all",
|
||||
wrongTenant: true,
|
||||
required: types.OrgRoleViewer,
|
||||
wantErr: ErrForbidden,
|
||||
},
|
||||
|
||||
{
|
||||
name: "missing explicit agent does not fall back",
|
||||
agentID: "agent",
|
||||
missingAgent: true,
|
||||
anyAgent: true,
|
||||
required: types.OrgRoleViewer,
|
||||
wantErr: ErrForbidden,
|
||||
},
|
||||
|
||||
{
|
||||
name: "invalid source rejected",
|
||||
agentID: "agent",
|
||||
source: "bad",
|
||||
mode: "all",
|
||||
required: types.OrgRoleViewer,
|
||||
wantErr: ErrInvalidAgentSource,
|
||||
},
|
||||
|
||||
{
|
||||
name: "own grant precedes agent parsing",
|
||||
own: true,
|
||||
agentID: "agent",
|
||||
source: "bad",
|
||||
required: types.OrgRoleViewer,
|
||||
want: types.OrgRoleAdmin,
|
||||
},
|
||||
|
||||
{
|
||||
name: "share grant precedes agent parsing",
|
||||
permission: types.OrgRoleViewer,
|
||||
agentID: "agent",
|
||||
source: "bad",
|
||||
required: types.OrgRoleViewer,
|
||||
want: types.OrgRoleViewer,
|
||||
},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
kb := &types.KnowledgeBase{ID: "kb", TenantID: 2}
|
||||
if tt.own {
|
||||
kb.TenantID = 1
|
||||
}
|
||||
shares := &shareLookup{permission: tt.permission}
|
||||
if tt.shareError {
|
||||
shares.err = errors.New("unavailable")
|
||||
}
|
||||
agents := &agentLookup{
|
||||
any: tt.anyAgent,
|
||||
agent: &types.CustomAgent{
|
||||
TenantID: 2,
|
||||
Config: types.CustomAgentConfig{KBSelectionMode: tt.mode, KnowledgeBases: tt.selected},
|
||||
},
|
||||
}
|
||||
if tt.wrongTenant {
|
||||
agents.agent.TenantID = 3
|
||||
}
|
||||
if tt.missingAgent {
|
||||
agents.agent = nil
|
||||
}
|
||||
if tt.agentError {
|
||||
agents.err = errors.New("unavailable")
|
||||
}
|
||||
request := KBRequest{
|
||||
Caller: types.Caller{TenantID: 1, Role: types.TenantRoleViewer},
|
||||
AgentID: tt.agentID,
|
||||
AgentSourceTenantID: tt.source,
|
||||
}
|
||||
grant, err := ResolveKB(context.Background(), request, kb, tt.required, shares, agents)
|
||||
if tt.wantErr != nil {
|
||||
require.ErrorIs(t, err, tt.wantErr)
|
||||
require.Nil(t, grant)
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tt.want, grant.Permission)
|
||||
require.Equal(t, uint64(1), grant.Caller.TenantID)
|
||||
require.Equal(t, kb.TenantID, grant.EffectiveTenantID)
|
||||
}
|
||||
if !tt.own {
|
||||
require.Equal(t, uint64(1), shares.caller)
|
||||
require.Equal(t, types.TenantRoleViewer, shares.role)
|
||||
}
|
||||
if tt.agentID != "" {
|
||||
require.Zero(t, agents.anyCalls)
|
||||
}
|
||||
if tt.source == "2" {
|
||||
require.Equal(t, uint64(2), agents.source)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveKBMissingIdentityResourceAndAPIKeyScope(t *testing.T) {
|
||||
kb := &types.KnowledgeBase{ID: "kb", TenantID: 1}
|
||||
_, err := ResolveKB(context.Background(), KBRequest{}, kb, types.OrgRoleViewer, nil, nil)
|
||||
require.ErrorIs(t, err, ErrUnauthorized)
|
||||
_, err = ResolveKB(
|
||||
context.Background(),
|
||||
KBRequest{Caller: types.Caller{TenantID: 1}},
|
||||
nil,
|
||||
types.OrgRoleViewer,
|
||||
nil,
|
||||
nil,
|
||||
)
|
||||
require.ErrorIs(t, err, ErrNotFound)
|
||||
ctx := types.WithTenantAPIKeyScope(
|
||||
context.Background(),
|
||||
types.TenantAPIKeyScope{KnowledgeBaseIDs: types.StringArray{"other"}},
|
||||
)
|
||||
_, err = ResolveKB(ctx, KBRequest{Caller: types.Caller{TenantID: 1}}, kb, types.OrgRoleViewer, nil, nil)
|
||||
require.Error(t, err, "API key scope must apply even to owned KBs")
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
package access
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// MessageFileLookup is the narrow message-service surface needed by the
|
||||
// message-scoped file proxy. Keeping it small makes the authorization boundary
|
||||
// independently testable.
|
||||
type MessageFileLookup interface {
|
||||
GetMessage(ctx context.Context, sessionID, messageID string) (*types.Message, error)
|
||||
}
|
||||
|
||||
// SharedAgentFileLookup verifies that a source workspace's agent is still
|
||||
// shared to the caller. Revoking the share therefore also revokes historical
|
||||
// message-file access.
|
||||
type SharedAgentFileLookup interface {
|
||||
GetSharedAgentForTenant(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
callerTenantRole types.TenantRole,
|
||||
agentID string,
|
||||
sourceTenantID ...uint64,
|
||||
) (*types.CustomAgent, error)
|
||||
}
|
||||
|
||||
// KBSharePermissionGuard is the org-share surface the message-scoped proxy
|
||||
// needs for its shared-KB fallback.
|
||||
type KBSharePermissionGuard = KBShareLookup
|
||||
|
||||
// KBTenantLookup resolves knowledge bases without a tenant filter, so a
|
||||
// message's persisted retrieval evidence can be mapped back to the knowledge
|
||||
// bases the chunks were retrieved from.
|
||||
type KBTenantLookup interface {
|
||||
GetKnowledgeBasesByIDsOnly(ctx context.Context, ids []string) ([]*types.KnowledgeBase, error)
|
||||
}
|
||||
|
||||
// KnowledgeOwnerLookup resolves a knowledge entry to its knowledge base for
|
||||
// message references that predate the denormalized knowledge_base_id field.
|
||||
type KnowledgeOwnerLookup interface {
|
||||
GetKnowledgeByIDOnly(ctx context.Context, id string) (*types.Knowledge, error)
|
||||
}
|
||||
|
||||
// MessageKBShareAuthorizer bundles the read-only lookups behind the
|
||||
// message proxy's org-shared-KB fallback. A nil ShareGuard or KBs lookup
|
||||
// disables the fallback. A live Bindings lookup is also required and can
|
||||
// be supplied by the resource catalog. A nil Knowledges lookup only disables the
|
||||
// pre-denormalization KnowledgeID path.
|
||||
type MessageKBShareAuthorizer struct {
|
||||
ShareGuard KBSharePermissionGuard
|
||||
KBs KBTenantLookup
|
||||
Knowledges KnowledgeOwnerLookup
|
||||
Bindings interfaces.KBResourceLookup
|
||||
}
|
||||
|
||||
// resourceAccessibleViaSharedKB reports whether the message's persisted
|
||||
// retrieval evidence proves the resource came from an org-shared KB the
|
||||
// caller may read. This is the fallback for replies whose agent belongs to
|
||||
// the caller's own workspace while the retrieved resources belong to the
|
||||
// workspace that shared the knowledge base (#3022).
|
||||
//
|
||||
// Evidence required from one retrieval record: a canonical resource://
|
||||
// handle (not a prefix of a longer token) appears in the chunk text or
|
||||
// image_info, its knowledge base belongs to the resource's tenant, and
|
||||
// that KB is org-shared to the caller with at least viewer permission, and
|
||||
// an independent live resource binding confirms the file still belongs to it.
|
||||
// Smart-reasoning turns persist that evidence on AgentSteps when
|
||||
// KnowledgeReferences was never filled. Any lookup failure fails closed.
|
||||
func (a MessageKBShareAuthorizer) resourceAccessibleViaSharedKB(
|
||||
ctx context.Context,
|
||||
message *types.Message,
|
||||
resource *types.StoredResource,
|
||||
callerTenantID uint64,
|
||||
callerTenantRole types.TenantRole,
|
||||
) bool {
|
||||
if a.ShareGuard == nil || a.KBs == nil || a.Bindings == nil || message == nil || resource == nil {
|
||||
return false
|
||||
}
|
||||
handle, ok := types.ParseResourcePath(types.BuildResourcePath(resource.Handle))
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
kbIDs := a.collectSharedKBEvidenceIDs(ctx, message, handle)
|
||||
if len(kbIDs) == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
kbs, err := a.KBs.GetKnowledgeBasesByIDsOnly(ctx, kbIDs)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
permissions := NewKBSharePermissions(ctx, a.ShareGuard, callerTenantID, callerTenantRole)
|
||||
for _, kb := range kbs {
|
||||
if kb == nil || kb.TenantID != resource.TenantID {
|
||||
continue
|
||||
}
|
||||
shared, err := permissions.Check(kb.ID, types.OrgRoleViewer)
|
||||
if err == nil && shared {
|
||||
bound, bindingErr := a.Bindings.IsReferencedByKnowledgeBase(
|
||||
ctx, resource.TenantID, kb.ID, types.BuildResourcePath(handle))
|
||||
if bindingErr == nil && bound {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (a MessageKBShareAuthorizer) collectSharedKBEvidenceIDs(
|
||||
ctx context.Context,
|
||||
message *types.Message,
|
||||
handle string,
|
||||
) []string {
|
||||
seenKB := make(map[string]bool)
|
||||
seenKnowledge := make(map[string]bool)
|
||||
var kbIDs, knowledgeIDs []string
|
||||
addKB := func(id string) {
|
||||
if id == "" || seenKB[id] {
|
||||
return
|
||||
}
|
||||
seenKB[id] = true
|
||||
kbIDs = append(kbIDs, id)
|
||||
}
|
||||
addKnowledge := func(id string) {
|
||||
if id == "" || seenKnowledge[id] {
|
||||
return
|
||||
}
|
||||
seenKnowledge[id] = true
|
||||
knowledgeIDs = append(knowledgeIDs, id)
|
||||
}
|
||||
|
||||
for _, ref := range message.KnowledgeReferences {
|
||||
if !searchResultHasResourceHandle(ref, handle) {
|
||||
continue
|
||||
}
|
||||
if ref.KnowledgeBaseID != "" {
|
||||
addKB(ref.KnowledgeBaseID)
|
||||
continue
|
||||
}
|
||||
addKnowledge(ref.KnowledgeID)
|
||||
}
|
||||
collectKBEvidenceFromValue(message.AgentSteps, handle, "", "", addKB, addKnowledge)
|
||||
|
||||
if a.Knowledges != nil {
|
||||
for _, knowledgeID := range knowledgeIDs {
|
||||
knowledge, err := a.Knowledges.GetKnowledgeByIDOnly(ctx, knowledgeID)
|
||||
if err != nil || knowledge == nil {
|
||||
continue
|
||||
}
|
||||
addKB(knowledge.KnowledgeBaseID)
|
||||
}
|
||||
}
|
||||
return kbIDs
|
||||
}
|
||||
|
||||
func searchResultHasResourceHandle(ref *types.SearchResult, handle string) bool {
|
||||
if ref == nil {
|
||||
return false
|
||||
}
|
||||
return textHasResourceHandle(ref.Content, handle) ||
|
||||
textHasResourceHandle(ref.MatchedContent, handle) ||
|
||||
textHasResourceHandle(ref.ImageInfo, handle)
|
||||
}
|
||||
|
||||
func textHasResourceHandle(text, handle string) bool {
|
||||
if text == "" || handle == "" {
|
||||
return false
|
||||
}
|
||||
want := types.BuildResourcePath(handle)
|
||||
for _, ref := range types.ScanResourceReferences(text) {
|
||||
if ref == want {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func collectKBEvidenceFromValue(
|
||||
v interface{},
|
||||
handle, kbID, knowledgeID string,
|
||||
addKB, addKnowledge func(string),
|
||||
) {
|
||||
switch val := v.(type) {
|
||||
case string:
|
||||
if !textHasResourceHandle(val, handle) {
|
||||
return
|
||||
}
|
||||
if kbID != "" {
|
||||
addKB(kbID)
|
||||
return
|
||||
}
|
||||
addKnowledge(knowledgeID)
|
||||
case types.AgentSteps:
|
||||
for _, step := range val {
|
||||
collectKBEvidenceFromValue(step, handle, kbID, knowledgeID, addKB, addKnowledge)
|
||||
}
|
||||
case types.AgentStep:
|
||||
collectKBEvidenceFromValue(val.ToolCalls, handle, kbID, knowledgeID, addKB, addKnowledge)
|
||||
case []types.ToolCall:
|
||||
for _, call := range val {
|
||||
collectKBEvidenceFromValue(call, handle, kbID, knowledgeID, addKB, addKnowledge)
|
||||
}
|
||||
case types.ToolCall:
|
||||
if val.Result != nil {
|
||||
collectKBEvidenceFromValue(val.Result.Output, handle, kbID, knowledgeID, addKB, addKnowledge)
|
||||
collectKBEvidenceFromValue(val.Result.Data, handle, kbID, knowledgeID, addKB, addKnowledge)
|
||||
}
|
||||
case map[string]interface{}:
|
||||
nextKB := firstNonEmptyString(
|
||||
stringFromAnyMap(val, "knowledge_base_id"),
|
||||
stringFromAnyMap(val, "knowledge_base"),
|
||||
kbID,
|
||||
)
|
||||
nextKnowledge := firstNonEmptyString(stringFromAnyMap(val, "knowledge_id"), knowledgeID)
|
||||
for _, nested := range val {
|
||||
collectKBEvidenceFromValue(nested, handle, nextKB, nextKnowledge, addKB, addKnowledge)
|
||||
}
|
||||
case []interface{}:
|
||||
for _, item := range val {
|
||||
collectKBEvidenceFromValue(item, handle, kbID, knowledgeID, addKB, addKnowledge)
|
||||
}
|
||||
case []map[string]interface{}:
|
||||
for _, item := range val {
|
||||
collectKBEvidenceFromValue(item, handle, kbID, knowledgeID, addKB, addKnowledge)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func stringFromAnyMap(m map[string]interface{}, key string) string {
|
||||
if m == nil {
|
||||
return ""
|
||||
}
|
||||
s, _ := m[key].(string)
|
||||
return strings.TrimSpace(s)
|
||||
}
|
||||
|
||||
func firstNonEmptyString(values ...string) string {
|
||||
for _, value := range values {
|
||||
if strings.TrimSpace(value) != "" {
|
||||
return strings.TrimSpace(value)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package access
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrResourceNotFound means the ownership lookup found no resource visible
|
||||
// in the caller's tenant. HTTP adapters decide how to produce the 404.
|
||||
ErrResourceNotFound = errors.New("rbac: resource not found")
|
||||
// ErrOwnershipForbidden indicates neither ownership nor the required role.
|
||||
ErrOwnershipForbidden = errors.New("rbac: ownership or role insufficient")
|
||||
)
|
||||
|
||||
// OwnershipRequest carries server-resolved identity and rollout policy. The
|
||||
// cross-tenant bypass must already account for the cluster configuration.
|
||||
// This gate does not replace API-key capabilities or resource-scope checks.
|
||||
type OwnershipRequest struct {
|
||||
UserID string
|
||||
Role types.TenantRole
|
||||
APIKey bool
|
||||
CrossTenantSuperuser bool
|
||||
Enforce bool
|
||||
}
|
||||
|
||||
// OwnershipDecision contains the details adapters need for logs and audits.
|
||||
// The error returned with it determines whether access was allowed.
|
||||
type OwnershipDecision struct {
|
||||
CreatorID string
|
||||
EnforcementSkipped bool
|
||||
LookupFailed bool
|
||||
}
|
||||
|
||||
// CreatorRoleFloor is the lowest role at which creating a resource still lets
|
||||
// the caller manage it. Below it a member mutates nothing, including what they
|
||||
// created before being demoted.
|
||||
const CreatorRoleFloor = types.TenantRoleContributor
|
||||
|
||||
// CheckOwnershipOrRole performs no resource lookup when API-key authorization,
|
||||
// role, superuser status, or the RBAC rollout policy already settles the gate.
|
||||
// The lookup must enforce tenant visibility before returning a creator ID.
|
||||
func CheckOwnershipOrRole(
|
||||
request OwnershipRequest,
|
||||
required types.TenantRole,
|
||||
lookup func() (string, error),
|
||||
) (OwnershipDecision, error) {
|
||||
var decision OwnershipDecision
|
||||
if request.APIKey || request.Role.HasPermission(required) || request.CrossTenantSuperuser {
|
||||
return decision, nil
|
||||
}
|
||||
if !request.Enforce {
|
||||
decision.EnforcementSkipped = true
|
||||
return decision, nil
|
||||
}
|
||||
if lookup == nil {
|
||||
decision.LookupFailed = true
|
||||
return decision, errors.New("rbac: creator lookup unavailable")
|
||||
}
|
||||
creator, err := lookup()
|
||||
decision.CreatorID = creator
|
||||
if errors.Is(err, ErrResourceNotFound) {
|
||||
return decision, ErrResourceNotFound
|
||||
}
|
||||
if err != nil {
|
||||
decision.LookupFailed = true
|
||||
return decision, err
|
||||
}
|
||||
if creator != "" && creator == request.UserID && request.Role.HasPermission(CreatorRoleFloor) {
|
||||
return decision, nil
|
||||
}
|
||||
return decision, ErrOwnershipForbidden
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package access
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestCheckOwnershipOrRoleSkipsLookupWhenGateAlreadyResolved(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
request OwnershipRequest
|
||||
skipped bool
|
||||
}{
|
||||
{name: "API key", request: OwnershipRequest{APIKey: true, Role: types.TenantRoleViewer, Enforce: true}},
|
||||
{name: "admin", request: OwnershipRequest{Role: types.TenantRoleAdmin, Enforce: true}},
|
||||
{name: "owner role", request: OwnershipRequest{Role: types.TenantRoleOwner, Enforce: true}},
|
||||
{
|
||||
name: "cross tenant superuser",
|
||||
request: OwnershipRequest{
|
||||
Role: types.TenantRoleViewer,
|
||||
CrossTenantSuperuser: true,
|
||||
Enforce: true,
|
||||
},
|
||||
},
|
||||
|
||||
{name: "enforcement disabled", request: OwnershipRequest{Role: types.TenantRoleViewer}, skipped: true},
|
||||
{name: "role before rollout", request: OwnershipRequest{Role: types.TenantRoleAdmin}},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
decision, err := CheckOwnershipOrRole(tt.request, types.TenantRoleAdmin, func() (string, error) {
|
||||
t.Fatal("ownership lookup must not run on a fast path")
|
||||
return "", errors.New("unavailable")
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tt.skipped, decision.EnforcementSkipped)
|
||||
require.False(t, decision.LookupFailed)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckOwnershipOrRoleResolvesCreator(t *testing.T) {
|
||||
failure := errors.New("database unavailable")
|
||||
for _, tt := range []struct {
|
||||
name, user, creator string
|
||||
lookupErr, wantErr error
|
||||
lookupFailed bool
|
||||
}{
|
||||
{name: "creator", user: "user", creator: "user"},
|
||||
{name: "other creator", user: "user", creator: "other", wantErr: ErrOwnershipForbidden},
|
||||
{name: "tenant owned", user: "user", wantErr: ErrOwnershipForbidden},
|
||||
{name: "missing identity cannot match empty creator", wantErr: ErrOwnershipForbidden},
|
||||
{name: "missing resource", user: "user", lookupErr: ErrResourceNotFound, wantErr: ErrResourceNotFound},
|
||||
{
|
||||
name: "wrapped missing resource",
|
||||
user: "user",
|
||||
lookupErr: fmt.Errorf("load: %w",
|
||||
ErrResourceNotFound),
|
||||
wantErr: ErrResourceNotFound,
|
||||
},
|
||||
|
||||
{
|
||||
name: "lookup failure wins over creator match",
|
||||
user: "user",
|
||||
creator: "user",
|
||||
lookupErr: failure,
|
||||
wantErr: failure,
|
||||
lookupFailed: true,
|
||||
},
|
||||
|
||||
{
|
||||
name: "lookup denial remains a lookup failure",
|
||||
lookupErr: ErrOwnershipForbidden,
|
||||
wantErr: ErrOwnershipForbidden,
|
||||
lookupFailed: true,
|
||||
},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
calls := 0
|
||||
decision, err := CheckOwnershipOrRole(
|
||||
OwnershipRequest{UserID: tt.user, Role: types.TenantRoleContributor, Enforce: true},
|
||||
types.TenantRoleAdmin,
|
||||
func() (string, error) {
|
||||
calls++
|
||||
return tt.creator, tt.lookupErr
|
||||
},
|
||||
)
|
||||
require.Equal(t, 1, calls)
|
||||
require.ErrorIs(t, err, tt.wantErr)
|
||||
require.Equal(t, tt.creator, decision.CreatorID)
|
||||
require.Equal(t, tt.lookupFailed, decision.LookupFailed)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckOwnershipOrRoleMissingLookupFailsClosed(t *testing.T) {
|
||||
decision, err := CheckOwnershipOrRole(
|
||||
OwnershipRequest{Role: types.TenantRoleContributor, Enforce: true}, types.TenantRoleAdmin, nil)
|
||||
require.Error(t, err)
|
||||
require.True(t, decision.LookupFailed)
|
||||
}
|
||||
|
||||
func TestCheckOwnershipOrRoleDeniesCreatorsBelowTheFloor(t *testing.T) {
|
||||
for _, role := range []types.TenantRole{types.TenantRoleViewer, ""} {
|
||||
t.Run(string(role)+"-creator", func(t *testing.T) {
|
||||
decision, err := CheckOwnershipOrRole(
|
||||
OwnershipRequest{UserID: "user", Role: role, Enforce: true},
|
||||
types.TenantRoleAdmin,
|
||||
func() (string, error) { return "user", nil },
|
||||
)
|
||||
require.ErrorIs(t, err, ErrOwnershipForbidden)
|
||||
require.False(t, decision.LookupFailed)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckOwnershipOrRoleKeepsNotFoundBelowTheFloor(t *testing.T) {
|
||||
_, err := CheckOwnershipOrRole(
|
||||
OwnershipRequest{UserID: "user", Role: types.TenantRoleViewer, Enforce: true},
|
||||
types.TenantRoleAdmin,
|
||||
func() (string, error) { return "", ErrResourceNotFound },
|
||||
)
|
||||
require.ErrorIs(t, err, ErrResourceNotFound)
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package access
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"academy/internal/config"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// IsCrossTenantSuperuser reports whether the caller's user attribute and the
|
||||
// cluster-wide flag both allow bypassing workspace role gates. API-key and
|
||||
// resource-scope authorization remain separate checks.
|
||||
func IsCrossTenantSuperuser(ctx context.Context, cfg *config.Config) bool {
|
||||
if cfg == nil || cfg.Tenant == nil || !cfg.Tenant.EnableCrossTenantAccess {
|
||||
return false
|
||||
}
|
||||
u, ok := ctx.Value(types.UserContextKey).(*types.User)
|
||||
return ok && u != nil && u.CanAccessAllTenants
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
# Chat attachment boundaries
|
||||
|
||||
Attachments remain readable without a sandbox. Durable storage and the temporary-document
|
||||
row are authoritative; sandbox files are disposable copies.
|
||||
|
||||
| Responsibility | Owner |
|
||||
| --- | --- |
|
||||
| Upload, session access, retention, task scheduling | `service/temporary_document.go` |
|
||||
| Parser, OCR, image extraction, chunking | `service/temporary_document_parse.go` |
|
||||
| Quick Answer excerpts and Agent attachment manifest | `service/temporary_document_prompt.go` |
|
||||
| Authorized reads, bounded parse waits | `attachment/Reader` |
|
||||
| Image preparation, scoped observations and reuse | `attachment/ImageReader` |
|
||||
| Observation persistence and concurrent updates | `repository/attachment_descriptions.go` |
|
||||
| Turn-start original/parsed-file reconciliation | `service/session_attachment_staging.go` |
|
||||
| Copies produced by a successful read | `service/attachment_sandbox.go` |
|
||||
| URI routing, pagination, image numbering and tool output | `agent/tools/read_file_attachment.go` |
|
||||
| Vision transport and fallback for other tools | `agent/engine.go`, `agent/tool_images.go` |
|
||||
|
||||
`agent_attachments.go` wires session-scoped storage adapters into `Reader`, then
|
||||
passes only `interfaces.AttachmentReader` to `read_file`. The reader authorizes
|
||||
against persisted message attachments before looking up the tenant's document,
|
||||
including documents inherited from a parent session. Neither the tool nor the
|
||||
Agent engine queries attachment repositories.
|
||||
|
||||
## Read and synchronization flow
|
||||
|
||||
1. At turn start, stage originals and already-ready parsed text if the selected
|
||||
sandbox supports session input files. Host workspaces have no input directory
|
||||
and are never used for attachment staging.
|
||||
2. `read_file attachment://...` resolves the session attachment and waits within
|
||||
the configured parse budget. A successful read projects newly-ready parsed
|
||||
text immediately, including when parsing finished after turn-start staging.
|
||||
3. Image reads default to one image with `brief` plus an optional `focus`.
|
||||
Use complete `attachment://<handle>/images/N` addresses, never bare `/images/N`.
|
||||
Exact chart/table values and calculations use `full` with a focused question;
|
||||
full reads return at most one image. Explicit brief batches are capped at four.
|
||||
Observations preserve category, series and unit alongside each value. Missing
|
||||
associations or inconsistent totals require a focused re-read, not guessed data.
|
||||
4. Non-vision chat models use the configured VLM. Successful observations are
|
||||
keyed by document, prepared-image hash, model ID and normalized reading prompt
|
||||
(including detail/focus). Equal requests reuse the observation across turns
|
||||
and authorized forks; different requirements do not reuse a narrower answer.
|
||||
Descriptions have a 60-second deadline (150 seconds for full reads), starting
|
||||
after a model slot is acquired. Failed or empty descriptions
|
||||
are not cached, and the engine does not repeat an attempted description.
|
||||
5. The document metadata stores a bounded observation cache through optimistic
|
||||
updates that preserve parser metadata and concurrent writes. Cache entries
|
||||
inherit the document's deletion and retention rules. They are not merged into
|
||||
parsed Markdown or presented as exhaustive OCR.
|
||||
6. After an image read, copy the prepared image and any available observation to
|
||||
`<original>.assets/`. Tool results expose the paths, and observations carry
|
||||
their source, detail, focus, model and timestamp. Normal turn-start staging
|
||||
preserves these files while the original belongs to the session. After a
|
||||
sandbox rebuild, the next read recreates copies from durable data/cache.
|
||||
|
||||
No sandbox is needed for steps 2–5. Projection failures are reported separately
|
||||
and do not turn a successful durable read into a failure. Native vision sends
|
||||
images directly to the chat model and copies the image if a sandbox is present;
|
||||
it does not perform an extra VLM call just to manufacture a cached observation.
|
||||
|
||||
The cache reuses observations for the same model ID and prompt, not arbitrary
|
||||
semantic similarity between focus strings. Raw VLM reasoning from a native vision
|
||||
response is not an attachment artifact. These boundaries keep cache scope explicit
|
||||
and avoid speculative re-reading of every extracted image.
|
||||
@@ -0,0 +1,183 @@
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"academy/internal/models/imageprep"
|
||||
"academy/internal/searchutil"
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"golang.org/x/sync/singleflight"
|
||||
)
|
||||
|
||||
const (
|
||||
// Deadlines start once a VLM slot is held, so queueing behind other reads
|
||||
// does not eat into the model's time. Full transcriptions run longer.
|
||||
imageDescribeTimeout = 60 * time.Second
|
||||
imageDescribeFullTimeout = 150 * time.Second
|
||||
imageDescribeSlots = 4
|
||||
)
|
||||
|
||||
// Description records the scope of an observation; it is never merged into
|
||||
// parsed document text or treated as a complete reading of the image.
|
||||
type Description struct {
|
||||
Text string `json:"text"`
|
||||
Detail string `json:"detail"`
|
||||
Focus string `json:"focus,omitempty"`
|
||||
Model string `json:"model"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// DescriptionCache persists scoped observations alongside their owning document.
|
||||
type DescriptionCache interface {
|
||||
Get(ctx context.Context, documentID, key string) (*Description, error)
|
||||
Put(ctx context.Context, documentID, key string, value Description) error
|
||||
}
|
||||
|
||||
// Projection is optional. The durable document and cache remain usable when
|
||||
// the sandbox is absent, expires, or fails to accept a copy.
|
||||
type Projection interface {
|
||||
Document(context.Context, *types.TemporaryDocument) (string, error)
|
||||
Image(
|
||||
ctx context.Context, doc *types.TemporaryDocument, number int,
|
||||
data []byte, mime, key string, description *Description,
|
||||
) (map[string]string, error)
|
||||
}
|
||||
|
||||
// ImageReader describes requested images and reuses equivalent prior observations.
|
||||
type ImageReader struct {
|
||||
Model string
|
||||
Describe func(context.Context, []byte, string) (string, error)
|
||||
Cache DescriptionCache
|
||||
calls singleflight.Group
|
||||
slotsOnce sync.Once
|
||||
slots chan struct{}
|
||||
}
|
||||
|
||||
// ReadImages authorizes the document once, then prepares, describes and
|
||||
// projects the requested images concurrently.
|
||||
func (r *Reader) ReadImages(
|
||||
ctx context.Context, documentID string, numbers []int, detail, focus string,
|
||||
) ([]interfaces.AttachmentImageRead, error) {
|
||||
resolved, err := r.Resolve(ctx, documentID, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
doc := resolved.Document
|
||||
if doc == nil || doc.Status != types.TemporaryDocumentStatusReady {
|
||||
return nil, fmt.Errorf("attachment is not ready")
|
||||
}
|
||||
if r.readImage == nil {
|
||||
return nil, fmt.Errorf("attachment image storage is unavailable")
|
||||
}
|
||||
images := doc.ViewableImages()
|
||||
reads := make([]interfaces.AttachmentImageRead, len(numbers))
|
||||
var wg sync.WaitGroup
|
||||
for i, number := range numbers {
|
||||
reads[i].Number = number
|
||||
if number < 1 || number > len(images) {
|
||||
reads[i].Err = fmt.Errorf("image number out of range")
|
||||
continue
|
||||
}
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
reads[i].Image, reads[i].Err = r.readImageAt(ctx, doc, number, images[number-1].URL, detail, focus)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
return reads, nil
|
||||
}
|
||||
|
||||
func (r *Reader) readImageAt(
|
||||
ctx context.Context, doc *types.TemporaryDocument, number int, url, detail, focus string,
|
||||
) (*interfaces.AttachmentImage, error) {
|
||||
data, err := r.readImage(ctx, url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
prepared, err := imageprep.Prepare(data, searchutil.VisionImageLimits)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to prepare image %d: %w", number, err)
|
||||
}
|
||||
result := &interfaces.AttachmentImage{DataURI: prepared.DataURI()}
|
||||
var description *Description
|
||||
var key string
|
||||
if r.Images != nil && r.Images.Describe != nil {
|
||||
text := ""
|
||||
result.Description = &text
|
||||
description, key, err = r.Images.describe(ctx, doc.ID, prepared.Data, detail, focus)
|
||||
if description != nil {
|
||||
*result.Description = description.Text
|
||||
}
|
||||
if err != nil {
|
||||
result.Warning = "Image description: " + err.Error()
|
||||
}
|
||||
}
|
||||
if r.Projection != nil {
|
||||
result.Files, err = r.Projection.Image(ctx, doc, number, prepared.Data, prepared.MIMEType, key, description)
|
||||
if err != nil {
|
||||
result.Warning = strings.TrimSpace(result.Warning + " Could not sync image to sandbox: " + err.Error())
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (r *ImageReader) describe(
|
||||
ctx context.Context, documentID string, data []byte, detail, focus string,
|
||||
) (*Description, string, error) {
|
||||
detail, focus = types.NormalizeImageRead(detail, focus)
|
||||
prompt := types.ImageReadPrompt(detail, focus)
|
||||
identity, _ := json.Marshal([]string{r.Model, prompt, fmt.Sprintf("%x", sha256.Sum256(data))})
|
||||
key := fmt.Sprintf("%x", sha256.Sum256(identity))
|
||||
timeout := imageDescribeTimeout
|
||||
if detail == types.ImageDetailFull {
|
||||
timeout = imageDescribeFullTimeout
|
||||
}
|
||||
// Coalesce duplicate reads in one engine; the durable cache also serves
|
||||
// subsequent turns and forked sessions after their own authorization.
|
||||
// The shared call is detached from whichever caller started it, so one
|
||||
// caller giving up cannot fail the others waiting on the same image.
|
||||
shared := context.WithoutCancel(ctx)
|
||||
result := r.calls.DoChan(documentID+":"+key, func() (interface{}, error) {
|
||||
if r.Cache != nil {
|
||||
cached, err := r.Cache.Get(shared, documentID, key)
|
||||
if err == nil && cached != nil {
|
||||
return cached, nil
|
||||
}
|
||||
}
|
||||
r.slotsOnce.Do(func() { r.slots = make(chan struct{}, imageDescribeSlots) })
|
||||
r.slots <- struct{}{}
|
||||
defer func() { <-r.slots }()
|
||||
imageCtx, cancel := context.WithTimeout(shared, timeout)
|
||||
defer cancel()
|
||||
text, err := r.Describe(imageCtx, data, prompt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
text = strings.TrimSpace(text)
|
||||
if text == "" {
|
||||
return nil, fmt.Errorf("vision model returned no description")
|
||||
}
|
||||
value := &Description{Text: text, Detail: detail, Focus: focus, Model: r.Model, CreatedAt: time.Now().UTC()}
|
||||
if r.Cache != nil {
|
||||
if err := r.Cache.Put(shared, documentID, key, *value); err != nil {
|
||||
return value, fmt.Errorf("save description: %w", err)
|
||||
}
|
||||
}
|
||||
return value, nil
|
||||
})
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, key, ctx.Err()
|
||||
case value := <-result:
|
||||
description, _ := value.Val.(*Description)
|
||||
return description, key, value.Err
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
// Package attachment owns session-authorized attachment reads. It has no agent,
|
||||
// tool, database or sandbox dependency; adapters supply storage and projections.
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
)
|
||||
|
||||
const pollInterval = 500 * time.Millisecond
|
||||
|
||||
// Store supplies the session inventory and tenant-scoped document lookup.
|
||||
type Store interface {
|
||||
SessionAttachments(context.Context) (types.MessageAttachments, error)
|
||||
TemporaryDocument(context.Context, string) (*types.TemporaryDocument, error)
|
||||
}
|
||||
|
||||
// Reader coordinates authorized attachment reads independently of tools and sandboxes.
|
||||
type Reader struct {
|
||||
store Store
|
||||
parseWait time.Duration
|
||||
readImage func(context.Context, string) ([]byte, error)
|
||||
Images *ImageReader
|
||||
Projection Projection
|
||||
}
|
||||
|
||||
// NewReader binds durable storage to one conversation and its parse wait budget.
|
||||
func NewReader(store Store, wait time.Duration, readImage func(context.Context, string) ([]byte, error)) *Reader {
|
||||
return &Reader{store: store, parseWait: wait, readImage: readImage}
|
||||
}
|
||||
|
||||
// WaitTimeout bounds parsing plus one image batch: the batch is described
|
||||
// concurrently, with room for one queue round behind other reads.
|
||||
func (r *Reader) WaitTimeout() time.Duration {
|
||||
wait := r.parseWait
|
||||
if r.Images != nil && r.Images.Describe != nil {
|
||||
wait += imageDescribeFullTimeout + imageDescribeTimeout
|
||||
}
|
||||
return wait
|
||||
}
|
||||
|
||||
// List loads the authorized inventory once, then resolves each document without
|
||||
// waiting or projecting files. Listing must not reload the message history per item.
|
||||
func (r *Reader) List(ctx context.Context) ([]interfaces.AttachmentDocument, error) {
|
||||
inventory, err := r.inventory(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]interfaces.AttachmentDocument, 0, len(inventory))
|
||||
for _, item := range inventory {
|
||||
doc, err := r.store.TemporaryDocument(ctx, item.ID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load attachment %s: %w", item.ID, err)
|
||||
}
|
||||
out = append(out, interfaces.AttachmentDocument{Attachment: item, Document: doc})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Resolve opens a session attachment, optionally waiting for parsing and syncing its text.
|
||||
func (r *Reader) Resolve(ctx context.Context, ref string, wait bool) (*interfaces.AttachmentDocument, error) {
|
||||
inventory, err := r.inventory(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
item, err := findAttachment(inventory, ref)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %v", interfaces.ErrAttachmentNotFound, err)
|
||||
}
|
||||
var doc *types.TemporaryDocument
|
||||
if wait {
|
||||
doc, err = r.awaitDocument(ctx, item.ID)
|
||||
} else {
|
||||
doc, err = r.store.TemporaryDocument(ctx, item.ID)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := &interfaces.AttachmentDocument{Attachment: item, Document: doc}
|
||||
if wait && doc != nil && doc.Status == types.TemporaryDocumentStatusReady && r.Projection != nil {
|
||||
result.ParsedPath, err = r.Projection.Document(ctx, doc)
|
||||
if err != nil {
|
||||
result.Warning = "Could not sync parsed text to sandbox: " + err.Error()
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// inventory returns the session's stored attachments, deduplicated by ID.
|
||||
// Inline uploads without a stored document have nothing to read and are left
|
||||
// out.
|
||||
func (r *Reader) inventory(ctx context.Context) (types.MessageAttachments, error) {
|
||||
if r.store == nil {
|
||||
return nil, fmt.Errorf("attachments are unavailable")
|
||||
}
|
||||
all, err := r.store.SessionAttachments(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to load conversation attachments: %w", err)
|
||||
}
|
||||
seen := make(map[string]int, len(all))
|
||||
out := make(types.MessageAttachments, 0, len(all))
|
||||
for _, attachment := range all {
|
||||
id := strings.TrimSpace(attachment.ID)
|
||||
if id == "" {
|
||||
continue
|
||||
}
|
||||
if i, ok := seen[id]; ok {
|
||||
// Later rows carry the content persisted after resolution.
|
||||
if out[i].Content == "" {
|
||||
out[i] = attachment
|
||||
}
|
||||
continue
|
||||
}
|
||||
seen[id] = len(out)
|
||||
out = append(out, attachment)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func findAttachment(inventory types.MessageAttachments, ref string) (types.MessageAttachment, error) {
|
||||
ref = strings.TrimSpace(ref)
|
||||
var byName []types.MessageAttachment
|
||||
for _, attachment := range inventory {
|
||||
if types.AttachmentHandle(attachment.ID) == ref || attachment.ID == ref {
|
||||
return attachment, nil
|
||||
}
|
||||
if strings.EqualFold(attachment.FileName, ref) {
|
||||
byName = append(byName, attachment)
|
||||
}
|
||||
}
|
||||
if len(byName) > 0 {
|
||||
return byName[len(byName)-1], nil
|
||||
}
|
||||
paths := make([]string, 0, len(inventory))
|
||||
for _, attachment := range inventory {
|
||||
paths = append(paths, fmt.Sprintf("%s (%s)", types.AttachmentPath(attachment.ID), attachment.FileName))
|
||||
}
|
||||
if len(paths) == 0 {
|
||||
return types.MessageAttachment{}, fmt.Errorf("this conversation has no readable attachments")
|
||||
}
|
||||
return types.MessageAttachment{}, fmt.Errorf(
|
||||
"unknown attachment %q; available: %s", ref, strings.Join(paths, ", "))
|
||||
}
|
||||
|
||||
// awaitDocument loads the document, polling while it is still being parsed
|
||||
// until parseWait elapses or ctx is cancelled.
|
||||
func (r *Reader) awaitDocument(ctx context.Context, id string) (*types.TemporaryDocument, error) {
|
||||
deadline := time.Now().Add(r.parseWait)
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
document, err := r.store.TemporaryDocument(ctx, id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to load attachment: %w", err)
|
||||
}
|
||||
if document == nil || !attachmentPending(document.Status) || !time.Now().Before(deadline) {
|
||||
return document, nil
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-time.After(pollInterval):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func attachmentPending(status string) bool {
|
||||
return status == types.TemporaryDocumentStatusUploaded || status == types.TemporaryDocumentStatusProcessing
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/png"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type testStore struct {
|
||||
doc *types.TemporaryDocument
|
||||
allowed bool
|
||||
loads int
|
||||
}
|
||||
|
||||
func (s *testStore) SessionAttachments(context.Context) (types.MessageAttachments, error) {
|
||||
if !s.allowed {
|
||||
return nil, nil
|
||||
}
|
||||
return types.MessageAttachments{{ID: s.doc.ID, FileName: "report.pdf"}}, nil
|
||||
}
|
||||
|
||||
func (s *testStore) TemporaryDocument(context.Context, string) (*types.TemporaryDocument, error) {
|
||||
s.loads++
|
||||
return s.doc, nil
|
||||
}
|
||||
|
||||
type testCache struct {
|
||||
mu sync.Mutex
|
||||
values map[string]Description
|
||||
fail bool
|
||||
}
|
||||
|
||||
func (c *testCache) Get(_ context.Context, id, key string) (*Description, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.fail {
|
||||
return nil, errors.New("cache offline")
|
||||
}
|
||||
v, ok := c.values[id+key]
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
return &v, nil
|
||||
}
|
||||
|
||||
func (c *testCache) Put(_ context.Context, id, key string, v Description) error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.fail {
|
||||
return errors.New("cache offline")
|
||||
}
|
||||
c.values[id+key] = v
|
||||
return nil
|
||||
}
|
||||
|
||||
func imageFixture(t *testing.T) (*testStore, []byte) {
|
||||
t.Helper()
|
||||
var b bytes.Buffer
|
||||
require.NoError(t, png.Encode(&b, image.NewRGBA(image.Rect(0, 0, 2, 2))))
|
||||
return &testStore{allowed: true, doc: &types.TemporaryDocument{
|
||||
ID: "document", Status: types.TemporaryDocumentStatusReady,
|
||||
ResourceRef: "local://owner/image", MimeType: "image/png",
|
||||
}}, b.Bytes()
|
||||
}
|
||||
|
||||
func readOne(
|
||||
ctx context.Context, reader *Reader, number int, detail, focus string,
|
||||
) (*interfaces.AttachmentImage, error) {
|
||||
reads, err := reader.ReadImages(ctx, "document", []int{number}, detail, focus)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return reads[0].Image, reads[0].Err
|
||||
}
|
||||
|
||||
func TestReaderAuthorizesBeforeDocumentImageOrCacheAccess(t *testing.T) {
|
||||
store, data := imageFixture(t)
|
||||
store.allowed = false
|
||||
reader := NewReader(store, 0, func(context.Context, string) ([]byte, error) {
|
||||
t.Fatal("unauthorized file access")
|
||||
return data, nil
|
||||
})
|
||||
_, err := readOne(context.Background(), reader, 1, "brief", "")
|
||||
require.ErrorIs(t, err, interfaces.ErrAttachmentNotFound)
|
||||
require.Zero(t, store.loads)
|
||||
}
|
||||
|
||||
func TestDescriptionsSurviveReadersAndSeparateReadingRequirements(t *testing.T) {
|
||||
store, data := imageFixture(t)
|
||||
cache := &testCache{values: map[string]Description{}}
|
||||
calls := 0
|
||||
makeReader := func(model string) *Reader {
|
||||
reader := NewReader(store, 0, func(context.Context, string) ([]byte, error) { return data, nil })
|
||||
reader.Images = &ImageReader{
|
||||
Model: model, Cache: cache,
|
||||
Describe: func(ctx context.Context, _ []byte, prompt string) (string, error) {
|
||||
calls++
|
||||
deadline, ok := ctx.Deadline()
|
||||
require.True(t, ok)
|
||||
require.LessOrEqual(t, time.Until(deadline), imageDescribeFullTimeout)
|
||||
return prompt, nil
|
||||
},
|
||||
}
|
||||
return reader
|
||||
}
|
||||
ctx := context.Background()
|
||||
first, err := readOne(ctx, makeReader("vision-a"), 1, "", " axes ")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, first.Description)
|
||||
again, err := readOne(ctx, makeReader("vision-a"), 1, "brief", "axes")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, first.Description, again.Description)
|
||||
require.Equal(t, 1, calls)
|
||||
for _, tc := range []struct{ model, detail, focus string }{
|
||||
{"vision-a", "brief", "legend"}, {"vision-a", "full", "axes"}, {"vision-b", "brief", "axes"},
|
||||
} {
|
||||
_, err = readOne(ctx, makeReader(tc.model), 1, tc.detail, tc.focus)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
require.Equal(t, 4, calls)
|
||||
data = append(data, 0) // Different source bytes cannot reuse the observation.
|
||||
_, err = readOne(ctx, makeReader("vision-a"), 1, "brief", "axes")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 5, calls)
|
||||
}
|
||||
|
||||
func TestFailedDescriptionsAreRetriedAndCacheFailureDoesNotLoseResult(t *testing.T) {
|
||||
store, data := imageFixture(t)
|
||||
cache := &testCache{values: map[string]Description{}}
|
||||
reader := NewReader(store, 0, func(context.Context, string) ([]byte, error) { return data, nil })
|
||||
calls := 0
|
||||
reader.Images = &ImageReader{Cache: cache, Describe: func(context.Context, []byte, string) (string, error) {
|
||||
calls++
|
||||
if calls == 1 {
|
||||
return "", errors.New("model unavailable")
|
||||
}
|
||||
return "chart", nil
|
||||
}}
|
||||
first, err := readOne(context.Background(), reader, 1, "brief", "")
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, first.Warning)
|
||||
require.Empty(t, *first.Description)
|
||||
second, err := readOne(context.Background(), reader, 1, "brief", "")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "chart", *second.Description)
|
||||
require.Equal(t, 2, calls)
|
||||
cache.fail = true
|
||||
third, err := readOne(context.Background(), reader, 1, "brief", "new focus")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "chart", *third.Description)
|
||||
require.Contains(t, third.Warning, "save description")
|
||||
}
|
||||
|
||||
type failedProjection struct{ images int }
|
||||
|
||||
func (*failedProjection) Document(context.Context, *types.TemporaryDocument) (string, error) {
|
||||
return "", errors.New("sandbox offline")
|
||||
}
|
||||
|
||||
func (p *failedProjection) Image(
|
||||
context.Context, *types.TemporaryDocument, int, []byte, string, string, *Description,
|
||||
) (map[string]string, error) {
|
||||
p.images++
|
||||
return nil, errors.New("sandbox offline")
|
||||
}
|
||||
|
||||
func TestNativeVisionAndUnavailableSandboxDoNotRequireDescription(t *testing.T) {
|
||||
store, data := imageFixture(t)
|
||||
reader := NewReader(store, 0, func(context.Context, string) ([]byte, error) { return data, nil })
|
||||
projection := &failedProjection{}
|
||||
reader.Projection = projection
|
||||
document, err := reader.Resolve(context.Background(), "document", true)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, document.Document)
|
||||
require.Contains(t, document.Warning, "sandbox offline")
|
||||
view, err := readOne(context.Background(), reader, 1, "brief", "")
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, view.DataURI)
|
||||
require.Nil(t, view.Description)
|
||||
require.Equal(t, 1, projection.images)
|
||||
require.Contains(t, view.Warning, "sandbox offline")
|
||||
}
|
||||
|
||||
func TestConcurrentDescriptionRequestsShareOneCall(t *testing.T) {
|
||||
cache := &testCache{values: map[string]Description{}}
|
||||
var calls atomic.Int32
|
||||
reader := &ImageReader{Cache: cache, Describe: func(context.Context, []byte, string) (string, error) {
|
||||
calls.Add(1)
|
||||
return "chart", nil
|
||||
}}
|
||||
var wg sync.WaitGroup
|
||||
for range 8 {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
value, _, err := reader.describe(context.Background(), "document", []byte("image"), "brief", "axes")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "chart", value.Text)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
require.Equal(t, int32(1), calls.Load())
|
||||
}
|
||||
|
||||
func TestReadImagesAuthorizesOnceAndDescribesConcurrently(t *testing.T) {
|
||||
store, data := imageFixture(t)
|
||||
store.doc.MimeType = "application/pdf"
|
||||
store.doc.ImageRefs = types.JSON(`[{"url":"a"},{"url":"b"},{"url":"c"}]`)
|
||||
reader := NewReader(store, 0, func(_ context.Context, url string) ([]byte, error) {
|
||||
return append(append([]byte(nil), data...), url...), nil
|
||||
})
|
||||
var inside sync.WaitGroup
|
||||
inside.Add(3)
|
||||
reader.Images = &ImageReader{Describe: func(_ context.Context, _ []byte, _ string) (string, error) {
|
||||
inside.Done()
|
||||
// Every description has to be in flight at once to get past here.
|
||||
inside.Wait()
|
||||
return "chart", nil
|
||||
}}
|
||||
done := make(chan []interfaces.AttachmentImageRead)
|
||||
go func() {
|
||||
reads, err := reader.ReadImages(context.Background(), "document", []int{1, 2, 3, 9}, "brief", "")
|
||||
require.NoError(t, err)
|
||||
done <- reads
|
||||
}()
|
||||
select {
|
||||
case reads := <-done:
|
||||
require.Len(t, reads, 4)
|
||||
for i, read := range reads[:3] {
|
||||
require.Equal(t, i+1, read.Number)
|
||||
require.NoError(t, read.Err)
|
||||
require.Equal(t, "chart", *read.Image.Description)
|
||||
}
|
||||
require.Equal(t, 9, reads[3].Number)
|
||||
require.Error(t, reads[3].Err)
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("images were described one at a time")
|
||||
}
|
||||
require.Equal(t, 1, store.loads)
|
||||
}
|
||||
|
||||
func TestDescriptionDeadlineStartsAfterQueueing(t *testing.T) {
|
||||
reader := &ImageReader{}
|
||||
reader.slotsOnce.Do(func() { reader.slots = make(chan struct{}, 1) })
|
||||
reader.slots <- struct{}{}
|
||||
const queued = 200 * time.Millisecond
|
||||
time.AfterFunc(queued, func() { <-reader.slots })
|
||||
var remaining time.Duration
|
||||
reader.Describe = func(ctx context.Context, _ []byte, _ string) (string, error) {
|
||||
deadline, ok := ctx.Deadline()
|
||||
require.True(t, ok)
|
||||
remaining = time.Until(deadline)
|
||||
return "chart", nil
|
||||
}
|
||||
_, _, err := reader.describe(context.Background(), "document", []byte("image"), "brief", "")
|
||||
require.NoError(t, err)
|
||||
require.Greater(t, remaining, imageDescribeTimeout-queued/2)
|
||||
}
|
||||
|
||||
func TestCancelledCallerDoesNotFailSharedDescription(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
started, release := make(chan struct{}), make(chan struct{})
|
||||
reader := &ImageReader{Describe: func(ctx context.Context, _ []byte, _ string) (string, error) {
|
||||
calls.Add(1)
|
||||
close(started)
|
||||
<-release
|
||||
if err := ctx.Err(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "chart", nil
|
||||
}}
|
||||
firstCtx, cancel := context.WithCancel(context.Background())
|
||||
firstErr := make(chan error, 1)
|
||||
go func() {
|
||||
_, _, err := reader.describe(firstCtx, "document", []byte("image"), "brief", "")
|
||||
firstErr <- err
|
||||
}()
|
||||
<-started
|
||||
second := make(chan *Description, 1)
|
||||
go func() {
|
||||
value, _, err := reader.describe(context.Background(), "document", []byte("image"), "brief", "")
|
||||
require.NoError(t, err)
|
||||
second <- value
|
||||
}()
|
||||
time.Sleep(50 * time.Millisecond) // let the second caller join the in-flight call
|
||||
cancel()
|
||||
require.ErrorIs(t, <-firstErr, context.Canceled)
|
||||
close(release)
|
||||
require.Equal(t, "chart", (<-second).Text)
|
||||
require.Equal(t, int32(1), calls.Load())
|
||||
}
|
||||
|
||||
func TestChartPromptDoesNotReuseLegacyUnstructuredObservation(t *testing.T) {
|
||||
store, data := imageFixture(t)
|
||||
const oldPrompt = "Describe this image in at most 120 words. " +
|
||||
"Include its type, key labels, numbers and relationships. Do not transcribe long passages. " +
|
||||
"Say when content is illegible; do not guess. Plain text only."
|
||||
identity, err := json.Marshal([]string{"vision", oldPrompt, fmt.Sprintf("%x", sha256.Sum256(data))})
|
||||
require.NoError(t, err)
|
||||
key := fmt.Sprintf("%x", sha256.Sum256(identity))
|
||||
cache := &testCache{values: map[string]Description{
|
||||
store.doc.ID + key: {Text: "160 148 120 116 96", Model: "vision"},
|
||||
}}
|
||||
reader := NewReader(store, 0, func(context.Context, string) ([]byte, error) { return data, nil })
|
||||
calls := 0
|
||||
reader.Images = &ImageReader{
|
||||
Model: "vision", Cache: cache,
|
||||
Describe: func(_ context.Context, image []byte, prompt string) (string, error) {
|
||||
calls++
|
||||
require.NotEmpty(t, image)
|
||||
require.Contains(t, prompt, "one labelled row per category")
|
||||
return "East: Q1=102, Q2=148 (万元)", nil
|
||||
},
|
||||
}
|
||||
first, err := readOne(t.Context(), reader, 1, "brief", "")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "East: Q1=102, Q2=148 (万元)", *first.Description)
|
||||
_, err = readOne(t.Context(), reader, 1, "brief", "")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, calls, "reuse the new observation, not the legacy OCR list")
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
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