refactor(context): replace middleware.EmbedChannelContextKey with types.EmbedChannelContextKey

- Updated test files to use types.EmbedChannelContextKey instead of middleware.EmbedChannelContextKey for consistency.
- Introduced context cloning decisions for EmbedChannelContextKey to ensure proper context management during background tasks.
- Added tests to verify the correct behavior of context key declarations and their cloning decisions.
main
wizardchen 2026-08-13 17:52:06 +08:00 committed by lyingbug
parent 10cc694fed
commit 98239de0d2
10 changed files with 336 additions and 61 deletions

View File

@ -8,7 +8,6 @@ import (
"testing"
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/middleware"
"github.com/Tencent/WeKnora/internal/types"
"github.com/gin-gonic/gin"
)
@ -79,7 +78,7 @@ func TestExchangeEmbedSessionSuccess(t *testing.T) {
r := gin.New()
r.POST("/exchange", func(c *gin.Context) {
ch := &types.EmbedChannel{ID: "channel-1", Enabled: true}
ctx := context.WithValue(c.Request.Context(), middleware.EmbedChannelContextKey, ch)
ctx := context.WithValue(c.Request.Context(), types.EmbedChannelContextKey, ch)
c.Request = c.Request.WithContext(ctx)
h.ExchangeEmbedSession(c)
})
@ -114,7 +113,7 @@ func TestExchangeEmbedSessionUnavailable(t *testing.T) {
r := gin.New()
r.POST("/exchange", func(c *gin.Context) {
ch := &types.EmbedChannel{ID: "channel-1", Enabled: true}
ctx := context.WithValue(c.Request.Context(), middleware.EmbedChannelContextKey, ch)
ctx := context.WithValue(c.Request.Context(), types.EmbedChannelContextKey, ch)
c.Request = c.Request.WithContext(ctx)
h.ExchangeEmbedSession(c)
})
@ -136,7 +135,7 @@ func TestExchangeEmbedSessionRejectsSessionToken(t *testing.T) {
r := gin.New()
r.POST("/exchange", func(c *gin.Context) {
ch := &types.EmbedChannel{ID: "channel-1", Enabled: true}
ctx := context.WithValue(c.Request.Context(), middleware.EmbedChannelContextKey, ch)
ctx := context.WithValue(c.Request.Context(), types.EmbedChannelContextKey, ch)
c.Request = c.Request.WithContext(ctx)
h.ExchangeEmbedSession(c)
})

View File

@ -11,7 +11,6 @@ import (
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/middleware"
"github.com/Tencent/WeKnora/internal/types"
)
@ -27,7 +26,7 @@ func newEmbedLoadMessagesCtx(
http.MethodGet, "/messages/"+testEmbedSessionID+"/load"+query, nil)
c.Request.Header.Set("X-Embed-Session", service.SignEmbedSessionHandle(ch, testEmbedSessionID))
c.Params = gin.Params{{Key: "session_id", Value: testEmbedSessionID}}
ctx := context.WithValue(c.Request.Context(), middleware.EmbedChannelContextKey, ch)
ctx := context.WithValue(c.Request.Context(), types.EmbedChannelContextKey, ch)
c.Request = c.Request.WithContext(ctx)
return c, w
}

View File

@ -11,7 +11,6 @@ import (
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/handler/session"
"github.com/Tencent/WeKnora/internal/middleware"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/gin-gonic/gin"
@ -145,7 +144,7 @@ func newEnsureEmbedSessionCtx(ch *types.EmbedChannel, sessionID, sig string) (*g
c.Request.Header.Set("X-Embed-Session", sig)
}
c.Params = gin.Params{{Key: "session_id", Value: sessionID}}
ctx := context.WithValue(c.Request.Context(), middleware.EmbedChannelContextKey, ch)
ctx := context.WithValue(c.Request.Context(), types.EmbedChannelContextKey, ch)
c.Request = c.Request.WithContext(ctx)
return c, w
}
@ -255,7 +254,7 @@ func TestCreateEmbedSessionSuccess(t *testing.T) {
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodPost, "/sessions", nil)
c.Set(types.TenantIDContextKey.String(), ch.TenantID)
ctx := context.WithValue(c.Request.Context(), middleware.EmbedChannelContextKey, ch)
ctx := context.WithValue(c.Request.Context(), types.EmbedChannelContextKey, ch)
c.Request = c.Request.WithContext(ctx)
h.CreateEmbedSession(c)
@ -299,7 +298,7 @@ func TestGetEmbedChunkForbidden(t *testing.T) {
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/chunks/chunk-1", nil)
c.Params = gin.Params{{Key: "chunk_id", Value: "chunk-1"}}
ctx := context.WithValue(c.Request.Context(), middleware.EmbedChannelContextKey, ch)
ctx := context.WithValue(c.Request.Context(), types.EmbedChannelContextKey, ch)
c.Request = c.Request.WithContext(ctx)
h.GetEmbedChunk(c)
@ -324,7 +323,7 @@ func TestGetEmbedChunkSuccess(t *testing.T) {
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/chunks/chunk-ok", nil)
c.Params = gin.Params{{Key: "chunk_id", Value: "chunk-ok"}}
ctx := context.WithValue(c.Request.Context(), middleware.EmbedChannelContextKey, ch)
ctx := context.WithValue(c.Request.Context(), types.EmbedChannelContextKey, ch)
c.Request = c.Request.WithContext(ctx)
h.GetEmbedChunk(c)
@ -345,7 +344,7 @@ func newEmbedStopSessionCtx(ch *types.EmbedChannel, sessionID, sig, body string)
}
c.Params = gin.Params{{Key: "session_id", Value: sessionID}}
c.Set(types.TenantIDContextKey.String(), ch.TenantID)
ctx := context.WithValue(c.Request.Context(), middleware.EmbedChannelContextKey, ch)
ctx := context.WithValue(c.Request.Context(), types.EmbedChannelContextKey, ch)
c.Request = c.Request.WithContext(ctx)
return c, w
}

View File

@ -503,51 +503,15 @@ func Fatalf(c context.Context, format string, args ...interface{}) {
}
// CloneContext 复制上下文中的关键信息到新上下文
//
// Which keys survive is decided by types.contextCloneAcrossDetach, which lives
// next to where context keys are declared so that adding a key and deciding
// its fate are the same edit. Keeping that decision here instead meant every
// new key silently defaulted to being dropped.
func CloneContext(ctx context.Context) context.Context {
newCtx := context.Background()
for _, k := range []types.ContextKey{
types.LoggerContextKey,
types.TenantIDContextKey,
types.RequestIDContextKey,
types.TenantInfoContextKey,
types.UserIDContextKey,
types.UserContextKey,
types.PrincipalContextKey,
types.TenantAPIKeyScopeContextKey,
// TenantRoleContextKey: the caller's resolved role in the
// active tenant (PR 2 #1303). Must be propagated for the same
// reason as TenantIDContextKey — any handler that does
// `ctx := logger.CloneContext(c.Request.Context())` and then
// reads role via TenantRoleFromContext would otherwise see the
// type-zero TenantRole and fall back
// to Viewer, blocking even Owners.
types.TenantRoleContextKey,
types.SystemAdminContextKey,
types.LanguageContextKey,
types.SessionTenantIDContextKey,
types.SessionIDContextKey,
// SandboxTenantIDContextKey: the session owner's tenant, which the
// shared-agent path deliberately keeps separate from
// TenantIDContextKey. Dropping it here would silently re-key every
// session→sandbox binding onto the borrowed tenant, because
// setupSSEStream builds its async context through CloneContext.
types.SandboxTenantIDContextKey,
types.EmbedQueryContextKey,
types.EmbedVisitorContextKey,
// MemoryDisabledContextKey: the agent-level opt-out from long-term
// memory. setupSSEStream builds its async context through
// CloneContext, and the memory WRITE path (extraction, explicit
// remember, document affinity) hangs off that context. Dropping the
// key here would let an agent that cannot read memory keep writing
// to it.
types.MemoryDisabledContextKey,
// Keep the Langfuse trace alive across CloneContext boundaries so
// LLM/Embedder/Reranker/VLM/ASR wrappers attach their generations
// to the same trace opened by GinMiddleware, instead of each call
// auto-creating its own orphan trace.
types.LangfuseTraceContextKey,
} {
for _, k := range types.ContextKeysClonedAcrossDetach() {
if v := ctx.Value(k); v != nil {
newCtx = context.WithValue(newCtx, k, v)
}

View File

@ -249,3 +249,33 @@ func TestCloneContextPreservesTheAgentMemoryOptOut(t *testing.T) {
t.Fatal("MemoryAllowedForAgent(cloned) = false for an unmarked context, want true")
}
}
// Document ingestion detaches mid-flight: knowledge_create hands processChunks
// to a goroutine on a cloned context, and processChunks vectorises every chunk.
// If the background mark does not survive, that work stops being visible to the
// per-model concurrency governor and the ingestion storm it exists to contain
// runs past it, starving interactive chat.
func TestCloneContextKeepsBackgroundWorkThrottled(t *testing.T) {
t.Parallel()
if !types.IsBackgroundTask(CloneContext(types.WithBackgroundTask(context.Background()))) {
t.Fatal("IsBackgroundTask(cloned) = false, want background work to stay throttled across a detach")
}
if types.IsBackgroundTask(CloneContext(context.Background())) {
t.Fatal("IsBackgroundTask(cloned) = true for an unmarked context, want interactive work left ungated")
}
}
// An IM bot has no live client to click "Authorize", so losing this mark makes
// the agent block on the OAuth wait for every unauthorized service instead of
// replying with its one-shot notice.
func TestCloneContextKeepsTheNonInteractiveOAuthMark(t *testing.T) {
t.Parallel()
if !types.IsMCPOAuthNonInteractive(CloneContext(types.WithMCPOAuthNonInteractive(context.Background()))) {
t.Fatal("IsMCPOAuthNonInteractive(cloned) = false, want the mark to survive a detach")
}
if types.IsMCPOAuthNonInteractive(CloneContext(context.Background())) {
t.Fatal("IsMCPOAuthNonInteractive(cloned) = true for an unmarked context, want interactive prompts to stay possible")
}
}

View File

@ -30,7 +30,7 @@ func TestApplyAuthSessionSetsBothSurfaces(t *testing.T) {
Role: types.TenantRoleAdmin,
SystemAdmin: true,
APIKeyScope: scope,
Extra: map[types.ContextKey]any{EmbedChannelContextKey: &types.EmbedChannel{ID: "ch"}},
Extra: map[types.ContextKey]any{types.EmbedChannelContextKey: &types.EmbedChannel{ID: "ch"}},
})
ctx := c.Request.Context()
@ -67,7 +67,7 @@ func TestApplyAuthSessionSetsBothSurfaces(t *testing.T) {
if ch, ok := EmbedChannelFromContext(ctx); !ok || ch.ID != "ch" {
t.Fatalf("ctx embed channel = %#v, ok=%v", ch, ok)
}
if got, ok := c.Get(EmbedChannelContextKey.String()); !ok || got.(*types.EmbedChannel).ID != "ch" {
if got, ok := c.Get(types.EmbedChannelContextKey.String()); !ok || got.(*types.EmbedChannel).ID != "ch" {
t.Fatalf("keys embed channel = %v, ok=%v", got, ok)
}
}

View File

@ -32,9 +32,6 @@ const (
embedGlobalMinuteFloor = 120
)
// EmbedChannelContextKey stores the authenticated embed channel on the request context.
const EmbedChannelContextKey types.ContextKey = "EmbedChannel"
var (
embedLimiterOnce sync.Once
embedLimiter *ratelimit.Limiter
@ -171,7 +168,7 @@ func EmbedAuth(
TenantID: ch.TenantID,
Tenant: tenant,
Role: types.TenantRoleViewer,
Extra: map[types.ContextKey]any{EmbedChannelContextKey: ch},
Extra: map[types.ContextKey]any{types.EmbedChannelContextKey: ch},
})
c.Next()
}
@ -235,6 +232,6 @@ func originAllowed(origin string, allowed []string) bool {
// EmbedChannelFromContext returns the authenticated embed channel, if any.
func EmbedChannelFromContext(ctx context.Context) (*types.EmbedChannel, bool) {
ch, ok := ctx.Value(EmbedChannelContextKey).(*types.EmbedChannel)
ch, ok := ctx.Value(types.EmbedChannelContextKey).(*types.EmbedChannel)
return ch, ok && ch != nil
}

View File

@ -54,6 +54,13 @@ const (
LanguageContextKey ContextKey = "Language"
// EmbedVisitorContextKey is the anonymous visitor id for embed OAuth isolation.
EmbedVisitorContextKey ContextKey = "EmbedVisitorID"
// EmbedChannelContextKey stores the authenticated embed channel (an
// *EmbedChannel) on the request context. Declared here rather than in the
// middleware that authenticates it, for the same reason as
// LangfuseTraceContextKey: the clone table in context_clone.go has to name
// every context key, and middleware imports this package, so a key
// declared there could only be referred to by its raw string value.
EmbedChannelContextKey ContextKey = "EmbedChannel"
// LangfuseTraceContextKey carries the active Langfuse *Trace across the
// request lifecycle. Defined here (not inside the langfuse package) so
// that logger.CloneContext can preserve it without importing langfuse.

View File

@ -0,0 +1,135 @@
package types
import "sort"
// contextCloneAcrossDetach answers one question for every context key in the
// codebase: when a request's context is detached for background work by
// logger.CloneContext, does this key travel with it?
//
// It is an exhaustive decision table rather than a list of keys to keep,
// because the two ways of getting this wrong fail in opposite directions and
// neither default is safe. Dropping a key that carries a RESTRICTION fails
// open: an agent's memory opt-out or a session's sandbox tenant that goes
// missing lets background work do what the request forbade. Keeping a key that
// carries a GRANT fails open the other way: a per-request access decision or a
// suppressed-audit marker that outlives its request widens what the background
// work may do. Since no default is universally right, every key states its
// own answer here, next to where such keys are declared, and
// TestEveryContextKeyDeclaresACloneDecision fails when a new key arrives
// without one instead of letting it opt out by silence.
//
// false is a valid, meaningful answer — it means "deliberately does not
// survive a detach" — and is not the same as being absent.
var contextCloneAcrossDetach = map[ContextKey]bool{
// Caller identity and workspace scope. Background work runs as the same
// principal in the same workspace, so all of this has to survive; a
// detached goroutine that loses its tenant reads another tenant's rows or
// none at all.
TenantIDContextKey: true,
TenantInfoContextKey: true,
UserContextKey: true,
UserIDContextKey: true,
PrincipalContextKey: true,
SystemAdminContextKey: true,
// TenantRoleContextKey: the caller's resolved role in the active tenant
// (PR 2 #1303). Must survive for the same reason as TenantIDContextKey —
// any handler that does `ctx := logger.CloneContext(c.Request.Context())`
// and then reads the role via TenantRoleFromContext would otherwise see
// the type-zero TenantRole and fall back to Viewer, blocking even Owners.
TenantRoleContextKey: true,
// Per-API-key operation and KB scopes: a restriction, so dropping it would
// hand background work broader reach than the key it came from.
TenantAPIKeyScopeContextKey: true,
// Session scope. SessionTenantID re-scopes session/message lookups, while
// SandboxTenantID keys the session→sandbox binding to the session owner
// even when a shared agent borrowed another tenant. Dropping the latter
// would silently re-key every binding onto the borrowed tenant, because
// setupSSEStream builds its async context through CloneContext, and
// abandon a paused MicroVM that keeps billing.
SessionIDContextKey: true,
SessionTenantIDContextKey: true,
SandboxTenantIDContextKey: true,
// Embed callers: the anonymous visitor id isolates embed OAuth, so losing
// it would merge visitors together.
EmbedQueryContextKey: true,
EmbedVisitorContextKey: true,
// Diagnostics and presentation that background work is expected to keep.
// The Langfuse trace in particular must stay alive so the LLM / embedder /
// reranker / VLM / ASR wrappers attach their generations to the trace
// GinMiddleware opened, rather than each auto-creating an orphan.
LoggerContextKey: true,
RequestIDContextKey: true,
LanguageContextKey: true,
LangfuseTraceContextKey: true,
// The agent-level opt-out from long-term memory. Recall is gated inside
// the QA services, but extraction, the explicit "remember this" route and
// document affinity all run from a context descended from a CloneContext.
// Dropping this key would let an agent that cannot read memory keep
// writing to it.
MemoryDisabledContextKey: true,
// Marks model calls as coming from an asynq worker so the per-model chat
// concurrency governor throttles them, leaving interactive chat latency
// alone. Document ingestion detaches mid-flight — knowledge_create hands
// processChunks to a goroutine on a cloned context, and processChunks is
// what vectorises every chunk. Dropping the mark there would let exactly
// the ingestion storm the governor exists to contain run past it. Keeping
// it can only over-throttle a context that is background by definition.
BackgroundTaskContextKey: true,
// Marks a channel that cannot resolve an in-conversation MCP OAuth prompt
// (an IM bot has no live client to click "Authorize"). Dropping it makes
// the agent block on the OAuth wait for every unauthorized service instead
// of emitting its one-shot notice, so the failure is a stalled reply.
// A detached context has no live client either, which is what this says.
MCPOAuthNonInteractiveContextKey: true,
// ---- Deliberately does not survive a detach ----
//
// false here is a decision, not an oversight: each of these describes one
// request, one call or one attachment rather than the caller, so carrying
// it into detached work would describe that work wrongly.
// Labels for a single model request, set immediately before the call by
// every call site that has an opinion. An inherited label is worse than no
// label, because usage is aggregated by purpose and a background call
// would be filed under whatever its parent was doing.
LLMCallPurposeContextKey: false,
LLMPromptPrefixFingerprintContextKey: false,
// Who is authoring one wiki page write. Absent deliberately means the wiki
// ingest pipeline, which is what detached work should look like; an
// inherited "user" would attribute a background rewrite to a person.
WikiEditSourceContextKey: false,
// The parser engine resolved from one agent's ChatParserEngineRules for
// one attachment's file type. Read by the attachment processor on the same
// context that set it, and meaningless for anything else.
ChatParserEngineContextKey: false,
// The authenticated embed channel. Every reader takes it straight off the
// request context inside the embed handler that authenticated it; nothing
// downstream of a detach reads it.
EmbedChannelContextKey: false,
}
// ContextKeysClonedAcrossDetach returns the keys logger.CloneContext carries
// into a detached context, sorted so the result does not depend on map order.
func ContextKeysClonedAcrossDetach() []ContextKey {
keys := make([]ContextKey, 0, len(contextCloneAcrossDetach))
for key, clone := range contextCloneAcrossDetach {
if clone {
keys = append(keys, key)
}
}
sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] })
return keys
}
// ContextCloneDecision reports whether the key survives a detach, and whether
// any decision has been recorded for it at all. The second return value is
// what the coverage test uses to tell a deliberate false from an omission.
func ContextCloneDecision(key ContextKey) (clone bool, declared bool) {
clone, declared = contextCloneAcrossDetach[key]
return clone, declared
}

View File

@ -0,0 +1,145 @@
package types
import (
"go/ast"
"go/parser"
"go/token"
"io/fs"
"path/filepath"
"strconv"
"strings"
"testing"
)
// declaredContextKeys walks the source of internal/ and returns every declared
// context key by its underlying string value, mapped to where it was found.
//
// The keys are collected from the source rather than from a hand-written list
// because a hand-written list has the very failure mode this test exists to
// close: whoever forgets to register a new key in the clone table is exactly
// the person who would forget to add it to the list guarding the table.
func declaredContextKeys(t *testing.T) map[ContextKey]string {
t.Helper()
found := make(map[ContextKey]string)
fset := token.NewFileSet()
err := filepath.WalkDir("..", func(path string, entry fs.DirEntry, err error) error {
if err != nil {
return err
}
if entry.IsDir() {
return nil
}
// Test files are skipped: a key invented by a test never reaches a
// detached production context, so forcing a decision for it would be
// noise.
if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
return nil
}
file, parseErr := parser.ParseFile(fset, path, nil, parser.SkipObjectResolution)
if parseErr != nil {
return parseErr
}
for _, decl := range file.Decls {
generic, ok := decl.(*ast.GenDecl)
if !ok || generic.Tok != token.CONST {
continue
}
for _, spec := range generic.Specs {
value, ok := spec.(*ast.ValueSpec)
if !ok || !isContextKeyType(value.Type) {
continue
}
for _, expr := range value.Values {
literal, ok := expr.(*ast.BasicLit)
if !ok || literal.Kind != token.STRING {
continue
}
unquoted, unquoteErr := strconv.Unquote(literal.Value)
if unquoteErr != nil {
return unquoteErr
}
found[ContextKey(unquoted)] = path
}
}
}
return nil
})
if err != nil {
t.Fatalf("walking internal/ for context key declarations: %v", err)
}
if len(found) == 0 {
t.Fatal("found no context key declarations, so this test is not guarding anything")
}
return found
}
// isContextKeyType reports whether a const is typed as this package's
// ContextKey, written either bare (inside types) or qualified (outside it).
func isContextKeyType(expr ast.Expr) bool {
switch typed := expr.(type) {
case *ast.Ident:
return typed.Name == "ContextKey"
case *ast.SelectorExpr:
return typed.Sel.Name == "ContextKey"
}
return false
}
// A context key that reaches logger.CloneContext without a recorded decision
// opts out of surviving the detach by accident, and nothing reports it: the
// background work simply runs without the value. That is how an agent's
// long-term memory opt-out came to stop recall while leaving the write path
// running, and how the session→sandbox binding was once re-keyed onto a
// borrowed tenant. Either answer is fine here; silence is not.
func TestEveryContextKeyDeclaresACloneDecision(t *testing.T) {
t.Parallel()
for key, path := range declaredContextKeys(t) {
if _, declared := ContextCloneDecision(key); !declared {
t.Errorf(
"context key %q (declared in %s) has no entry in contextCloneAcrossDetach; "+
"add one saying whether it should survive logger.CloneContext",
key, path,
)
}
}
}
// The reverse direction: an entry left behind by a deleted key turns the table
// into folklore, and the next reader cannot tell which entries still describe
// something real.
func TestTheCloneTableHasNoEntriesForKeysThatNoLongerExist(t *testing.T) {
t.Parallel()
declared := declaredContextKeys(t)
for key := range contextCloneAcrossDetach {
if _, ok := declared[key]; !ok {
t.Errorf(
"contextCloneAcrossDetach has an entry for %q, but no context key with that value is declared in internal/",
key,
)
}
}
}
// The table is what CloneContext iterates, so a key marked as surviving has to
// come back out of the accessor, and one marked as dropped must not.
func TestClonedKeysAreExactlyTheOnesMarkedToSurvive(t *testing.T) {
t.Parallel()
surviving := make(map[ContextKey]bool)
for _, key := range ContextKeysClonedAcrossDetach() {
if surviving[key] {
t.Errorf("key %q is returned twice", key)
}
surviving[key] = true
}
for key, clone := range contextCloneAcrossDetach {
if clone != surviving[key] {
t.Errorf("key %q: table says clone=%v, accessor says %v", key, clone, surviving[key])
}
}
}