2025-08-05 07:08:07 +00:00
// Package container implements dependency injection container setup
// Provides centralized configuration for services, repositories, and handlers
// This package is responsible for wiring up all dependencies and ensuring proper lifecycle management
package container
import (
"context"
2025-12-23 08:56:30 +00:00
"database/sql"
2026-04-27 08:56:30 +00:00
"errors"
2025-08-05 07:08:07 +00:00
"fmt"
2026-06-01 12:53:26 +00:00
"io"
2025-11-08 19:27:24 +00:00
"net/url"
2025-08-05 07:08:07 +00:00
"os"
2026-02-28 05:22:07 +00:00
"path/filepath"
2025-08-05 07:08:07 +00:00
"slices"
2025-08-16 05:13:52 +00:00
"strconv"
2025-08-05 07:08:07 +00:00
"strings"
"time"
2026-02-28 05:22:07 +00:00
sqlite_vec "github.com/asg017/sqlite-vec-go-bindings/cgo"
2026-01-05 06:52:11 +00:00
_ "github.com/duckdb/duckdb-go/v2"
2025-08-05 07:08:07 +00:00
esv7 "github.com/elastic/go-elasticsearch/v7"
"github.com/elastic/go-elasticsearch/v8"
feat(retriever): 接入 Apache Doris 4.1 作为向量数据库
为 RetrieveEngine 体系新增 Doris 后端,与现有 Qdrant/Milvus/Weaviate
等保持完整能力对齐:向量检索、关键词检索、健康检查、环境变量与多实例
DB 配置、前端类型注册、单元测试、Docker Compose 模板。
实现要点:
- 协议分工:主链路用 MySQL 协议(database/sql + go-sql-driver/mysql)
做 DDL / 查询 / 删除;批量更新走 Stream Load HTTP API,并启用
partial_update=true、merge_type=APPEND,自动按 1MiB 切分批次并处理
307 重定向。
- 表结构:UNIQUE KEY(id) + enable_unique_key_merge_on_write=true 以
支持 upsert/部分列更新;按维度分表(<base>_<dim>),每张表上建
HNSW ANN 索引(metric_type=cosine_distance)和 INVERTED 索引
(parser=chinese)。
- 分数语义:使用 cosine_distance_approximate,再以 1 - dist 转换为
"越大越相似",与现有 KVHybridRetrieveEngine 约定一致。
- 异步索引:ANN 索引为后台构建,ensureTable 通过轮询 SHOW INDEX 等
待索引就绪后再放行写入,避免首次检索召回为空。
- ARRAY<FLOAT> 序列化:go-sql-driver/mysql 不支持数组占位符,
embeddingLiteral 将 []float32 转成 SQL 字面量字符串再拼接。
新增文件:
- internal/application/repository/retriever/doris/{structs,schema,
query,repository,streamload,repository_test}.go
- scripts/e2e-doris.sh:E2E 验证清单
- docs/wiki/集成扩展/Doris改动与上游同步.md:fork-and-rebase 工作流
与改动清单
修改文件(接线 + 文档):
- internal/types/{retriever,tenant,vectorstore}.go:新增
DorisRetrieverEngineType、env 解析、表单 schema 与索引参数校验
- internal/container/{container,engine_factory}.go:环境变量驱动
与 VectorStore 配置驱动两条路径都支持 Doris
- internal/application/service/vectorstore{,_healthcheck}.go:连接
校验 + Ping/Version 健康检查
- docker-compose.yml:新增 doris-fe / doris-be 服务(profile=doris)
- .env.example:DORIS_* 环境变量与示例
- docs/{使用其他向量数据库,wiki/集成扩展/集成向量数据库}.md:
使用说明与索引/分数行为说明
依赖:go.mod/go.sum 新增 github.com/go-sql-driver/mysql(运行时)和
github.com/DATA-DOG/go-sqlmock(测试)。
测试:repository 层 SQL 形状、Stream Load HTTP 行为、whereBuilder
逻辑、embeddingLiteral 往返、健康检查错误路径均有单测覆盖。
2026-05-07 09:58:37 +00:00
_ "github.com/go-sql-driver/mysql" // 给 Doris (database/sql) 注册 MySQL 协议驱动
2026-02-26 13:48:38 +00:00
"github.com/milvus-io/milvus/client/v2/milvusclient"
2026-04-11 14:06:39 +00:00
"github.com/neo4j/neo4j-go-driver/v6/neo4j"
2025-08-05 07:08:07 +00:00
"github.com/panjf2000/ants/v2"
2025-11-26 10:58:53 +00:00
"github.com/qdrant/go-client/qdrant"
2025-11-06 13:12:26 +00:00
"github.com/redis/go-redis/v9"
2025-08-05 07:08:07 +00:00
"go.uber.org/dig"
2026-02-26 13:48:38 +00:00
"google.golang.org/grpc"
2025-08-05 07:08:07 +00:00
"gorm.io/driver/postgres"
2026-02-28 05:22:07 +00:00
"gorm.io/driver/sqlite"
2025-08-05 07:08:07 +00:00
"gorm.io/gorm"
feat(agent): human-in-the-loop approval for MCP tool calls (#1173)
Add an opt-in human approval gate so Agent runs pause before executing
MCP tools that operators flag as dangerous, surface an approval card in
the chat UI, and only resume after the user approves (optionally with
edited args) or rejects.
Backend
- New mcp_tool_approvals table + repo/service to mark per-tool approval
required (PG migration 000042 + sqlite init).
- approval.Gate coordinates RequestAndWait / Resolve with sync.Once
delivery, configurable timeout, and Redis Pub/Sub fan-out so multi-
replica deployments work without sticky sessions.
- MCPTool.Execute integrates the gate; uses a round-level ApprovalCtx
(without the per-tool 60s timeout) for the wait, and re-derives a
fresh 60s exec ctx after approval so CallTool keeps a full window.
- New SSE response types (tool_approval_required / _resolved) and
EventBus events plumb approval state to AgentStreamDisplay.
- REST: list/set per-tool approval flag, resolve pending approval.
- Configurable via agent.tool_approval_timeout_seconds (yaml) or
WEKNORA_AGENT_TOOL_APPROVAL_TIMEOUT env (accepts seconds or Go
duration).
Frontend
- MCP settings: per-tool "require approval" switch on the test panel.
- Chat: ToolApprovalCard renders the pause point with editable JSON
args, validation feedback, mm:ss countdown that turns warning/danger
near deadline, and a resolved state that retains context.
- i18n strings added for zh-CN / en-US / ko-KR / ru-RU.
Docs
- docs/zh/mcp-approval.md covering behavior, config, API, deployment
considerations (Redis cross-instance, restart limitations).
2026-05-10 13:23:49 +00:00
"github.com/Tencent/WeKnora/internal/agent/approval"
2025-08-05 07:08:07 +00:00
"github.com/Tencent/WeKnora/internal/application/repository"
2026-02-12 08:02:09 +00:00
memoryRepo "github.com/Tencent/WeKnora/internal/application/repository/memory/neo4j"
feat(retriever): 接入 Apache Doris 4.1 作为向量数据库
为 RetrieveEngine 体系新增 Doris 后端,与现有 Qdrant/Milvus/Weaviate
等保持完整能力对齐:向量检索、关键词检索、健康检查、环境变量与多实例
DB 配置、前端类型注册、单元测试、Docker Compose 模板。
实现要点:
- 协议分工:主链路用 MySQL 协议(database/sql + go-sql-driver/mysql)
做 DDL / 查询 / 删除;批量更新走 Stream Load HTTP API,并启用
partial_update=true、merge_type=APPEND,自动按 1MiB 切分批次并处理
307 重定向。
- 表结构:UNIQUE KEY(id) + enable_unique_key_merge_on_write=true 以
支持 upsert/部分列更新;按维度分表(<base>_<dim>),每张表上建
HNSW ANN 索引(metric_type=cosine_distance)和 INVERTED 索引
(parser=chinese)。
- 分数语义:使用 cosine_distance_approximate,再以 1 - dist 转换为
"越大越相似",与现有 KVHybridRetrieveEngine 约定一致。
- 异步索引:ANN 索引为后台构建,ensureTable 通过轮询 SHOW INDEX 等
待索引就绪后再放行写入,避免首次检索召回为空。
- ARRAY<FLOAT> 序列化:go-sql-driver/mysql 不支持数组占位符,
embeddingLiteral 将 []float32 转成 SQL 字面量字符串再拼接。
新增文件:
- internal/application/repository/retriever/doris/{structs,schema,
query,repository,streamload,repository_test}.go
- scripts/e2e-doris.sh:E2E 验证清单
- docs/wiki/集成扩展/Doris改动与上游同步.md:fork-and-rebase 工作流
与改动清单
修改文件(接线 + 文档):
- internal/types/{retriever,tenant,vectorstore}.go:新增
DorisRetrieverEngineType、env 解析、表单 schema 与索引参数校验
- internal/container/{container,engine_factory}.go:环境变量驱动
与 VectorStore 配置驱动两条路径都支持 Doris
- internal/application/service/vectorstore{,_healthcheck}.go:连接
校验 + Ping/Version 健康检查
- docker-compose.yml:新增 doris-fe / doris-be 服务(profile=doris)
- .env.example:DORIS_* 环境变量与示例
- docs/{使用其他向量数据库,wiki/集成扩展/集成向量数据库}.md:
使用说明与索引/分数行为说明
依赖:go.mod/go.sum 新增 github.com/go-sql-driver/mysql(运行时)和
github.com/DATA-DOG/go-sqlmock(测试)。
测试:repository 层 SQL 形状、Stream Load HTTP 行为、whereBuilder
逻辑、embeddingLiteral 往返、健康检查错误路径均有单测覆盖。
2026-05-07 09:58:37 +00:00
dorisRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/doris"
2025-08-05 07:08:07 +00:00
elasticsearchRepoV7 "github.com/Tencent/WeKnora/internal/application/repository/retriever/elasticsearch/v7"
elasticsearchRepoV8 "github.com/Tencent/WeKnora/internal/application/repository/retriever/elasticsearch/v8"
2026-02-26 13:48:38 +00:00
milvusRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/milvus"
2025-09-24 04:15:17 +00:00
neo4jRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/neo4j"
feat(retriever): activate OpenSearch k-NN driver (PR 3 of 3)
Phase 3 (#1440) gate flip. PR 1 (#1445) + PR 2a (#1481) + PR 2b (#1482)
laid the type prep + driver skeleton + read/write paths as gated dead
code; this PR wires every activation surface so opensearch becomes a
registerable VectorStore engine.
Activation wiring
- internal/types: validEngineTypes / GetVectorStoreTypes (with HNSW
bounds + knn_engine enum + Immutable hints) / retrieverEngineMapping /
buildEnvStoreForDriver — every gated surface now recognises
"opensearch". IndexConfig grows four omitempty HNSW fields (HNSWM /
HNSWEFConstruction / HNSWEFSearch / KNNEngine), keeping other engines'
serialised config byte-identical.
- internal/container: createOpenSearchEngine + the switch case in
createEngineServiceFromStore; the RETRIEVE_DRIVER=opensearch env path
in initRetrieveEngineRegistry; NewEngineFactory now closes over the
AuditLogService (the EngineFactory type itself is unchanged).
- internal/application/service/vectorstore_healthcheck.go: a
testOpenSearchConnection case so CreateStore's connectivity probe
accepts opensearch instead of returning 400.
- internal/application/repository/retriever/opensearch/transport.go:
NewOpenSearchClient is exported so the factory and env path can build
the TLS-hardened client; healthcheck.go reuses the unexported
probeVersion / probeKNNPlugin for the service-layer probe.
Service-layer validation
- validateOpenSearchIndexConfig validates the HNSW caps (m 2-100,
ef_construction 2-4096, ef_search 1-10000, knn_engine ∈ lucene|faiss).
Shards/replicas continue to be enforced by the flat ValidateIndexConfig.
Create-only: UpdateStore mutates the name only.
- validateConnectionConfig requires addr for opensearch.
Sync implementations (stubs.go shrinks)
- CopyIndices (copy.go) mirrors the Elasticsearch / Qdrant pattern —
search → BatchSave with the source_id remap for generated questions —
so dim/keyword routing and the source_id contract come from BatchSave
for free. embeddingMap is keyed by the *target* SourceID because
OpenSearch's BatchSave looks up embeddings by SourceID
(lookupEmbedding), not by chunk_id (the ES driver's convention).
Pagination is from/size; copies larger than max_result_window
(default 10000) need the scroll-based async path that lands later.
- BatchUpdateChunkEnabledStatus / BatchUpdateChunkTagID (bulk_update.go)
group the input by target value and issue one _update_by_query per
group over the cross-dim <base>_* pattern. Caller values flow through
bound script params only — never string-interpolated into the Painless
source — closing the script-injection surface.
- inspectByQueryResponse (byquery.go) mirrors inspectBulkResponse: the
full failure reason goes to the debug log only; the returned error
carries the bounded id + type.
- UpdateByQueryParams.Refresh is *bool in opensearch-go v4.6.0 (the same
shape as DeleteByQuery's quirk), so refresh=wait_for is not
expressible; we use refresh=true.
Driver-owned audit (DIP)
- A new opensearch.AuditSink interface (with nopSink + WithAuditSink
functional option) lets the driver emit opensearch.index_created and
opensearch.reindex_executed events without importing any service
package — the service layer implements the interface. NewRepository
takes opts, so existing 4-arg test call sites keep compiling unchanged.
- internal/container/audit_sink.go bridges AuditSink to AuditLogService.
When the context carries no tenant (the env-path registration ctx
during boot, for example) the adapter skips the emit with a warning
rather than silently writing tenant_id=0, which would collide with the
system-scope sentinel.
Frontend + polish
- FieldSchema (frontend/src/api/vector-store.ts) gains min/max/enum/
immutable. VectorStoreSettings.vue is now schema-driven: a closed
`enum` renders a t-select; number inputs use the schema's `:min`/`:max`
and fall back to the legacy replica-vs-shard heuristic only when the
schema does not pin them; a danger-coloured warning fires when
insecure_skip_verify is toggled on (the switch and warning are wrapped
in a vertical stack so the warning sits on its own row below the switch).
- i18n: labels for hnsw_m / hnsw_ef_construction / hnsw_ef_search /
knn_engine / insecure_skip_verify plus the warning copy in en-US,
ko-KR, zh-CN, ru-RU.
- docker-compose.dev.yml: an opensearch profile (single-node 3.3.2 with
security plugin disabled for dev only). OpenSearch Dashboards lives in a
separate, opt-in opensearch-ui profile so the heavy UI container is not
forced up alongside the cluster (the driver e2e is fully curl-verifiable
against :9200). The new docs/dev/opensearch-integration-test.md covers the
end-to-end exercise and the single-node guidance (set replicas=0 to keep
the cluster Green).
Gating-guard tests flipped
- The "OpenSearch is NOT in validEngineTypes / mapping / types list /
env builder / stubs" guard tests from PR 1 / PR 2 are replaced by
their positive counterparts in this PR. The test suite was the
activation checklist; the activation flip is its diff.
Backward compatibility
- Additive everywhere. IndexConfig's new HNSW fields are omitempty so
other engines' serialised config is byte-identical. Existing
Elasticsearch / Qdrant / Milvus / Weaviate / Doris / TencentVectorDB
stores are untouched. No migrations.
Test plan
- go build ./... clean
- go vet ./... clean
- gofmt -l clean on touched files
- go test ./... — only TestOssEnsureBucket_CreateFails (Aliyun OSS
endpoint), the docreader gRPC tests, and the doris SQL-shape tests
fail; all three are pre-existing on upstream/main and untouched by
this PR.
- New tests across internal/types, opensearch, service and container —
including a full end-to-end env-path test that exercises
initRetrieveEngineRegistry with RETRIEVE_DRIVER=opensearch against an
httptest cluster.
2026-05-28 09:01:17 +00:00
openSearchRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/opensearch"
2025-08-05 07:08:07 +00:00
postgresRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/postgres"
2025-11-26 10:58:53 +00:00
qdrantRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/qdrant"
2026-02-28 05:22:07 +00:00
sqliteRetrieverRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/sqlite"
2026-05-08 08:09:55 +00:00
tencentVectorDBRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/tencentvectordb"
2026-03-07 07:17:27 +00:00
weaviateRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/weaviate"
2025-08-05 07:08:07 +00:00
"github.com/Tencent/WeKnora/internal/application/service"
2026-03-22 17:57:06 +00:00
chatpipeline "github.com/Tencent/WeKnora/internal/application/service/chat_pipeline"
2025-08-05 07:08:07 +00:00
"github.com/Tencent/WeKnora/internal/application/service/file"
2026-02-12 08:02:09 +00:00
memoryService "github.com/Tencent/WeKnora/internal/application/service/memory"
2025-08-05 07:08:07 +00:00
"github.com/Tencent/WeKnora/internal/application/service/retriever"
"github.com/Tencent/WeKnora/internal/config"
2025-11-08 19:27:24 +00:00
"github.com/Tencent/WeKnora/internal/database"
2026-03-27 07:02:40 +00:00
"github.com/Tencent/WeKnora/internal/datasource"
feishuConnector "github.com/Tencent/WeKnora/internal/datasource/connector/feishu"
2026-04-06 15:31:46 +00:00
notionConnector "github.com/Tencent/WeKnora/internal/datasource/connector/notion"
2026-04-21 09:29:37 +00:00
yuqueConnector "github.com/Tencent/WeKnora/internal/datasource/connector/yuque"
2025-11-05 15:18:44 +00:00
"github.com/Tencent/WeKnora/internal/event"
2025-08-05 07:08:07 +00:00
"github.com/Tencent/WeKnora/internal/handler"
2025-11-08 16:02:31 +00:00
"github.com/Tencent/WeKnora/internal/handler/session"
2026-03-15 10:45:53 +00:00
imPkg "github.com/Tencent/WeKnora/internal/im"
2026-03-24 08:48:34 +00:00
"github.com/Tencent/WeKnora/internal/im/dingtalk"
2026-03-15 10:45:53 +00:00
"github.com/Tencent/WeKnora/internal/im/feishu"
2026-03-27 03:07:09 +00:00
"github.com/Tencent/WeKnora/internal/im/mattermost"
2026-03-18 09:25:06 +00:00
"github.com/Tencent/WeKnora/internal/im/slack"
2026-03-24 08:48:13 +00:00
"github.com/Tencent/WeKnora/internal/im/telegram"
2026-03-23 10:27:21 +00:00
"github.com/Tencent/WeKnora/internal/im/wechat"
2026-03-15 10:45:53 +00:00
"github.com/Tencent/WeKnora/internal/im/wecom"
2026-02-28 05:22:07 +00:00
"github.com/Tencent/WeKnora/internal/infrastructure/docparser"
2026-04-08 11:52:28 +00:00
infra_web_search "github.com/Tencent/WeKnora/internal/infrastructure/web_search"
2025-08-05 07:08:07 +00:00
"github.com/Tencent/WeKnora/internal/logger"
2025-11-08 19:27:24 +00:00
"github.com/Tencent/WeKnora/internal/mcp"
2026-06-01 12:53:26 +00:00
"github.com/Tencent/WeKnora/internal/models/chat"
2025-08-05 07:08:07 +00:00
"github.com/Tencent/WeKnora/internal/models/embedding"
"github.com/Tencent/WeKnora/internal/models/utils/ollama"
"github.com/Tencent/WeKnora/internal/router"
"github.com/Tencent/WeKnora/internal/stream"
feat(observability): integrate Langfuse for LLM token tracking and tracing
Closes #620 #497. Add opt-in Langfuse observability covering all five
model types (chat, embedding, rerank, VLM, ASR) with HTTP-request-scoped
traces and Docker Compose support (both cloud and self-hosted).
Core package internal/tracing/langfuse:
- HTTP client with batched async ingestion (non-blocking in request path)
- Sampling, environment / release tagging, and graceful fallback when
LANGFUSE_* env vars are absent (wrappers become no-ops)
- Gin middleware opens one trace per traced request and finishes it after
the handler chain returns, attaching method / path / user / session
- Trace context is stored under a typed key exported from internal/types
so logger.CloneContext can preserve it across handler / goroutine
boundaries (otherwise each LLM call auto-created an orphan trace,
fragmenting one request into many)
Per-model generation wrappers (opt-in via NewChat/NewEmbedder/...):
- chat: captures prompt, streaming output, token usage + TTFT
- embedding: approximates tokens when the provider omits usage
- rerank: previews query/docs, summarizes results to keep payload small
- vlm: records image count and total bytes, never uploads raw pixels
- asr: records file size and audio duration, never uploads audio bytes
Async title generation (GenerateTitleAsync) now forwards the trace key
into the goroutine so title calls appear under the parent chat trace.
Docker Compose:
- LANGFUSE_* env passthrough on the `app` service for cloud deployments
- Optional `langfuse` profile spins up a self-hosted Langfuse stack that
reuses WeKnora's existing PostgreSQL (separate database via an idempotent
init container that fixes ICU collation drift) and Redis (separate DB
number), adding only ClickHouse, MinIO, web and worker containers
- web/worker entrypoints URL-encode DB_PASSWORD / REDIS_PASSWORD at start
to avoid Prisma P1013 when passwords contain @ / # / etc.
Docs: docs/Langfuse集成.md covers cloud vs self-hosted, per-model usage
strategy, code map, and resource footprint.
2026-04-23 17:57:12 +00:00
"github.com/Tencent/WeKnora/internal/tracing/langfuse"
2025-08-05 07:08:07 +00:00
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
2026-06-01 12:53:26 +00:00
secutils "github.com/Tencent/WeKnora/internal/utils"
2026-05-08 08:09:55 +00:00
"github.com/tencent/vectordatabase-sdk-go/tcvectordb"
2026-03-07 07:17:27 +00:00
"github.com/weaviate/weaviate-go-client/v5/weaviate"
"github.com/weaviate/weaviate-go-client/v5/weaviate/auth"
wgrpc "github.com/weaviate/weaviate-go-client/v5/weaviate/grpc"
2025-08-05 07:08:07 +00:00
)
// BuildContainer constructs the dependency injection container
// Registers all components, services, repositories and handlers needed by the application
// Creates a fully configured application container with proper dependency resolution
// Parameters:
// - container: Base dig container to add dependencies to
//
// Returns:
// - Configured container with all application dependencies registered
func BuildContainer ( container * dig . Container ) * dig . Container {
2026-01-05 02:15:55 +00:00
ctx := context . Background ( )
logger . Debugf ( ctx , "[Container] Starting container initialization..." )
2025-08-05 07:08:07 +00:00
// Register resource cleaner for proper cleanup of resources
must ( container . Provide ( NewResourceCleaner , dig . As ( new ( interfaces . ResourceCleaner ) ) ) )
// Core infrastructure configuration
2026-01-05 02:15:55 +00:00
logger . Debugf ( ctx , "[Container] Registering core infrastructure..." )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( config . LoadConfig ) )
feat(observability): integrate Langfuse for LLM token tracking and tracing
Closes #620 #497. Add opt-in Langfuse observability covering all five
model types (chat, embedding, rerank, VLM, ASR) with HTTP-request-scoped
traces and Docker Compose support (both cloud and self-hosted).
Core package internal/tracing/langfuse:
- HTTP client with batched async ingestion (non-blocking in request path)
- Sampling, environment / release tagging, and graceful fallback when
LANGFUSE_* env vars are absent (wrappers become no-ops)
- Gin middleware opens one trace per traced request and finishes it after
the handler chain returns, attaching method / path / user / session
- Trace context is stored under a typed key exported from internal/types
so logger.CloneContext can preserve it across handler / goroutine
boundaries (otherwise each LLM call auto-created an orphan trace,
fragmenting one request into many)
Per-model generation wrappers (opt-in via NewChat/NewEmbedder/...):
- chat: captures prompt, streaming output, token usage + TTFT
- embedding: approximates tokens when the provider omits usage
- rerank: previews query/docs, summarizes results to keep payload small
- vlm: records image count and total bytes, never uploads raw pixels
- asr: records file size and audio duration, never uploads audio bytes
Async title generation (GenerateTitleAsync) now forwards the trace key
into the goroutine so title calls appear under the parent chat trace.
Docker Compose:
- LANGFUSE_* env passthrough on the `app` service for cloud deployments
- Optional `langfuse` profile spins up a self-hosted Langfuse stack that
reuses WeKnora's existing PostgreSQL (separate database via an idempotent
init container that fixes ICU collation drift) and Redis (separate DB
number), adding only ClickHouse, MinIO, web and worker containers
- web/worker entrypoints URL-encode DB_PASSWORD / REDIS_PASSWORD at start
to avoid Prisma P1013 when passwords contain @ / # / etc.
Docs: docs/Langfuse集成.md covers cloud vs self-hosted, per-model usage
strategy, code map, and resource footprint.
2026-04-23 17:57:12 +00:00
must ( container . Provide ( initLangfuse ) )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( initDatabase ) )
must ( container . Provide ( initFileService ) )
2025-11-06 13:12:26 +00:00
must ( container . Provide ( initRedisClient ) )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( initAntsPool ) )
feat(observability): integrate Langfuse for LLM token tracking and tracing
Closes #620 #497. Add opt-in Langfuse observability covering all five
model types (chat, embedding, rerank, VLM, ASR) with HTTP-request-scoped
traces and Docker Compose support (both cloud and self-hosted).
Core package internal/tracing/langfuse:
- HTTP client with batched async ingestion (non-blocking in request path)
- Sampling, environment / release tagging, and graceful fallback when
LANGFUSE_* env vars are absent (wrappers become no-ops)
- Gin middleware opens one trace per traced request and finishes it after
the handler chain returns, attaching method / path / user / session
- Trace context is stored under a typed key exported from internal/types
so logger.CloneContext can preserve it across handler / goroutine
boundaries (otherwise each LLM call auto-created an orphan trace,
fragmenting one request into many)
Per-model generation wrappers (opt-in via NewChat/NewEmbedder/...):
- chat: captures prompt, streaming output, token usage + TTFT
- embedding: approximates tokens when the provider omits usage
- rerank: previews query/docs, summarizes results to keep payload small
- vlm: records image count and total bytes, never uploads raw pixels
- asr: records file size and audio duration, never uploads audio bytes
Async title generation (GenerateTitleAsync) now forwards the trace key
into the goroutine so title calls appear under the parent chat trace.
Docker Compose:
- LANGFUSE_* env passthrough on the `app` service for cloud deployments
- Optional `langfuse` profile spins up a self-hosted Langfuse stack that
reuses WeKnora's existing PostgreSQL (separate database via an idempotent
init container that fixes ICU collation drift) and Redis (separate DB
number), adding only ClickHouse, MinIO, web and worker containers
- web/worker entrypoints URL-encode DB_PASSWORD / REDIS_PASSWORD at start
to avoid Prisma P1013 when passwords contain @ / # / etc.
Docs: docs/Langfuse集成.md covers cloud vs self-hosted, per-model usage
strategy, code map, and resource footprint.
2026-04-23 17:57:12 +00:00
must ( container . Invoke ( registerLangfuseCleanup ) )
2026-03-04 09:43:34 +00:00
2025-08-05 07:08:07 +00:00
// Register goroutine pool cleanup handler
must ( container . Invoke ( registerPoolCleanup ) )
// Initialize retrieval engine registry for search capabilities
2026-01-05 02:15:55 +00:00
logger . Debugf ( ctx , "[Container] Registering retrieval engine registry..." )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( initRetrieveEngineRegistry ) )
// External service clients
2026-01-05 02:15:55 +00:00
logger . Debugf ( ctx , "[Container] Registering external service clients..." )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( initDocReaderClient ) )
2026-03-03 13:30:27 +00:00
must ( container . Provide ( docparser . NewImageResolver ) )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( initOllamaService ) )
2025-09-24 04:15:17 +00:00
must ( container . Provide ( initNeo4jClient ) )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( stream . NewStreamManager ) )
2026-01-05 02:15:55 +00:00
logger . Debugf ( ctx , "[Container] Initializing DuckDB..." )
2025-12-23 08:56:30 +00:00
must ( container . Provide ( NewDuckDB ) )
2026-01-05 02:15:55 +00:00
logger . Debugf ( ctx , "[Container] DuckDB registered" )
2025-08-05 07:08:07 +00:00
// Data repositories layer
2026-01-05 02:15:55 +00:00
logger . Debugf ( ctx , "[Container] Registering repositories..." )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( repository . NewTenantRepository ) )
2026-05-13 11:47:48 +00:00
must ( container . Provide ( repository . NewTenantMemberRepository ) )
2026-05-17 13:19:59 +00:00
must ( container . Provide ( repository . NewTenantInvitationRepository ) )
feat(rbac): per-tenant audit log for RBAC events (PR 6, #1303)
PR 1-5 of the multi-tenant RBAC series enforce the role matrix; what
they don't do is keep a durable record of who did what. Today the
RBAC middleware logs "[rbac] role insufficient ..." to stderr -
perishable, not searchable. Operators cannot answer "who removed
Alice from tenant T-foo on Tuesday" or "did we 403 a probing user
200 times last hour" after the fact.
This PR adds a generic per-tenant audit log that:
- Captures mutating RBAC actions (member add/remove/role-change/leave)
durably from the tenant_member service after the repo write succeeds.
- Captures enforcement rejections (RequireRole / RequireOwnershipOrRole
denies under EnableRBAC=true) via a gin-context-injected hook.
- Sliding-window dedup (1 minute) on (tenant, actor, action, path)
for denied events so a probing client cannot flood audit_logs.
- Default-on - no extra env flag. Schema is generic enough for future
KB / agent / datasource events to reuse via new action namespaces
without another migration.
Schema (migration 000044) mirrors wiki_log_entries' shape: a single
audit_logs table with action, target_type/id, request path/method,
outcome, and a JSONB details column. Three indexes: (tenant_id, id
DESC) for the per-tenant cursor feed, actor_user_id for "what did
Alice do", (tenant_id, action) for both the action filter and the
dedup lookup. Sqlite mirror added for Lite mode.
Wiring is nil-safe: the audit field on tenantMemberService and the
gin-context lookup in rbac.go both tolerate a nil service so existing
tests construct without a stub and dormant deployments degrade
gracefully if the provider is misconfigured.
The query API is GET /tenants/:id/audit-log, gated by Admin+ on top
of the existing PathTenantMatch (denial histories should not surface
to ordinary members). Cursor-paginated by descending id (sidesteps
the duplicate-timestamp tie-breaking that BIGSERIAL trivially solves).
Frontend: TenantMembers.vue gets a t-tabs wrapper with Members
(existing) and Audit log (new) tabs; the audit tab is gated to
Admin+ to mirror the server, lazy-loads on first open, paginates via
the next_cursor pattern, and renders coloured chips per
action/outcome so an operator can scan for anomalies. i18n keys
added in all four locales.
Tests: 14 new tests across service (6), middleware (4), and handler
(4). Service tests pin the dedup window behaviour (writes again
after expiry, dedup is per-actor-per-path, degrades on lookup
error). Middleware tests pin both reject sites' audit hook and the
"dormant mode does not fire" + "nil audit does not panic"
invariants. Handler tests pin the cursor envelope and that an empty
page returns next_cursor=0.
Out of scope: per-action ACL on the audit log, retention/TTL job,
KB/agent/datasource event wiring (schema supports it - just no
emitters yet), async writes, frontend filter UI.
2026-05-14 13:07:48 +00:00
must ( container . Provide ( repository . NewAuditLogRepository ) )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( repository . NewKnowledgeBaseRepository ) )
must ( container . Provide ( repository . NewKnowledgeRepository ) )
refactor(knowledge): replace flat stage table with langfuse-style span tree
Addresses review feedback that the PR② design had four shortcomings:
1. The pipeline is a DAG, not a sequence — Embedding and Multimodal
are independent of each other, both downstream of Chunking, both
upstream of PostProcess. The flat (knowledge_id, stage) table
couldn't represent that, so a Chunking failure left dependents
stranded as "pending" forever instead of being marked as
impossible-to-run.
2. No history across attempts. A reparse erased the previous run's
status before the new run started, leaving operators with no way
to investigate "why did this fail twice?".
3. Stages had only status + duration. Operators want to know how big
the work was — pages parsed, chunks created, tokens embedded, VLM
calls made — to distinguish "slow because the file is huge" from
"slow because the docreader is wedged".
4. Multimodal fans out N image tasks; Embedding fans out M batches;
PostProcess fans out into Summary/Question/Wiki/Graph. Each unit
is interesting on its own (Langfuse already captures this for
LLM calls). The flat model couldn't express it.
The redesign mirrors Langfuse's trace/span/generation hierarchy:
* Migration 000053 supersedes 000052: knowledge_processing_spans
table with (knowledge_id, attempt, span_id) primary key, plus
parent_span_id, kind ∈ {root, stage, subspan, generation},
status ∈ {pending,running,done,failed,skipped,cancelled}, and
JSONB input/output/metadata fields.
* SpanTracker (replacing StageTracker) exposes OpenAttempt /
BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan /
LookupStage. Cross-process workers (image_multimodal) get the
parent's attempt + span via payload + LookupStage so subspans
attach correctly.
* StageDependencies declares the DAG; FailSpan now cascades —
descendants of the failed span and dependent stages are flipped
to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear
blast radius instead of orphan spinners.
* Reparse now calls OpenAttempt up front so the timeline reflects
"new attempt, all pending" instead of letting the previous run's
status linger until the worker picks up the task.
* Image_multimodal records each image as a generation subspan with
its own success/failure on the parent attempt's multimodal stage.
The finalize-on-last-attempt counter logic is preserved unchanged.
* GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns
a tree shape with synthesized pending placeholders so the
frontend always renders five timeline segments. ?attempt=N
enables history navigation.
2026-05-27 06:05:47 +00:00
must ( container . Provide ( repository . NewKnowledgeSpanRepository ) )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( repository . NewChunkRepository ) )
2025-11-17 10:15:02 +00:00
must ( container . Provide ( repository . NewKnowledgeTagRepository ) )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( repository . NewSessionRepository ) )
must ( container . Provide ( repository . NewMessageRepository ) )
must ( container . Provide ( repository . NewModelRepository ) )
2025-09-15 18:47:39 +00:00
must ( container . Provide ( repository . NewUserRepository ) )
must ( container . Provide ( repository . NewAuthTokenRepository ) )
2026-05-24 13:38:05 +00:00
must ( container . Provide ( repository . NewSystemSettingRepository ) )
2025-09-24 04:15:17 +00:00
must ( container . Provide ( neo4jRepo . NewNeo4jRepository ) )
2026-02-12 08:02:09 +00:00
must ( container . Provide ( memoryRepo . NewMemoryRepository ) )
2025-11-08 19:27:24 +00:00
must ( container . Provide ( repository . NewMCPServiceRepository ) )
feat(agent): human-in-the-loop approval for MCP tool calls (#1173)
Add an opt-in human approval gate so Agent runs pause before executing
MCP tools that operators flag as dangerous, surface an approval card in
the chat UI, and only resume after the user approves (optionally with
edited args) or rejects.
Backend
- New mcp_tool_approvals table + repo/service to mark per-tool approval
required (PG migration 000042 + sqlite init).
- approval.Gate coordinates RequestAndWait / Resolve with sync.Once
delivery, configurable timeout, and Redis Pub/Sub fan-out so multi-
replica deployments work without sticky sessions.
- MCPTool.Execute integrates the gate; uses a round-level ApprovalCtx
(without the per-tool 60s timeout) for the wait, and re-derives a
fresh 60s exec ctx after approval so CallTool keeps a full window.
- New SSE response types (tool_approval_required / _resolved) and
EventBus events plumb approval state to AgentStreamDisplay.
- REST: list/set per-tool approval flag, resolve pending approval.
- Configurable via agent.tool_approval_timeout_seconds (yaml) or
WEKNORA_AGENT_TOOL_APPROVAL_TIMEOUT env (accepts seconds or Go
duration).
Frontend
- MCP settings: per-tool "require approval" switch on the test panel.
- Chat: ToolApprovalCard renders the pause point with editable JSON
args, validation feedback, mm:ss countdown that turns warning/danger
near deadline, and a resolved state that retains context.
- i18n strings added for zh-CN / en-US / ko-KR / ru-RU.
Docs
- docs/zh/mcp-approval.md covering behavior, config, API, deployment
considerations (Redis cross-instance, restart limitations).
2026-05-10 13:23:49 +00:00
must ( container . Provide ( repository . NewMCPToolApprovalRepository ) )
2025-12-24 02:34:41 +00:00
must ( container . Provide ( repository . NewCustomAgentRepository ) )
2026-01-30 08:28:01 +00:00
must ( container . Provide ( repository . NewOrganizationRepository ) )
must ( container . Provide ( repository . NewKBShareRepository ) )
2026-02-04 12:12:29 +00:00
must ( container . Provide ( repository . NewAgentShareRepository ) )
2026-06-12 14:40:18 +00:00
must ( container . Provide ( repository . NewEmbedChannelRepository ) )
2026-02-05 08:29:56 +00:00
must ( container . Provide ( repository . NewTenantDisabledSharedAgentRepository ) )
2026-05-16 15:04:03 +00:00
must ( container . Provide ( repository . NewUserResourceFavoriteRepository ) )
2025-12-23 08:56:30 +00:00
must ( container . Provide ( service . NewWebSearchStateService ) )
2026-03-27 07:02:40 +00:00
must ( container . Provide ( repository . NewDataSourceRepository ) )
must ( container . Provide ( repository . NewSyncLogRepository ) )
feat: Implement comprehensive wiki feature for knowledge bases
This commit introduces the complete wiki feature for WeKnora, enabling AI-powered wiki page generation and management. The implementation includes:
**Backend Changes:**
- Wiki data model: WikiPage type with support for multiple page types (Summary, Entity, Concept, Index, Log)
- Database schema: wiki_pages table with full migration support
- WikiPageService: CRUD operations and page management
- WikiPageRepository: GORM-based persistence layer
- Wiki ingest pipeline: Automated generation of wiki pages from knowledge documents
* Summary page generation using LLM
* Entity and concept extraction in a single LLM call
* Synthesis opportunity detection
* Index page rebuilding
* Log page maintenance
- Wiki boost feature: Enhance chat retrieval with wiki context
- Wiki linting: Maintenance and validation utilities
- Agent wiki tools: Enable agents to query and interact with wiki pages
- Wiki prompts: Comprehensive LLM prompt templates for all wiki generation tasks
- Language support: Reuse existing middleware language infrastructure for LLM prompts
**Frontend Changes:**
- Wiki browser UI: View all wiki pages with filtering and search
- Wiki API client: Knowledge base wiki management endpoints
- Knowledge base editor: Configure wiki settings (language, auto-ingest, synthesis model)
- i18n updates: Support for English, Korean, Russian, and Chinese interfaces
**Configuration:**
- Container DI: Wire up all wiki services
- Router: Register wiki API endpoints
- Task handling: Support async wiki ingest tasks
**Testing:**
- Unit tests for wiki page types
- Service layer tests
- Endpoint tests for wiki operations
- Integration tests with LLM mocking
**Documentation:**
- Language refactoring analysis and guides
- Implementation completion reports
- Quick reference guides for developers
**Key Features:**
✅ LLM-powered wiki page generation from documents
✅ Multi-language support (9+ languages)
✅ Automatic extraction of entities and concepts
✅ Synthesis opportunity detection
✅ Index and log page maintenance
✅ Progressive wiki building across multiple documents
✅ Agent-based wiki interaction
✅ Chat retrieval enhancement with wiki context
✅ Full frontend UI for wiki browsing
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 05:56:13 +00:00
must ( container . Provide ( repository . NewWikiPageRepository ) )
2026-05-08 13:43:53 +00:00
must ( container . Provide ( repository . NewWikiLogEntryRepository ) )
perf(wiki-ingest): scale to 4w-doc KBs + generic task queue / dead-letter
The wiki ingest post-process pipeline OOM'd and ran for hours on KBs
with ~40k documents. The dominant tail was a per-batch ListAllPages
that pulled every page (multi-MB content blobs) into Go memory, plus a
24h-TTL Redis pending list whose data could be evicted before a long
serialized backlog drained. dedup did O(P × N) Jaccard scoring in Go
on every batch. Lint loaded the full graph. The index page kept the
entire wiki directory in its content column and rewrote the TOAST
chunk on every ingest. None of these survive at 4w docs.
This change reworks the write path end to end and pulls the durable-
queue + dead-letter primitives out of wiki and into shared
infrastructure that every asynq task type now benefits from.
- migration 000041: task_pending_ops + task_dead_letters tables, plus
three GIN indexes on wiki_pages (source_refs jsonb_path_ops,
source_refs text fallback, lower(title) trgm).
- TaskPendingOpsRepository + TaskDeadLetterRepository in
internal/application/repository/task_queue.go: cursor-paginated
list, atomic IncrFailCount via UPDATE…RETURNING, dedup-key scoped
delete that refuses empty keys so a buggy caller can't wipe a KB's
queue.
- internal/middleware/asynqdl: writes a task_dead_letters row when an
asynq task exhausts its retry budget. Payload-agnostic — a small
probe struct extracts TenantID + scope hints across every existing
payload type, so summary:generation / image:multimodal /
faq_import / kb:clone / etc. all dead-letter without per-handler
code. Best-effort: an insert failure never masks the underlying
task error. Installed in router/task.go before the langfuse mw so
it sees raw errors.
- Pending queue moved Redis → PG (no TTL, restart-durable). Redis
keeps just the active-batch lock and the delete tombstone.
- In-batch retry budget (wikiMaxFailRetries=5) tracked via
pendingRepo.IncrFailCount; over the cap the row is moved to
task_dead_letters with task_type=wiki:ingest, related_id=knowledge
id. Asynq retries (10) are handled by the new middleware.
- Removed the per-batch ListAllPages. WikiBatchContext now carries
lazy fetcher closures (SlugTitleMany, SummaryByKnowledgeID) with
mutex-protected caches; reduce reaches for titles / summaries on
demand instead of pre-loading the whole KB.
- getExistingPageSlugsForKnowledge now uses ListSlugsBySourceRef,
which the new GIN index on source_refs serves as a Bitmap Index
Scan instead of a sequential text LIKE.
- Dedup pre-filter uses pg_trgm via FindSimilarPages
(idx_wiki_pages_title_trgm). For each new entity/concept (and each
of its aliases) we ask the DB for the top-K trigram-similar
existing pages and union the results — bounded prompt size, no Go-
side O(P × M) loop. Small KBs (≤25 entities) bypass the pre-filter.
- cleanDeadLinks / injectCrossLinks are scoped to the batch's
affected slugs (a few dozen) instead of every page in the KB. Both
use the new lite ListBySlugs / ExistsSlugs repo methods so they
pull only slug + title + outlinks, not full content.
- Slug fuzzy resolve (slug_fuzzy.go): when the LLM emits
[[bad-slug|display]] the cleanup path now tries display-text
reverse lookup → hyphen/case normalized equality → char-bigram
Jaccard ≥ 0.8 before stripping. Recovers the common pinyin-word-
break drift case ("shang-hai-tower" vs "shanghai-tower") in place
instead of replacing the link with plain text.
- rebuildIndexPage uses ListByTypeRecent(200) for the first-time
intro and drops the full DocumentSummaries blob from the
incremental update prompt, so its context stays bounded regardless
of KB size.
- Concurrency tunables surfaced in WikiConfig: IngestBatchSize /
IngestMapParallel / IngestReduceParallel, with sensible defaults
via OrDefault helpers. scheduleFollowUp drops to ProcessIn(0) so
follow-ups don't waste asynq retry slots bouncing on the active
lock.
- RunLint walks pages via the new ListPagesCursor in 200-page
windows and computes the live-slug set with a one-column
ListAllSlugs Pluck instead of a Limit:0 GetGraph that materialized
every node + edge. Memory is now bounded; 40k pages walks in
constant ~4MB.
- 14 GORM tests for both repos against an in-memory SQLite mirror of
the production DDL (task_queue_test.go).
- 6 tests for the dead-letter middleware covering retry budget
detection, payload-agnostic scope inference, error truncation, and
repo-failure isolation.
- 7 tests for the slug fuzzy resolve helper covering the three
resolution stages, display-text priority over normalized equality,
bigram fallback acceptance, and rejection of unrelated slugs.
- Existing wiki_ingest / wiki_lint / wiki_page tests updated to the
new fetcher / cursor APIs.
2026-05-09 15:42:53 +00:00
must ( container . Provide ( repository . NewTaskPendingOpsRepository ) )
must ( container . Provide ( repository . NewTaskDeadLetterRepository ) )
2025-11-08 19:27:24 +00:00
// MCP manager for managing MCP client connections
2026-01-05 02:15:55 +00:00
logger . Debugf ( ctx , "[Container] Registering MCP manager..." )
2025-11-08 19:27:24 +00:00
must ( container . Provide ( mcp . NewMCPManager ) )
2025-08-05 07:08:07 +00:00
// Business service layer
2026-01-05 02:15:55 +00:00
logger . Debugf ( ctx , "[Container] Registering business services..." )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( service . NewTenantService ) )
2026-05-13 11:47:48 +00:00
must ( container . Provide ( service . NewTenantMemberService ) )
2026-05-17 13:19:59 +00:00
must ( container . Provide ( service . NewTenantInvitationService ) )
feat(rbac): per-tenant audit log for RBAC events (PR 6, #1303)
PR 1-5 of the multi-tenant RBAC series enforce the role matrix; what
they don't do is keep a durable record of who did what. Today the
RBAC middleware logs "[rbac] role insufficient ..." to stderr -
perishable, not searchable. Operators cannot answer "who removed
Alice from tenant T-foo on Tuesday" or "did we 403 a probing user
200 times last hour" after the fact.
This PR adds a generic per-tenant audit log that:
- Captures mutating RBAC actions (member add/remove/role-change/leave)
durably from the tenant_member service after the repo write succeeds.
- Captures enforcement rejections (RequireRole / RequireOwnershipOrRole
denies under EnableRBAC=true) via a gin-context-injected hook.
- Sliding-window dedup (1 minute) on (tenant, actor, action, path)
for denied events so a probing client cannot flood audit_logs.
- Default-on - no extra env flag. Schema is generic enough for future
KB / agent / datasource events to reuse via new action namespaces
without another migration.
Schema (migration 000044) mirrors wiki_log_entries' shape: a single
audit_logs table with action, target_type/id, request path/method,
outcome, and a JSONB details column. Three indexes: (tenant_id, id
DESC) for the per-tenant cursor feed, actor_user_id for "what did
Alice do", (tenant_id, action) for both the action filter and the
dedup lookup. Sqlite mirror added for Lite mode.
Wiring is nil-safe: the audit field on tenantMemberService and the
gin-context lookup in rbac.go both tolerate a nil service so existing
tests construct without a stub and dormant deployments degrade
gracefully if the provider is misconfigured.
The query API is GET /tenants/:id/audit-log, gated by Admin+ on top
of the existing PathTenantMatch (denial histories should not surface
to ordinary members). Cursor-paginated by descending id (sidesteps
the duplicate-timestamp tie-breaking that BIGSERIAL trivially solves).
Frontend: TenantMembers.vue gets a t-tabs wrapper with Members
(existing) and Audit log (new) tabs; the audit tab is gated to
Admin+ to mirror the server, lazy-loads on first open, paginates via
the next_cursor pattern, and renders coloured chips per
action/outcome so an operator can scan for anomalies. i18n keys
added in all four locales.
Tests: 14 new tests across service (6), middleware (4), and handler
(4). Service tests pin the dedup window behaviour (writes again
after expiry, dedup is per-actor-per-path, degrades on lookup
error). Middleware tests pin both reject sites' audit hook and the
"dormant mode does not fire" + "nil audit does not panic"
invariants. Handler tests pin the cursor envelope and that an empty
page returns next_cursor=0.
Out of scope: per-action ACL on the audit log, retention/TTL job,
KB/agent/datasource event wiring (schema supports it - just no
emitters yet), async writes, frontend filter UI.
2026-05-14 13:07:48 +00:00
must ( container . Provide ( service . NewAuditLogService ) )
feat(rbac): daily retention sweep for audit_logs (default 90 days)
The audit_logs table grows monotonically until something purges it.
PR 6 explicitly listed retention as out of scope for v1; this picks
that up.
Adds an `audit.retention_days` config (default 90, 0 disables) and a
small background goroutine `AuditLogRetentionRunner` that fires once
~10 minutes after boot and then every 24h, calling
`AuditLogService.Purge` which DELETEs rows older than the cutoff in a
single statement. The dependency surface is intentionally minimal —
no robfig/cron, no asynq, no migration — because retention has no
wall-clock alignment requirement.
Wiring is the same shape as the existing data source scheduler:
container `Provide(NewAuditLogRetentionRunner)`, an `Invoke` that
calls `Start`, and a `ResourceCleaner.RegisterWithName` for graceful
shutdown.
Defaults preserve operator intent:
- `audit:` section omitted from YAML -> retention_days=90.
- explicit `audit.retention_days: 0` in YAML -> purge disabled.
- `WEKNORA_AUDIT_RETENTION_DAYS=N` env override (incl. N=0).
- `retention_days < 0` is rejected by ValidateConfig.
Tests cover the service Purge contract (no-op when disabled, cutoff
math, error propagation) and the runner lifecycle (Start no-op when
disabled, idempotent Start/Stop, ticker cadence, runOnce swallows
errors). 10 new tests, all green.
docs/rbac.md updated with the new YAML / env / behaviour.
Refs: #1303
2026-05-15 12:10:47 +00:00
must ( container . Provide ( service . NewAuditLogRetentionRunner ) )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( service . NewKnowledgeBaseService ) )
2026-01-30 08:28:01 +00:00
must ( container . Provide ( service . NewOrganizationService ) )
must ( container . Provide ( service . NewKBShareService ) ) // KBShareService must be registered before KnowledgeService and KnowledgeTagService
2026-02-04 12:12:29 +00:00
must ( container . Provide ( service . NewAgentShareService ) )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( service . NewKnowledgeService ) )
refactor(knowledge): replace flat stage table with langfuse-style span tree
Addresses review feedback that the PR② design had four shortcomings:
1. The pipeline is a DAG, not a sequence — Embedding and Multimodal
are independent of each other, both downstream of Chunking, both
upstream of PostProcess. The flat (knowledge_id, stage) table
couldn't represent that, so a Chunking failure left dependents
stranded as "pending" forever instead of being marked as
impossible-to-run.
2. No history across attempts. A reparse erased the previous run's
status before the new run started, leaving operators with no way
to investigate "why did this fail twice?".
3. Stages had only status + duration. Operators want to know how big
the work was — pages parsed, chunks created, tokens embedded, VLM
calls made — to distinguish "slow because the file is huge" from
"slow because the docreader is wedged".
4. Multimodal fans out N image tasks; Embedding fans out M batches;
PostProcess fans out into Summary/Question/Wiki/Graph. Each unit
is interesting on its own (Langfuse already captures this for
LLM calls). The flat model couldn't express it.
The redesign mirrors Langfuse's trace/span/generation hierarchy:
* Migration 000053 supersedes 000052: knowledge_processing_spans
table with (knowledge_id, attempt, span_id) primary key, plus
parent_span_id, kind ∈ {root, stage, subspan, generation},
status ∈ {pending,running,done,failed,skipped,cancelled}, and
JSONB input/output/metadata fields.
* SpanTracker (replacing StageTracker) exposes OpenAttempt /
BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan /
LookupStage. Cross-process workers (image_multimodal) get the
parent's attempt + span via payload + LookupStage so subspans
attach correctly.
* StageDependencies declares the DAG; FailSpan now cascades —
descendants of the failed span and dependent stages are flipped
to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear
blast radius instead of orphan spinners.
* Reparse now calls OpenAttempt up front so the timeline reflects
"new attempt, all pending" instead of letting the previous run's
status linger until the worker picks up the task.
* Image_multimodal records each image as a generation subspan with
its own success/failure on the parent attempt's multimodal stage.
The finalize-on-last-attempt counter logic is preserved unchanged.
* GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns
a tree shape with synthesized pending placeholders so the
frontend always renders five timeline segments. ?attempt=N
enables history navigation.
2026-05-27 06:05:47 +00:00
must ( container . Provide ( service . NewSpanTracker ) )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( service . NewChunkService ) )
2025-11-17 10:15:02 +00:00
must ( container . Provide ( service . NewKnowledgeTagService ) )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( embedding . NewBatchEmbedder ) )
must ( container . Provide ( service . NewModelService ) )
must ( container . Provide ( service . NewDatasetService ) )
must ( container . Provide ( service . NewEvaluationService ) )
2025-09-15 18:47:39 +00:00
must ( container . Provide ( service . NewUserService ) )
2026-05-24 13:38:05 +00:00
must ( container . Provide ( service . NewSystemSettingService ) )
2026-04-13 09:23:16 +00:00
must ( container . Provide ( service . NewWeKnoraCloudService ) )
2025-12-23 08:56:30 +00:00
// Extract services - register individual extracters with names
2026-02-06 07:05:00 +00:00
must ( container . Provide ( service . NewChunkExtractService , dig . Name ( "chunkExtractor" ) ) )
2025-12-23 08:56:30 +00:00
must ( container . Provide ( service . NewDataTableSummaryService , dig . Name ( "dataTableSummary" ) ) )
2026-02-28 05:22:07 +00:00
must ( container . Provide ( service . NewImageMultimodalService , dig . Name ( "imageMultimodal" ) ) )
2026-04-16 06:59:23 +00:00
must ( container . Provide ( service . NewKnowledgePostProcessService , dig . Name ( "knowledgePostProcess" ) ) )
2025-11-05 15:18:44 +00:00
must ( container . Provide ( service . NewMessageService ) )
2025-11-08 19:27:24 +00:00
must ( container . Provide ( service . NewMCPServiceService ) )
feat(agent): human-in-the-loop approval for MCP tool calls (#1173)
Add an opt-in human approval gate so Agent runs pause before executing
MCP tools that operators flag as dangerous, surface an approval card in
the chat UI, and only resume after the user approves (optionally with
edited args) or rejects.
Backend
- New mcp_tool_approvals table + repo/service to mark per-tool approval
required (PG migration 000042 + sqlite init).
- approval.Gate coordinates RequestAndWait / Resolve with sync.Once
delivery, configurable timeout, and Redis Pub/Sub fan-out so multi-
replica deployments work without sticky sessions.
- MCPTool.Execute integrates the gate; uses a round-level ApprovalCtx
(without the per-tool 60s timeout) for the wait, and re-derives a
fresh 60s exec ctx after approval so CallTool keeps a full window.
- New SSE response types (tool_approval_required / _resolved) and
EventBus events plumb approval state to AgentStreamDisplay.
- REST: list/set per-tool approval flag, resolve pending approval.
- Configurable via agent.tool_approval_timeout_seconds (yaml) or
WEKNORA_AGENT_TOOL_APPROVAL_TIMEOUT env (accepts seconds or Go
duration).
Frontend
- MCP settings: per-tool "require approval" switch on the test panel.
- Chat: ToolApprovalCard renders the pause point with editable JSON
args, validation feedback, mm:ss countdown that turns warning/danger
near deadline, and a resolved state that retains context.
- i18n strings added for zh-CN / en-US / ko-KR / ru-RU.
Docs
- docs/zh/mcp-approval.md covering behavior, config, API, deployment
considerations (Redis cross-instance, restart limitations).
2026-05-10 13:23:49 +00:00
must ( container . Provide ( service . NewMCPToolApprovalService ) )
2025-12-24 02:34:41 +00:00
must ( container . Provide ( service . NewCustomAgentService ) )
2026-05-16 15:04:03 +00:00
must ( container . Provide ( service . NewUserResourceFavoriteService ) )
2026-02-12 08:02:09 +00:00
must ( container . Provide ( memoryService . NewMemoryService ) )
feat: Implement comprehensive wiki feature for knowledge bases
This commit introduces the complete wiki feature for WeKnora, enabling AI-powered wiki page generation and management. The implementation includes:
**Backend Changes:**
- Wiki data model: WikiPage type with support for multiple page types (Summary, Entity, Concept, Index, Log)
- Database schema: wiki_pages table with full migration support
- WikiPageService: CRUD operations and page management
- WikiPageRepository: GORM-based persistence layer
- Wiki ingest pipeline: Automated generation of wiki pages from knowledge documents
* Summary page generation using LLM
* Entity and concept extraction in a single LLM call
* Synthesis opportunity detection
* Index page rebuilding
* Log page maintenance
- Wiki boost feature: Enhance chat retrieval with wiki context
- Wiki linting: Maintenance and validation utilities
- Agent wiki tools: Enable agents to query and interact with wiki pages
- Wiki prompts: Comprehensive LLM prompt templates for all wiki generation tasks
- Language support: Reuse existing middleware language infrastructure for LLM prompts
**Frontend Changes:**
- Wiki browser UI: View all wiki pages with filtering and search
- Wiki API client: Knowledge base wiki management endpoints
- Knowledge base editor: Configure wiki settings (language, auto-ingest, synthesis model)
- i18n updates: Support for English, Korean, Russian, and Chinese interfaces
**Configuration:**
- Container DI: Wire up all wiki services
- Router: Register wiki API endpoints
- Task handling: Support async wiki ingest tasks
**Testing:**
- Unit tests for wiki page types
- Service layer tests
- Endpoint tests for wiki operations
- Integration tests with LLM mocking
**Documentation:**
- Language refactoring analysis and guides
- Implementation completion reports
- Quick reference guides for developers
**Key Features:**
✅ LLM-powered wiki page generation from documents
✅ Multi-language support (9+ languages)
✅ Automatic extraction of entities and concepts
✅ Synthesis opportunity detection
✅ Index and log page maintenance
✅ Progressive wiki building across multiple documents
✅ Agent-based wiki interaction
✅ Chat retrieval enhancement with wiki context
✅ Full frontend UI for wiki browsing
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 05:56:13 +00:00
must ( container . Provide ( service . NewWikiPageService ) )
2026-05-08 13:43:53 +00:00
must ( container . Provide ( service . NewWikiLogEntryService ) )
feat: Implement comprehensive wiki feature for knowledge bases
This commit introduces the complete wiki feature for WeKnora, enabling AI-powered wiki page generation and management. The implementation includes:
**Backend Changes:**
- Wiki data model: WikiPage type with support for multiple page types (Summary, Entity, Concept, Index, Log)
- Database schema: wiki_pages table with full migration support
- WikiPageService: CRUD operations and page management
- WikiPageRepository: GORM-based persistence layer
- Wiki ingest pipeline: Automated generation of wiki pages from knowledge documents
* Summary page generation using LLM
* Entity and concept extraction in a single LLM call
* Synthesis opportunity detection
* Index page rebuilding
* Log page maintenance
- Wiki boost feature: Enhance chat retrieval with wiki context
- Wiki linting: Maintenance and validation utilities
- Agent wiki tools: Enable agents to query and interact with wiki pages
- Wiki prompts: Comprehensive LLM prompt templates for all wiki generation tasks
- Language support: Reuse existing middleware language infrastructure for LLM prompts
**Frontend Changes:**
- Wiki browser UI: View all wiki pages with filtering and search
- Wiki API client: Knowledge base wiki management endpoints
- Knowledge base editor: Configure wiki settings (language, auto-ingest, synthesis model)
- i18n updates: Support for English, Korean, Russian, and Chinese interfaces
**Configuration:**
- Container DI: Wire up all wiki services
- Router: Register wiki API endpoints
- Task handling: Support async wiki ingest tasks
**Testing:**
- Unit tests for wiki page types
- Service layer tests
- Endpoint tests for wiki operations
- Integration tests with LLM mocking
**Documentation:**
- Language refactoring analysis and guides
- Implementation completion reports
- Quick reference guides for developers
**Key Features:**
✅ LLM-powered wiki page generation from documents
✅ Multi-language support (9+ languages)
✅ Automatic extraction of entities and concepts
✅ Synthesis opportunity detection
✅ Index and log page maintenance
✅ Progressive wiki building across multiple documents
✅ Agent-based wiki interaction
✅ Chat retrieval enhancement with wiki context
✅ Full frontend UI for wiki browsing
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 05:56:13 +00:00
must ( container . Provide ( service . NewWikiIngestService , dig . Name ( "wikiIngest" ) ) )
must ( container . Provide ( service . NewWikiLintService ) )
2026-06-12 14:40:18 +00:00
must ( container . Provide ( service . NewEmbedChannelService ) )
2025-11-05 15:18:44 +00:00
2025-11-11 06:25:20 +00:00
// Web search service (needed by AgentService)
2026-01-19 12:28:31 +00:00
logger . Debugf ( ctx , "[Container] Registering web search registry and providers..." )
2026-03-31 12:14:26 +00:00
must ( container . Provide ( infra_web_search . NewRegistry ) )
2026-01-19 12:28:31 +00:00
must ( container . Invoke ( registerWebSearchProviders ) )
2026-03-31 12:14:26 +00:00
must ( container . Provide ( repository . NewWebSearchProviderRepository ) )
2026-04-10 00:32:48 +00:00
must ( container . Provide ( repository . NewVectorStoreRepository ) )
refactor(retriever): introduce factory for KB-scoped retrieve engine resolution
Extracts the 25 repeated NewCompositeRetrieveEngine call sites across
seven services into two factory functions with tenant-ownership
verification: CreateRetrieveEngineForKB (synchronous) and
CreateRetrieveEngineFromPayload (async task handlers). Promotes
GetByStoreID from concrete-only to interfaces.RetrieveEngineRegistry.
Extends KBDeletePayload / IndexDeletePayload with an omitempty
VectorStoreID snapshot.
Design highlights
- Factory verifies tenant ownership of the resolved store
(defense-in-depth) so a gap in PR3 validation or a tampered Asynq
payload cannot cross tenants. Cross-tenant attempts return
ErrVectorStoreForbidden with a structured log entry.
- Sentinel errors (ErrTenantInfoMissing, ErrVectorStoreNotFound,
ErrVectorStoreForbidden) let async handlers classify non-retryable
failures as asynq.SkipRetry.
- nil and empty-string pointers for vectorStoreID normalize to
"unbound" so callers never send an empty UUID to GetByStoreID.
- resolveBoundEngine constructs engineInfos directly (with
slices.Clone of Support()) instead of going through
NewCompositeRetrieveEngine. The latter only reads from the
byEngineType map and cannot reach DB stores in byStoreID -- multiple
stores can share the same engine type. Unbound fallbacks still reuse
NewCompositeRetrieveEngine so the tenant effective-engines path is
byte-for-byte unchanged.
- DeleteKnowledgeBase now reads the KB before soft-delete so the
enqueued KBDeletePayload carries a VectorStoreID snapshot; once the
row is soft-deleted GORM's default scope hides it. Cost: +1 SELECT
per KB-delete request (a rare admin operation).
- enqueueIndexDeleteTask gains a vectorStoreID *string parameter that
the single caller (tag.go) populates from the owning KB. The worker
(ProcessIndexDelete) validates ownership via the factory.
- cleanupKnowledgeResources loads the KB so bound-store cleanup routes
correctly. If the load fails it warns and falls back to tenant
effective engines; orphan vectors become observable in logs instead
of disappearing silently.
- DeleteKnowledges (batch) stays on the tenant effective-engines path
-- batches can span stores and multi-store fan-out is PR4 scope.
Noted inline.
Merge safety
All knowledge bases have VectorStoreID = NULL at merge time (introduced
nullable in PR1, Tencent/WeKnora#994). Every factory call falls back to
NewCompositeRetrieveEngine(registry, tenantInfo.GetEffectiveEngines()),
which is the existing code path for these KBs. Async payloads from
before this change decode to VectorStoreID = nil (omitempty) and take
the same fallback.
Testing
- go build ./...
- go vet ./...
- go test -race -count=1 ./internal/application/service/retriever/...
covers unbound (nil/empty), bound, cross-tenant, unregistered store,
ownership infra error, legacy payload shapes (missing field/null/
empty string/nil), tampered payload, and parallel invocation.
- grep -r NewCompositeRetrieveEngine internal/application/service
returns zero results outside factory.go/composite.go.
Refs: Part of Tencent/WeKnora#993. Depends on Tencent/WeKnora#994.
2026-05-13 08:24:17 +00:00
// TenantStoreOwnership adapter used by the retriever factory functions
// to verify that a resolved VectorStore belongs to the caller's tenant.
must ( container . Provide ( retriever . NewVectorStoreRepoOwnership ) )
2025-11-11 06:25:20 +00:00
must ( container . Provide ( service . NewWebSearchService ) )
2026-03-31 12:14:26 +00:00
must ( container . Provide ( service . NewWebSearchProviderService ) )
2026-04-15 03:44:52 +00:00
must ( container . Provide ( NewEngineFactory ) )
// StoreRegistry: same instance as RetrieveEngineRegistry, exposed as StoreRegistry interface.
// NewRetrieveEngineRegistry always returns *retriever.RetrieveEngineRegistry which implements both.
must ( container . Provide ( func ( r interfaces . RetrieveEngineRegistry ) ( interfaces . StoreRegistry , error ) {
sr , ok := r . ( * retriever . RetrieveEngineRegistry )
if ! ok {
return nil , fmt . Errorf ( "registry does not implement StoreRegistry" )
}
return sr , nil
} ) )
2026-04-10 00:32:48 +00:00
must ( container . Provide ( service . NewVectorStoreService ) )
2025-11-11 06:25:20 +00:00
// Agent service layer (requires event bus, web search service)
// SessionService is passed as parameter to CreateAgentEngine method when creating AgentService
2026-01-05 02:15:55 +00:00
logger . Debugf ( ctx , "[Container] Registering event bus and agent service..." )
2025-11-05 15:18:44 +00:00
must ( container . Provide ( event . NewEventBus ) )
feat(agent): human-in-the-loop approval for MCP tool calls (#1173)
Add an opt-in human approval gate so Agent runs pause before executing
MCP tools that operators flag as dangerous, surface an approval card in
the chat UI, and only resume after the user approves (optionally with
edited args) or rejects.
Backend
- New mcp_tool_approvals table + repo/service to mark per-tool approval
required (PG migration 000042 + sqlite init).
- approval.Gate coordinates RequestAndWait / Resolve with sync.Once
delivery, configurable timeout, and Redis Pub/Sub fan-out so multi-
replica deployments work without sticky sessions.
- MCPTool.Execute integrates the gate; uses a round-level ApprovalCtx
(without the per-tool 60s timeout) for the wait, and re-derives a
fresh 60s exec ctx after approval so CallTool keeps a full window.
- New SSE response types (tool_approval_required / _resolved) and
EventBus events plumb approval state to AgentStreamDisplay.
- REST: list/set per-tool approval flag, resolve pending approval.
- Configurable via agent.tool_approval_timeout_seconds (yaml) or
WEKNORA_AGENT_TOOL_APPROVAL_TIMEOUT env (accepts seconds or Go
duration).
Frontend
- MCP settings: per-tool "require approval" switch on the test panel.
- Chat: ToolApprovalCard renders the pause point with editable JSON
args, validation feedback, mm:ss countdown that turns warning/danger
near deadline, and a resolved state that retains context.
- i18n strings added for zh-CN / en-US / ko-KR / ru-RU.
Docs
- docs/zh/mcp-approval.md covering behavior, config, API, deployment
considerations (Redis cross-instance, restart limitations).
2026-05-10 13:23:49 +00:00
must ( container . Provide ( func ( cfg * config . Config , s interfaces . MCPToolApprovalService , rdb * redis . Client ) * approval . Gate {
return approval . NewGate ( cfg , & approval . Adapter { Svc : s } , rdb )
} ) )
// Expose Gate as MCPApproval interface so AgentService and others can depend on the abstraction.
must ( container . Provide ( func ( g * approval . Gate ) approval . MCPApproval { return g } ) )
2025-11-05 15:18:44 +00:00
must ( container . Provide ( service . NewAgentService ) )
// Session service (depends on agent service)
2025-11-11 06:25:20 +00:00
// SessionService is created after AgentService and passes itself to AgentService.CreateAgentEngine when needed
2026-01-05 02:15:55 +00:00
logger . Debugf ( ctx , "[Container] Registering session service..." )
2025-11-28 08:10:37 +00:00
must ( container . Provide ( service . NewSessionService ) )
2025-08-05 07:08:07 +00:00
2026-02-28 05:22:07 +00:00
logger . Debugf ( ctx , "[Container] Registering task enqueuer..." )
redisAvailable := os . Getenv ( "REDIS_ADDR" ) != ""
if redisAvailable {
must ( container . Provide ( router . NewAsyncqClient , dig . As ( new ( interfaces . TaskEnqueuer ) ) ) )
must ( container . Provide ( router . NewAsynqServer ) )
feat: add knowledge parse cancellation with finalizing post-process state
Lets users stop an in-flight document parse to free up LLM / worker
resources without losing the chunks and index already written. The
core insight is that the previous parse_status=completed flipped as
soon as primary chunks landed, while the most expensive subtasks
(graph extract = N LLM calls per chunk, plus summary, question
generation) were still running in the background — so "completed"
wasn't actually terminal from a resource standpoint.
State machine
pending -> processing -> finalizing -> completed
|
+-> cancelled (any of the three
in-flight states)
+-> failed
+-> deleting
`finalizing` is the new post-process fan-out window. parse_status
only promotes to `completed` once pending_subtasks_count (a new
column tracking summary + question + per-chunk graph extract)
drains to zero via atomic FinalizeSubtask. Wiki ingest is
intentionally excluded from the counter — it's a KB-scoped
debounced batch and would otherwise pin parse_status in
`finalizing` for the wiki batch window.
Backend
- New ParseStatusFinalizing + pending_subtasks_count column with
migration 000056.
- knowledgeRepository.SetFinalizing transitions processing -> finalizing
conditionally so a racing cancel cannot be clobbered.
- knowledgeRepository.FinalizeSubtask atomically decrements the
counter and self-promotes the row to completed when it hits zero.
- KnowledgePostProcess restructured to compute expected subtask
count up front, flip to finalizing (or completed when no
enrichment is enabled), and only then fan out subtasks. Subtask
handlers (summary, question, graph extract) defer-decrement on
terminal exit using the existing isFinalAsynqAttempt convention.
- New POST /api/v1/knowledge/{id}/cancel-parse handler accepting
pending / processing / finalizing. Marks the row cancelled,
zeroes the counter, best-effort dequeues asynq tasks via a new
TaskInspector abstraction (asynq-mode walks pending/scheduled/
retry queues; Lite-mode noop), and scrubs wiki ingest pending op.
- SpanTracker.AbortAttempt flat-sweeps every still-running span
for the attempt via a new repo.CancelAllOpenSpans helper so the
trace viewer's striped bars all flip to cancelled, even leaf
generations whose parent stage already EndSpan'd (multimodal
fan-out pattern). knowledge_post_process closes its postSpan
via SkipSpan on the cancel/deleting entry guard so a worker
that opens a span AFTER the cancel sweep doesn't leak it.
- Housekeeping and resetPendingTasks sweep finalizing rows
identically to processing so a crash/restart can't strand them.
- DeleteKnowledge/DeleteKnowledgeList proactively dequeue
downstream tasks via the same TaskInspector path.
- ChunkExtractService gets a cancel entry guard so the most
expensive enrichment (graph extract) bails immediately when the
parent knowledge is aborted.
Frontend
- New cancelKnowledgeParse API client + "Stop parsing" entry in
both list view and card view more menus, gated on
pending/processing/finalizing.
- Polling predicate refactored to a shared isParseInFlight helper
that recognises `finalizing` (previously the doc list silently
stopped polling once parse_status flipped from processing).
- Knowledge processing timeline: isPolling includes finalizing,
new isHardTerminal short-circuits LIVE for cancelled/failed/
completed so stranded child spans cannot pin LIVE on.
- DocumentListView.computeStatus distinguishes finalizing
("增强中") from completed and shows the previous "生成摘要中"
copy when summary_status is still pending under finalizing.
Added cancelled badge as well.
- i18n: statusFinalizing / statusCancelled / cancelParse* keys
across zh-CN, en-US, ko-KR, ru-RU.
Docs / SDK
- docs/api/knowledge.md: documents the new finalizing state,
cancel-parse semantics, and which statuses accept cancel.
- client (Go SDK): CancelKnowledgeParse with docstring listing
the cancellable statuses.
2026-05-28 10:26:56 +00:00
// Asynq inspector for cancel-by-knowledge-id (best-effort
// dequeue of pending/scheduled/retry tasks + active-task cancel).
must ( container . Provide ( router . NewAsynqInspector ) )
must ( container . Provide ( router . NewAsynqTaskInspector ) )
2026-02-28 05:22:07 +00:00
} else {
syncExec := router . NewSyncTaskExecutor ( )
must ( container . Provide ( func ( ) interfaces . TaskEnqueuer { return syncExec } ) )
must ( container . Provide ( func ( ) * router . SyncTaskExecutor { return syncExec } ) )
feat: add knowledge parse cancellation with finalizing post-process state
Lets users stop an in-flight document parse to free up LLM / worker
resources without losing the chunks and index already written. The
core insight is that the previous parse_status=completed flipped as
soon as primary chunks landed, while the most expensive subtasks
(graph extract = N LLM calls per chunk, plus summary, question
generation) were still running in the background — so "completed"
wasn't actually terminal from a resource standpoint.
State machine
pending -> processing -> finalizing -> completed
|
+-> cancelled (any of the three
in-flight states)
+-> failed
+-> deleting
`finalizing` is the new post-process fan-out window. parse_status
only promotes to `completed` once pending_subtasks_count (a new
column tracking summary + question + per-chunk graph extract)
drains to zero via atomic FinalizeSubtask. Wiki ingest is
intentionally excluded from the counter — it's a KB-scoped
debounced batch and would otherwise pin parse_status in
`finalizing` for the wiki batch window.
Backend
- New ParseStatusFinalizing + pending_subtasks_count column with
migration 000056.
- knowledgeRepository.SetFinalizing transitions processing -> finalizing
conditionally so a racing cancel cannot be clobbered.
- knowledgeRepository.FinalizeSubtask atomically decrements the
counter and self-promotes the row to completed when it hits zero.
- KnowledgePostProcess restructured to compute expected subtask
count up front, flip to finalizing (or completed when no
enrichment is enabled), and only then fan out subtasks. Subtask
handlers (summary, question, graph extract) defer-decrement on
terminal exit using the existing isFinalAsynqAttempt convention.
- New POST /api/v1/knowledge/{id}/cancel-parse handler accepting
pending / processing / finalizing. Marks the row cancelled,
zeroes the counter, best-effort dequeues asynq tasks via a new
TaskInspector abstraction (asynq-mode walks pending/scheduled/
retry queues; Lite-mode noop), and scrubs wiki ingest pending op.
- SpanTracker.AbortAttempt flat-sweeps every still-running span
for the attempt via a new repo.CancelAllOpenSpans helper so the
trace viewer's striped bars all flip to cancelled, even leaf
generations whose parent stage already EndSpan'd (multimodal
fan-out pattern). knowledge_post_process closes its postSpan
via SkipSpan on the cancel/deleting entry guard so a worker
that opens a span AFTER the cancel sweep doesn't leak it.
- Housekeeping and resetPendingTasks sweep finalizing rows
identically to processing so a crash/restart can't strand them.
- DeleteKnowledge/DeleteKnowledgeList proactively dequeue
downstream tasks via the same TaskInspector path.
- ChunkExtractService gets a cancel entry guard so the most
expensive enrichment (graph extract) bails immediately when the
parent knowledge is aborted.
Frontend
- New cancelKnowledgeParse API client + "Stop parsing" entry in
both list view and card view more menus, gated on
pending/processing/finalizing.
- Polling predicate refactored to a shared isParseInFlight helper
that recognises `finalizing` (previously the doc list silently
stopped polling once parse_status flipped from processing).
- Knowledge processing timeline: isPolling includes finalizing,
new isHardTerminal short-circuits LIVE for cancelled/failed/
completed so stranded child spans cannot pin LIVE on.
- DocumentListView.computeStatus distinguishes finalizing
("增强中") from completed and shows the previous "生成摘要中"
copy when summary_status is still pending under finalizing.
Added cancelled badge as well.
- i18n: statusFinalizing / statusCancelled / cancelParse* keys
across zh-CN, en-US, ko-KR, ru-RU.
Docs / SDK
- docs/api/knowledge.md: documents the new finalizing state,
cancel-parse semantics, and which statuses accept cancel.
- client (Go SDK): CancelKnowledgeParse with docstring listing
the cancellable statuses.
2026-05-28 10:26:56 +00:00
// Lite mode: no Redis means no asynq inspector. SyncTaskExecutor
// dispatches inline goroutines that the checkpoint-based abort
// already handles.
must ( container . Provide ( router . NewNoopTaskInspector ) )
2026-02-28 05:22:07 +00:00
}
2025-11-13 11:34:33 +00:00
// Chat pipeline components for processing chat requests
2026-01-05 02:15:55 +00:00
logger . Debugf ( ctx , "[Container] Registering chat pipeline plugins..." )
2026-03-27 07:02:40 +00:00
// Data source sync framework
logger . Debugf ( ctx , "[Container] Registering data source sync framework..." )
must ( container . Provide ( initConnectorRegistry ) )
must ( container . Provide ( datasource . NewScheduler ) )
must ( container . Provide ( service . NewDataSourceService ) )
must ( container . Invoke ( startDataSourceScheduler ) )
logger . Debugf ( ctx , "[Container] Data source sync framework registered" )
feat(rbac): daily retention sweep for audit_logs (default 90 days)
The audit_logs table grows monotonically until something purges it.
PR 6 explicitly listed retention as out of scope for v1; this picks
that up.
Adds an `audit.retention_days` config (default 90, 0 disables) and a
small background goroutine `AuditLogRetentionRunner` that fires once
~10 minutes after boot and then every 24h, calling
`AuditLogService.Purge` which DELETEs rows older than the cutoff in a
single statement. The dependency surface is intentionally minimal —
no robfig/cron, no asynq, no migration — because retention has no
wall-clock alignment requirement.
Wiring is the same shape as the existing data source scheduler:
container `Provide(NewAuditLogRetentionRunner)`, an `Invoke` that
calls `Start`, and a `ResourceCleaner.RegisterWithName` for graceful
shutdown.
Defaults preserve operator intent:
- `audit:` section omitted from YAML -> retention_days=90.
- explicit `audit.retention_days: 0` in YAML -> purge disabled.
- `WEKNORA_AUDIT_RETENTION_DAYS=N` env override (incl. N=0).
- `retention_days < 0` is rejected by ValidateConfig.
Tests cover the service Purge contract (no-op when disabled, cutoff
math, error propagation) and the runner lifecycle (Start no-op when
disabled, idempotent Start/Stop, ticker cadence, runOnce swallows
errors). 10 new tests, all green.
docs/rbac.md updated with the new YAML / env / behaviour.
Refs: #1303
2026-05-15 12:10:47 +00:00
must ( container . Invoke ( startAuditLogRetention ) )
logger . Debugf ( ctx , "[Container] Audit log retention runner registered" )
2026-05-27 05:17:08 +00:00
must ( container . Provide ( service . NewHousekeepingService ) )
must ( container . Invoke ( startHousekeepingService ) )
logger . Debugf ( ctx , "[Container] Knowledge housekeeping runner registered" )
2026-03-22 17:57:06 +00:00
must ( container . Provide ( chatpipeline . NewEventManager ) )
must ( container . Invoke ( chatpipeline . NewPluginSearch ) )
must ( container . Invoke ( chatpipeline . NewPluginRerank ) )
2026-03-31 12:14:26 +00:00
must ( container . Invoke ( chatpipeline . NewPluginWebFetch ) )
2026-03-22 17:57:06 +00:00
must ( container . Invoke ( chatpipeline . NewPluginMerge ) )
must ( container . Invoke ( chatpipeline . NewPluginDataAnalysis ) )
must ( container . Invoke ( chatpipeline . NewPluginIntoChatMessage ) )
must ( container . Invoke ( chatpipeline . NewPluginChatCompletion ) )
must ( container . Invoke ( chatpipeline . NewPluginChatCompletionStream ) )
must ( container . Invoke ( chatpipeline . NewPluginFilterTopK ) )
must ( container . Invoke ( chatpipeline . NewPluginQueryUnderstand ) )
must ( container . Invoke ( chatpipeline . NewPluginLoadHistory ) )
must ( container . Invoke ( chatpipeline . NewPluginExtractEntity ) )
must ( container . Invoke ( chatpipeline . NewPluginSearchEntity ) )
must ( container . Invoke ( chatpipeline . NewPluginSearchParallel ) )
feat: Implement comprehensive wiki feature for knowledge bases
This commit introduces the complete wiki feature for WeKnora, enabling AI-powered wiki page generation and management. The implementation includes:
**Backend Changes:**
- Wiki data model: WikiPage type with support for multiple page types (Summary, Entity, Concept, Index, Log)
- Database schema: wiki_pages table with full migration support
- WikiPageService: CRUD operations and page management
- WikiPageRepository: GORM-based persistence layer
- Wiki ingest pipeline: Automated generation of wiki pages from knowledge documents
* Summary page generation using LLM
* Entity and concept extraction in a single LLM call
* Synthesis opportunity detection
* Index page rebuilding
* Log page maintenance
- Wiki boost feature: Enhance chat retrieval with wiki context
- Wiki linting: Maintenance and validation utilities
- Agent wiki tools: Enable agents to query and interact with wiki pages
- Wiki prompts: Comprehensive LLM prompt templates for all wiki generation tasks
- Language support: Reuse existing middleware language infrastructure for LLM prompts
**Frontend Changes:**
- Wiki browser UI: View all wiki pages with filtering and search
- Wiki API client: Knowledge base wiki management endpoints
- Knowledge base editor: Configure wiki settings (language, auto-ingest, synthesis model)
- i18n updates: Support for English, Korean, Russian, and Chinese interfaces
**Configuration:**
- Container DI: Wire up all wiki services
- Router: Register wiki API endpoints
- Task handling: Support async wiki ingest tasks
**Testing:**
- Unit tests for wiki page types
- Service layer tests
- Endpoint tests for wiki operations
- Integration tests with LLM mocking
**Documentation:**
- Language refactoring analysis and guides
- Implementation completion reports
- Quick reference guides for developers
**Key Features:**
✅ LLM-powered wiki page generation from documents
✅ Multi-language support (9+ languages)
✅ Automatic extraction of entities and concepts
✅ Synthesis opportunity detection
✅ Index and log page maintenance
✅ Progressive wiki building across multiple documents
✅ Agent-based wiki interaction
✅ Chat retrieval enhancement with wiki context
✅ Full frontend UI for wiki browsing
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 05:56:13 +00:00
must ( container . Invoke ( chatpipeline . NewPluginWikiBoost ) )
2026-03-22 17:57:06 +00:00
must ( container . Invoke ( chatpipeline . NewMemoryPlugin ) )
2026-01-05 02:15:55 +00:00
logger . Debugf ( ctx , "[Container] Chat pipeline plugins registered" )
2025-08-05 07:08:07 +00:00
// HTTP handlers layer
2026-01-05 02:15:55 +00:00
logger . Debugf ( ctx , "[Container] Registering HTTP handlers..." )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( handler . NewTenantHandler ) )
feat(rbac): tenant member management + invite_only gate (PR 3 of 3, #1303)
Wire the human-facing surface for the tenant-RBAC system that PR 1
introduced and PR 2 enforced: REST endpoints + UI for managing tenant
members, plus the long-pending invite_only registration gate.
Backend
- internal/handler/auth.go: Register now rejects with 403 when
auth.registration_mode=invite_only. PR 1 already exposes the mode via
/auth/config so the frontend hides the sign-up link; this is the
server-side enforcement for direct API calls.
- internal/handler/tenant_member.go: new TenantMemberHandler with
ListMembers / AddMember / UpdateMemberRole / RemoveMember. Maps
service-layer sentinels onto HTTP semantics (ErrLastOwner -> 409,
ErrMembershipAlreadyExists -> 409, ErrUserNotFound on AddMember -> 404,
ErrInvalidTenantRole -> 400). AddMember requires the invitee to
already have an account; SMTP-driven email invites are deferred.
- internal/types/tenant_member.go: new TenantMemberResponse projection
carrying the fields the management UI renders (email, username,
avatar, role, joined_at).
- internal/router/router.go: four routes under /tenants/:id/members
gated per the matrix (Viewer+ for list, Owner+ for every mutation).
- internal/container/container.go: dig provider for the new handler.
Tests
- handler/tenant_member_test.go: 12 table-driven cases covering happy
path, dangling-user tolerance, ErrLastOwner -> 409, ErrMembershipNotFound
-> 404, ErrMembershipAlreadyExists -> 409, unknown email -> 404,
invalid role rejected before user lookup, bad tenant id -> 400.
- handler/auth_register_invite_only_test.go: invite_only -> 403,
self_serve -> 201, nil Auth config falls through.
Frontend
- src/api/tenant/members.ts: typed client (TenantRole/TenantMember/...)
for the four endpoints.
- src/views/settings/TenantMembers.vue: members table with add dialog,
inline role select, confirm-remove modal. All mutation widgets gated
behind currentTenantRole === 'owner'; server still enforces.
- src/views/settings/Settings.vue: register the Members tab; show only
when currentTenantRole is loaded (avoids tab flash on cold nav).
- i18n in en-US/zh-CN/ko-KR/ru-RU: new tenantMember namespace covering
all UI strings and structured error messages (lastOwner / userNotFound
/ alreadyMember / invalidRole etc).
This completes the #1303 RBAC rollout. With cfg.Tenant.EnableRBAC=true
operators now have a full management surface; with EnableRBAC=false
the routes still exist but mutations log-and-pass per PR 2 contract.
2026-05-13 14:23:59 +00:00
must ( container . Provide ( handler . NewTenantMemberHandler ) )
2026-05-17 13:19:59 +00:00
must ( container . Provide ( handler . NewTenantInvitationHandler ) )
feat(rbac): per-tenant audit log for RBAC events (PR 6, #1303)
PR 1-5 of the multi-tenant RBAC series enforce the role matrix; what
they don't do is keep a durable record of who did what. Today the
RBAC middleware logs "[rbac] role insufficient ..." to stderr -
perishable, not searchable. Operators cannot answer "who removed
Alice from tenant T-foo on Tuesday" or "did we 403 a probing user
200 times last hour" after the fact.
This PR adds a generic per-tenant audit log that:
- Captures mutating RBAC actions (member add/remove/role-change/leave)
durably from the tenant_member service after the repo write succeeds.
- Captures enforcement rejections (RequireRole / RequireOwnershipOrRole
denies under EnableRBAC=true) via a gin-context-injected hook.
- Sliding-window dedup (1 minute) on (tenant, actor, action, path)
for denied events so a probing client cannot flood audit_logs.
- Default-on - no extra env flag. Schema is generic enough for future
KB / agent / datasource events to reuse via new action namespaces
without another migration.
Schema (migration 000044) mirrors wiki_log_entries' shape: a single
audit_logs table with action, target_type/id, request path/method,
outcome, and a JSONB details column. Three indexes: (tenant_id, id
DESC) for the per-tenant cursor feed, actor_user_id for "what did
Alice do", (tenant_id, action) for both the action filter and the
dedup lookup. Sqlite mirror added for Lite mode.
Wiring is nil-safe: the audit field on tenantMemberService and the
gin-context lookup in rbac.go both tolerate a nil service so existing
tests construct without a stub and dormant deployments degrade
gracefully if the provider is misconfigured.
The query API is GET /tenants/:id/audit-log, gated by Admin+ on top
of the existing PathTenantMatch (denial histories should not surface
to ordinary members). Cursor-paginated by descending id (sidesteps
the duplicate-timestamp tie-breaking that BIGSERIAL trivially solves).
Frontend: TenantMembers.vue gets a t-tabs wrapper with Members
(existing) and Audit log (new) tabs; the audit tab is gated to
Admin+ to mirror the server, lazy-loads on first open, paginates via
the next_cursor pattern, and renders coloured chips per
action/outcome so an operator can scan for anomalies. i18n keys
added in all four locales.
Tests: 14 new tests across service (6), middleware (4), and handler
(4). Service tests pin the dedup window behaviour (writes again
after expiry, dedup is per-actor-per-path, degrades on lookup
error). Middleware tests pin both reject sites' audit hook and the
"dormant mode does not fire" + "nil audit does not panic"
invariants. Handler tests pin the cursor envelope and that an empty
page returns next_cursor=0.
Out of scope: per-action ACL on the audit log, retention/TTL job,
KB/agent/datasource event wiring (schema supports it - just no
emitters yet), async writes, frontend filter UI.
2026-05-14 13:07:48 +00:00
must ( container . Provide ( handler . NewAuditLogHandler ) )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( handler . NewKnowledgeBaseHandler ) )
must ( container . Provide ( handler . NewKnowledgeHandler ) )
must ( container . Provide ( handler . NewChunkHandler ) )
2025-11-14 17:30:17 +00:00
must ( container . Provide ( handler . NewFAQHandler ) )
2025-11-17 10:15:02 +00:00
must ( container . Provide ( handler . NewTagHandler ) )
2025-11-08 16:02:31 +00:00
must ( container . Provide ( session . NewHandler ) )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( handler . NewMessageHandler ) )
must ( container . Provide ( handler . NewModelHandler ) )
must ( container . Provide ( handler . NewEvaluationHandler ) )
2025-08-10 09:04:39 +00:00
must ( container . Provide ( handler . NewInitializationHandler ) )
2025-09-15 18:47:39 +00:00
must ( container . Provide ( handler . NewAuthHandler ) )
2025-09-17 08:02:08 +00:00
must ( container . Provide ( handler . NewSystemHandler ) )
2025-11-08 19:27:24 +00:00
must ( container . Provide ( handler . NewMCPServiceHandler ) )
refactor(credentials): introduce /credentials subresource pattern
Replace the legacy "redacted placeholder + Clear* boolean" pattern with
dedicated per-resource credential subresources across MCP services,
Models, Web search providers, and Data sources.
Why
---
The previous design had three problems:
1. Main PUT body carried secret fields. The frontend echoed back a
redacted "***" placeholder, and a fragile MergeUpdate / IsRedactedOrEmpty
defense in the service layer tried to detect "user did not change this"
vs "user wants to clear this". A regression in that defense (or a new
frontend forgetting it) silently overwrites the stored secret with the
placeholder.
2. The "remove this credential" UX was a red checkbox under a pre-filled
password input. Three intents (preserve / replace / clear) collapsed
onto one field, and credential changes were bundled with unrelated
config edits in the same submit. Users wiped working keys by mistake.
3. Secret presence was inferred from "did the response come back with a
'***' placeholder", which couples the contract to a magic string.
Design
------
Each of the four resources now exposes:
PUT /{resource}/{id}/credentials # write one or more fields
DELETE /{resource}/{id}/credentials/{field} # clear a single field
"Is this configured?" metadata travels on the main resource response as
a typed map (dto.MCPServiceResponse.Credentials etc.) — no separate GET
endpoint. The frontend reads the configured boolean from the main GET
and never sees secret values at all.
Main PUT endpoints now ignore any secret fields in the request body and
log a deprecation warning if they appear, so legacy clients fail loudly
rather than overwriting silently.
Frontend
--------
- New reusable <CredentialResource> component renders a three-state card
(unconfigured / configured / editing) and drives the dedicated
endpoints. Used by MCP, Model, Web search; DataSource has a bespoke
card with the same behaviour because its credentials are a single
atomic per-connector map.
- Cancel from edit mode now restores state synchronously from the meta
prop. The previous async refresh() was a no-op while state was still
'editing', leaving the input frozen open.
- Remove is single-click + toast. The danger-themed button is the
deterrent; a modal confirm adds friction without adding safety (the
plaintext is irrecoverable client-side either way — recovery means
re-typing).
DTOs (internal/handler/dto/) are deliberately separate from the GORM
models so "no secret in response" is a compile-time invariant: a future
contributor cannot leak a secret without explicitly adding the field to
the DTO, which is review-able in a single diff.
Storage is unchanged — credentials still live in the existing jsonb /
parameters columns. No schema migration.
Cleanup
-------
- types.MCPService / types.Model / types.WebSearchProviderEntity /
types.DataSourceConfig: drop ClearAPIKey / ClearToken / ClearAppSecret
/ ClearCredentials boolean fields, MergeUpdate(), RedactSensitiveData().
- utils/types/secret.go: drop PreserveIfRedacted / IsRedactedOrEmpty.
RedactedSecretPlaceholder constant is retained because VectorStore
still uses the old pattern and is out of scope here.
- Frontend hasExistingApiKey / clearApiKey / convertToLegacyFormat
redaction handling removed; i18n keys renamed secret -> credential.
2026-05-17 07:09:30 +00:00
must ( container . Provide ( handler . NewMCPCredentialsHandler ) )
must ( container . Provide ( handler . NewModelCredentialsHandler ) )
must ( container . Provide ( handler . NewWebSearchProviderCredentialsHandler ) )
must ( container . Provide ( handler . NewDataSourceCredentialsHandler ) )
2025-11-09 19:14:12 +00:00
must ( container . Provide ( handler . NewWebSearchHandler ) )
2026-03-31 12:14:26 +00:00
must ( container . Provide ( handler . NewWebSearchProviderHandler ) )
2026-04-10 00:32:48 +00:00
must ( container . Provide ( handler . NewVectorStoreHandler ) )
2025-12-24 02:34:41 +00:00
must ( container . Provide ( handler . NewCustomAgentHandler ) )
2026-05-16 15:04:03 +00:00
must ( container . Provide ( handler . NewUserResourceFavoriteHandler ) )
2026-02-03 19:40:09 +00:00
must ( container . Provide ( service . NewSkillService ) )
must ( container . Provide ( handler . NewSkillHandler ) )
2026-01-30 08:28:01 +00:00
must ( container . Provide ( handler . NewOrganizationHandler ) )
2026-03-15 10:45:53 +00:00
2026-03-27 07:02:40 +00:00
// Data source handler
must ( container . Provide ( handler . NewDataSourceHandler ) )
feat: Implement comprehensive wiki feature for knowledge bases
This commit introduces the complete wiki feature for WeKnora, enabling AI-powered wiki page generation and management. The implementation includes:
**Backend Changes:**
- Wiki data model: WikiPage type with support for multiple page types (Summary, Entity, Concept, Index, Log)
- Database schema: wiki_pages table with full migration support
- WikiPageService: CRUD operations and page management
- WikiPageRepository: GORM-based persistence layer
- Wiki ingest pipeline: Automated generation of wiki pages from knowledge documents
* Summary page generation using LLM
* Entity and concept extraction in a single LLM call
* Synthesis opportunity detection
* Index page rebuilding
* Log page maintenance
- Wiki boost feature: Enhance chat retrieval with wiki context
- Wiki linting: Maintenance and validation utilities
- Agent wiki tools: Enable agents to query and interact with wiki pages
- Wiki prompts: Comprehensive LLM prompt templates for all wiki generation tasks
- Language support: Reuse existing middleware language infrastructure for LLM prompts
**Frontend Changes:**
- Wiki browser UI: View all wiki pages with filtering and search
- Wiki API client: Knowledge base wiki management endpoints
- Knowledge base editor: Configure wiki settings (language, auto-ingest, synthesis model)
- i18n updates: Support for English, Korean, Russian, and Chinese interfaces
**Configuration:**
- Container DI: Wire up all wiki services
- Router: Register wiki API endpoints
- Task handling: Support async wiki ingest tasks
**Testing:**
- Unit tests for wiki page types
- Service layer tests
- Endpoint tests for wiki operations
- Integration tests with LLM mocking
**Documentation:**
- Language refactoring analysis and guides
- Implementation completion reports
- Quick reference guides for developers
**Key Features:**
✅ LLM-powered wiki page generation from documents
✅ Multi-language support (9+ languages)
✅ Automatic extraction of entities and concepts
✅ Synthesis opportunity detection
✅ Index and log page maintenance
✅ Progressive wiki building across multiple documents
✅ Agent-based wiki interaction
✅ Chat retrieval enhancement with wiki context
✅ Full frontend UI for wiki browsing
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 05:56:13 +00:00
// Wiki page handler
must ( container . Provide ( handler . NewWikiPageHandler ) )
2026-03-15 10:45:53 +00:00
// IM integration
logger . Debugf ( ctx , "[Container] Registering IM integration..." )
must ( container . Provide ( imPkg . NewService ) )
2026-03-15 18:23:22 +00:00
must ( container . Invoke ( registerIMAdapterFactories ) )
2026-03-15 10:45:53 +00:00
must ( container . Provide ( handler . NewIMHandler ) )
2026-06-12 14:40:18 +00:00
must ( container . Provide ( handler . NewEmbedChannelHandler ) )
2026-04-13 09:23:16 +00:00
must ( container . Provide ( handler . NewWeKnoraCloudHandler ) )
2026-01-05 02:15:55 +00:00
logger . Debugf ( ctx , "[Container] HTTP handlers registered" )
2025-08-05 07:08:07 +00:00
2026-06-01 12:53:26 +00:00
// Wire the chat package's local image resolver so multimodal chat can read
// local:// images that live under a tenant's configured storage PathPrefix
// (which is not encoded in the local:// URL).
must ( container . Invoke ( registerChatLocalImageResolver ) )
2025-08-05 07:08:07 +00:00
// Router configuration
2026-02-28 05:22:07 +00:00
logger . Debugf ( ctx , "[Container] Registering router and starting task server..." )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( router . NewRouter ) )
2026-02-28 05:22:07 +00:00
if redisAvailable {
must ( container . Invoke ( router . RunAsynqServer ) )
} else {
must ( container . Invoke ( router . RegisterSyncHandlers ) )
}
2025-08-05 07:08:07 +00:00
2026-01-05 02:15:55 +00:00
logger . Infof ( ctx , "[Container] Container initialization completed successfully" )
2025-08-05 07:08:07 +00:00
return container
}
2026-06-01 12:53:26 +00:00
// registerChatLocalImageResolver wires the chat package's LocalImageResolver
// hook. Stored local:// URLs are relative to the resolved storage base dir and
// do NOT encode the owning tenant's configured PathPrefix, so resolving them to
// disk bytes requires rebuilding the FileService from that tenant's storage
// config. The owning tenant is parsed from the URL's first path segment, which
// correctly handles cross-tenant shared resources (e.g. shared KB images).
func registerChatLocalImageResolver ( tenantRepo interfaces . TenantRepository ) {
chat . LocalImageResolver = func ( storageURL string ) ( [ ] byte , bool ) {
tenantID := secutils . ParseTenantIDFromStoragePath ( storageURL )
if tenantID == 0 {
return nil , false
}
ctx := context . Background ( )
tenant , err := tenantRepo . GetTenantByID ( ctx , tenantID )
if err != nil || tenant == nil {
return nil , false
}
baseDir := strings . TrimSpace ( os . Getenv ( "LOCAL_STORAGE_BASE_DIR" ) )
fileSvc , _ , err := file . NewFileServiceFromStorageConfig ( "local" , tenant . StorageEngineConfig , baseDir )
if err != nil {
return nil , false
}
rc , err := fileSvc . GetFile ( ctx , storageURL )
if err != nil {
return nil , false
}
defer rc . Close ( )
data , err := io . ReadAll ( rc )
if err != nil {
return nil , false
}
return data , true
}
}
2025-08-05 07:08:07 +00:00
// must is a helper function for error handling
// Panics if the error is not nil, useful for configuration steps that must succeed
// Parameters:
// - err: Error to check
func must ( err error ) {
if err != nil {
panic ( err )
}
}
feat(observability): integrate Langfuse for LLM token tracking and tracing
Closes #620 #497. Add opt-in Langfuse observability covering all five
model types (chat, embedding, rerank, VLM, ASR) with HTTP-request-scoped
traces and Docker Compose support (both cloud and self-hosted).
Core package internal/tracing/langfuse:
- HTTP client with batched async ingestion (non-blocking in request path)
- Sampling, environment / release tagging, and graceful fallback when
LANGFUSE_* env vars are absent (wrappers become no-ops)
- Gin middleware opens one trace per traced request and finishes it after
the handler chain returns, attaching method / path / user / session
- Trace context is stored under a typed key exported from internal/types
so logger.CloneContext can preserve it across handler / goroutine
boundaries (otherwise each LLM call auto-created an orphan trace,
fragmenting one request into many)
Per-model generation wrappers (opt-in via NewChat/NewEmbedder/...):
- chat: captures prompt, streaming output, token usage + TTFT
- embedding: approximates tokens when the provider omits usage
- rerank: previews query/docs, summarizes results to keep payload small
- vlm: records image count and total bytes, never uploads raw pixels
- asr: records file size and audio duration, never uploads audio bytes
Async title generation (GenerateTitleAsync) now forwards the trace key
into the goroutine so title calls appear under the parent chat trace.
Docker Compose:
- LANGFUSE_* env passthrough on the `app` service for cloud deployments
- Optional `langfuse` profile spins up a self-hosted Langfuse stack that
reuses WeKnora's existing PostgreSQL (separate database via an idempotent
init container that fixes ICU collation drift) and Redis (separate DB
number), adding only ClickHouse, MinIO, web and worker containers
- web/worker entrypoints URL-encode DB_PASSWORD / REDIS_PASSWORD at start
to avoid Prisma P1013 when passwords contain @ / # / etc.
Docs: docs/Langfuse集成.md covers cloud vs self-hosted, per-model usage
strategy, code map, and resource footprint.
2026-04-23 17:57:12 +00:00
// initLangfuse initializes the Langfuse ingestion client.
// Configuration is read from LANGFUSE_* environment variables (see
// docs/langfuse.md). Returns a disabled manager if credentials are absent —
// never an error — so deployments that don't use Langfuse are unaffected.
func initLangfuse ( ) ( * langfuse . Manager , error ) {
cfg := langfuse . LoadConfigFromEnv ( )
return langfuse . Init ( cfg )
}
2025-11-06 13:12:26 +00:00
func initRedisClient ( ) ( * redis . Client , error ) {
2026-02-28 05:22:07 +00:00
redisAddr := os . Getenv ( "REDIS_ADDR" )
if redisAddr == "" {
logger . Infof ( context . Background ( ) , "[Redis] No REDIS_ADDR configured, Redis disabled (Lite mode)" )
return nil , nil
}
2025-11-06 13:12:26 +00:00
db , err := strconv . Atoi ( os . Getenv ( "REDIS_DB" ) )
if err != nil {
2026-02-28 05:22:07 +00:00
db = 0
2025-11-06 13:12:26 +00:00
}
client := redis . NewClient ( & redis . Options {
2026-02-28 05:22:07 +00:00
Addr : redisAddr ,
2026-02-04 10:48:04 +00:00
Username : os . Getenv ( "REDIS_USERNAME" ) ,
2025-11-06 13:12:26 +00:00
Password : os . Getenv ( "REDIS_PASSWORD" ) ,
DB : db ,
} )
_ , err = client . Ping ( context . Background ( ) ) . Result ( )
if err != nil {
return nil , fmt . Errorf ( "连接Redis失败: %w" , err )
}
return client , nil
}
2025-08-05 07:08:07 +00:00
// initDatabase initializes database connection
// Creates and configures database connection based on environment configuration
// Supports multiple database backends (PostgreSQL)
// Parameters:
// - cfg: Application configuration
//
// Returns:
// - Configured database connection
// - Error if connection fails
func initDatabase ( cfg * config . Config ) ( * gorm . DB , error ) {
var dialector gorm . Dialector
2025-11-08 19:27:24 +00:00
var migrateDSN string
2026-04-10 21:48:53 +00:00
var sqliteDBPath string
2025-08-05 07:08:07 +00:00
switch os . Getenv ( "DB_DRIVER" ) {
case "postgres" :
2025-11-08 19:27:24 +00:00
// DSN for GORM (key-value format)
gormDSN := fmt . Sprintf (
2026-03-30 11:33:17 +00:00
"host=%s port=%s user=%s password=%s dbname=%s sslmode=%s TimeZone=UTC" ,
2025-08-05 07:08:07 +00:00
os . Getenv ( "DB_HOST" ) ,
os . Getenv ( "DB_PORT" ) ,
os . Getenv ( "DB_USER" ) ,
os . Getenv ( "DB_PASSWORD" ) ,
os . Getenv ( "DB_NAME" ) ,
"disable" ,
)
2025-11-08 19:27:24 +00:00
dialector = postgres . Open ( gormDSN )
// DSN for golang-migrate (URL format)
// URL-encode password to handle special characters like !@#
dbPassword := os . Getenv ( "DB_PASSWORD" )
encodedPassword := url . QueryEscape ( dbPassword )
2025-12-09 06:20:01 +00:00
// Check if postgres is in RETRIEVE_DRIVER to determine skip_embedding
retrieveDriver := strings . Split ( os . Getenv ( "RETRIEVE_DRIVER" ) , "," )
skipEmbedding := "true"
if slices . Contains ( retrieveDriver , "postgres" ) {
skipEmbedding = "false"
}
logger . Infof ( context . Background ( ) , "Skip embedding: %s" , skipEmbedding )
2025-11-08 19:27:24 +00:00
migrateDSN = fmt . Sprintf (
2025-12-09 06:20:01 +00:00
"postgres://%s:%s@%s:%s/%s?sslmode=disable&options=-c%%20app.skip_embedding=%s" ,
2025-11-08 19:27:24 +00:00
os . Getenv ( "DB_USER" ) ,
encodedPassword , // Use encoded password
os . Getenv ( "DB_HOST" ) ,
os . Getenv ( "DB_PORT" ) ,
os . Getenv ( "DB_NAME" ) ,
2025-12-09 06:20:01 +00:00
skipEmbedding ,
2025-11-08 19:27:24 +00:00
)
// Debug log (don't log password)
logger . Infof ( context . Background ( ) , "DB Config: user=%s host=%s port=%s dbname=%s" ,
os . Getenv ( "DB_USER" ) ,
os . Getenv ( "DB_HOST" ) ,
os . Getenv ( "DB_PORT" ) ,
os . Getenv ( "DB_NAME" ) ,
)
2026-02-28 05:22:07 +00:00
case "sqlite" :
dbPath := os . Getenv ( "DB_PATH" )
if dbPath == "" {
dbPath = "./data/weknora.db"
}
if dir := filepath . Dir ( dbPath ) ; dir != "." && dir != "" {
2026-04-13 09:23:16 +00:00
if err := os . MkdirAll ( dir , 0 o755 ) ; err != nil {
2026-02-28 05:22:07 +00:00
return nil , fmt . Errorf ( "failed to create SQLite data directory %s: %w" , dir , err )
}
}
sqlite_vec . Auto ( )
dsn := dbPath + "?_journal_mode=WAL&_busy_timeout=5000&_foreign_keys=on"
dialector = sqlite . Open ( dsn )
2026-04-10 21:48:53 +00:00
sqliteDBPath = dbPath
2026-02-28 05:22:07 +00:00
migrateDSN = "sqlite3://" + dbPath
logger . Infof ( context . Background ( ) , "DB Config: driver=sqlite path=%s" , dbPath )
2025-08-05 07:08:07 +00:00
default :
return nil , fmt . Errorf ( "unsupported database driver: %s" , os . Getenv ( "DB_DRIVER" ) )
}
2026-03-27 07:02:40 +00:00
db , err := gorm . Open ( dialector , & gorm . Config {
NowFunc : func ( ) time . Time {
return time . Now ( ) . UTC ( )
} ,
} )
2025-08-05 07:08:07 +00:00
if err != nil {
return nil , err
}
2026-05-18 01:10:01 +00:00
// Sanity check: dialect-specific code in services (notably the
// vector_stores delete guard) compares Dialector.Name() to "postgres" /
// "sqlite" string literals. A future driver swap that produces a
// different name (e.g., a wrapper dialect for managed PG) would silently
// fall back to the SQLite path, dropping the row-level X-lock. Catching
// the mismatch at startup is loud and inexpensive.
if name := db . Dialector . Name ( ) ; name != "postgres" && name != "sqlite" {
return nil , fmt . Errorf (
"unsupported gorm dialector %q; expected postgres or sqlite " +
"(see vectorStoreService.isPostgres for impact)" , name )
}
2026-02-28 05:22:07 +00:00
if os . Getenv ( "DB_DRIVER" ) == "sqlite" {
sqlDB , err := db . DB ( )
if err != nil {
return nil , fmt . Errorf ( "failed to get underlying sql.DB: %w" , err )
}
if err := sqlDB . Ping ( ) ; err != nil {
return nil , fmt . Errorf ( "failed to ping SQLite database: %w" , err )
}
}
2025-11-08 19:27:24 +00:00
// Run database migrations automatically (optional, can be disabled via env var)
// To disable auto-migration, set AUTO_MIGRATE=false
2025-12-08 09:40:10 +00:00
// To enable auto-recovery from dirty state, set AUTO_RECOVER_DIRTY=true
2025-11-08 19:27:24 +00:00
if os . Getenv ( "AUTO_MIGRATE" ) != "false" {
logger . Infof ( context . Background ( ) , "Running database migrations..." )
2025-12-09 06:20:01 +00:00
2025-12-16 04:07:25 +00:00
autoRecover := os . Getenv ( "AUTO_RECOVER_DIRTY" ) != "false"
2025-12-09 06:20:01 +00:00
migrationOpts := database . MigrationOptions {
2025-12-08 09:40:10 +00:00
AutoRecoverDirty : autoRecover ,
2026-04-10 21:48:53 +00:00
SQLiteDBPath : sqliteDBPath ,
2025-12-09 06:20:01 +00:00
}
// Run base migrations (all versioned migrations including embeddings)
// The embeddings migration will be conditionally executed based on skip_embedding parameter in DSN
if err := database . RunMigrationsWithOptions ( migrateDSN , migrationOpts ) ; err != nil {
2025-11-08 19:27:24 +00:00
// Log warning but don't fail startup - migrations might be handled externally
logger . Warnf ( context . Background ( ) , "Database migration failed: %v" , err )
2025-11-28 08:17:52 +00:00
logger . Warnf (
context . Background ( ) ,
"Continuing with application startup. Please run migrations manually if needed." ,
)
2025-11-08 19:27:24 +00:00
}
2026-03-02 03:02:19 +00:00
// Post-migration: resolve __pending_env__ storage provider markers for historical KBs.
// The SQL migration marks KBs that have documents but no provider with "__pending_env__";
// we replace that with the actual STORAGE_TYPE from the environment.
resolveStorageProviderPending ( db )
2026-05-22 15:15:12 +00:00
// Post-migration: declarative built-in models from config/builtin_models.yaml (optional).
if err := types . LoadBuiltinModelsConfig ( context . Background ( ) , db , config . ConfigDir ( ) ) ; err != nil {
logger . Warnf ( context . Background ( ) , "Load builtin models config failed: %v" , err )
}
2025-11-08 19:27:24 +00:00
} else {
logger . Infof ( context . Background ( ) , "Auto-migration is disabled (AUTO_MIGRATE=false)" )
}
2025-08-05 07:08:07 +00:00
// Get underlying SQL DB object
sqlDB , err := db . DB ( )
if err != nil {
return nil , err
}
// Configure connection pool parameters
2026-02-28 05:22:07 +00:00
if os . Getenv ( "DB_DRIVER" ) == "sqlite" {
// SQLite only supports one concurrent writer even in WAL mode.
// Limiting to a single open connection serialises all DB access and
// prevents "database is locked" errors from concurrent goroutines.
sqlDB . SetMaxOpenConns ( 1 )
} else {
sqlDB . SetMaxIdleConns ( 10 )
}
2025-08-05 07:08:07 +00:00
sqlDB . SetConnMaxLifetime ( time . Duration ( 10 ) * time . Minute )
return db , nil
}
2026-03-02 03:02:19 +00:00
// resolveStorageProviderPending replaces the "__pending_env__" sentinel in
// knowledge_bases.storage_provider_config with the actual STORAGE_TYPE from the environment.
// This runs once after SQL migrations to bind historical KBs to their real storage provider.
func resolveStorageProviderPending ( db * gorm . DB ) {
storageType := strings . TrimSpace ( os . Getenv ( "STORAGE_TYPE" ) )
if storageType == "" {
storageType = "local"
}
storageType = strings . ToLower ( storageType )
result := db . Exec (
` UPDATE knowledge_bases SET storage_provider_config = ? WHERE storage_provider_config IS NOT NULL AND storage_provider_config->>'provider' = '__pending_env__' ` ,
fmt . Sprintf ( ` { "provider":"%s"} ` , storageType ) ,
)
if result . Error != nil {
logger . Warnf ( context . Background ( ) , "Failed to resolve __pending_env__ storage providers: %v" , result . Error )
} else if result . RowsAffected > 0 {
logger . Infof ( context . Background ( ) , "Resolved %d knowledge bases with __pending_env__ storage provider → %s" , result . RowsAffected , storageType )
}
2026-04-10 21:48:53 +00:00
2026-04-16 14:39:10 +00:00
// Sync PostgreSQL sequences with actual MAX values to prevent duplicate key
// errors. The old code assigned seq_id via SELECT MAX()+1 in application
// code, which could push values past the DB sequence counter.
syncSequences ( db )
2026-04-10 21:48:53 +00:00
// Reset any pending tasks left over from previous aborted runs (Lite App mode)
resetPendingTasks ( db )
}
2026-04-16 14:39:10 +00:00
// syncSequences ensures PostgreSQL sequences for auto-increment columns (seq_id)
// are at least as high as the current MAX value in each table. This is needed
// because older code assigned seq_id via application-level MAX()+1, which could
// advance values past the DB sequence counter and cause duplicate key errors.
func syncSequences ( db * gorm . DB ) {
if db . Dialector . Name ( ) != "postgres" {
return
}
pairs := [ ] [ 2 ] string {
{ "chunks" , "chunks_seq_id_seq" } ,
{ "knowledge_tags" , "knowledge_tags_seq_id_seq" } ,
}
for _ , p := range pairs {
table , seq := p [ 0 ] , p [ 1 ]
sql := fmt . Sprintf (
` SELECT setval('%s', GREATEST(nextval('%s'), (SELECT COALESCE(MAX(seq_id), 0) FROM %s))) ` ,
seq , seq , table ,
)
if err := db . Exec ( sql ) . Error ; err != nil {
logger . Warnf ( context . Background ( ) , "Failed to sync sequence %s: %v" , seq , err )
} else {
logger . Infof ( context . Background ( ) , "Synced sequence %s with table %s" , seq , table )
}
}
}
2025-08-05 07:08:07 +00:00
// initFileService initializes file storage service
// Creates the appropriate file storage service based on configuration
// Supports multiple storage backends (MinIO, COS, local filesystem)
// Parameters:
// - cfg: Application configuration
//
// Returns:
// - Configured file service implementation
// - Error if initialization fails
func initFileService ( cfg * config . Config ) ( interfaces . FileService , error ) {
2026-02-28 05:22:07 +00:00
storageType := strings . TrimSpace ( os . Getenv ( "STORAGE_TYPE" ) )
if storageType == "" {
storageType = "local"
}
switch storageType {
2025-08-05 07:08:07 +00:00
case "minio" :
if os . Getenv ( "MINIO_ENDPOINT" ) == "" ||
os . Getenv ( "MINIO_ACCESS_KEY_ID" ) == "" ||
os . Getenv ( "MINIO_SECRET_ACCESS_KEY" ) == "" ||
os . Getenv ( "MINIO_BUCKET_NAME" ) == "" {
return nil , fmt . Errorf ( "missing MinIO configuration" )
}
return file . NewMinioFileService (
os . Getenv ( "MINIO_ENDPOINT" ) ,
os . Getenv ( "MINIO_ACCESS_KEY_ID" ) ,
os . Getenv ( "MINIO_SECRET_ACCESS_KEY" ) ,
os . Getenv ( "MINIO_BUCKET_NAME" ) ,
2025-12-09 06:20:01 +00:00
strings . EqualFold ( os . Getenv ( "MINIO_USE_SSL" ) , "true" ) ,
2025-08-05 07:08:07 +00:00
)
case "cos" :
2025-09-15 12:49:34 +00:00
if os . Getenv ( "COS_BUCKET_NAME" ) == "" ||
2025-08-05 07:08:07 +00:00
os . Getenv ( "COS_REGION" ) == "" ||
os . Getenv ( "COS_SECRET_ID" ) == "" ||
os . Getenv ( "COS_SECRET_KEY" ) == "" ||
os . Getenv ( "COS_PATH_PREFIX" ) == "" {
return nil , fmt . Errorf ( "missing COS configuration" )
}
2026-01-06 02:51:40 +00:00
return file . NewCosFileServiceWithTempBucket (
2025-09-15 12:49:34 +00:00
os . Getenv ( "COS_BUCKET_NAME" ) ,
2025-08-05 07:08:07 +00:00
os . Getenv ( "COS_REGION" ) ,
os . Getenv ( "COS_SECRET_ID" ) ,
os . Getenv ( "COS_SECRET_KEY" ) ,
os . Getenv ( "COS_PATH_PREFIX" ) ,
2026-02-28 05:22:07 +00:00
os . Getenv ( "COS_TEMP_BUCKET_NAME" ) ,
os . Getenv ( "COS_TEMP_REGION" ) ,
2025-08-05 07:08:07 +00:00
)
2026-02-24 15:12:28 +00:00
case "tos" :
if os . Getenv ( "TOS_ENDPOINT" ) == "" ||
os . Getenv ( "TOS_REGION" ) == "" ||
os . Getenv ( "TOS_ACCESS_KEY" ) == "" ||
os . Getenv ( "TOS_SECRET_KEY" ) == "" ||
os . Getenv ( "TOS_BUCKET_NAME" ) == "" {
return nil , fmt . Errorf ( "missing TOS configuration" )
}
return file . NewTosFileServiceWithTempBucket (
os . Getenv ( "TOS_ENDPOINT" ) ,
os . Getenv ( "TOS_REGION" ) ,
os . Getenv ( "TOS_ACCESS_KEY" ) ,
os . Getenv ( "TOS_SECRET_KEY" ) ,
os . Getenv ( "TOS_BUCKET_NAME" ) ,
os . Getenv ( "TOS_PATH_PREFIX" ) ,
os . Getenv ( "TOS_TEMP_BUCKET_NAME" ) , // 可选:临时桶名称(桶需配置生命周期规则自动过期)
os . Getenv ( "TOS_TEMP_REGION" ) , // 可选:临时桶 region, 默认与主桶相同
)
2026-03-07 06:01:22 +00:00
case "s3" :
if os . Getenv ( "S3_ENDPOINT" ) == "" ||
os . Getenv ( "S3_REGION" ) == "" ||
os . Getenv ( "S3_ACCESS_KEY" ) == "" ||
os . Getenv ( "S3_SECRET_KEY" ) == "" ||
os . Getenv ( "S3_BUCKET_NAME" ) == "" {
return nil , fmt . Errorf ( "missing S3 configuration" )
}
pathPrefix := os . Getenv ( "S3_PATH_PREFIX" )
if pathPrefix == "" {
pathPrefix = "weknora/"
}
return file . NewS3FileService (
os . Getenv ( "S3_ENDPOINT" ) ,
os . Getenv ( "S3_ACCESS_KEY" ) ,
os . Getenv ( "S3_SECRET_KEY" ) ,
os . Getenv ( "S3_BUCKET_NAME" ) ,
os . Getenv ( "S3_REGION" ) ,
pathPrefix ,
)
2026-05-18 10:54:57 +00:00
case "obs" :
if os . Getenv ( "OBS_ENDPOINT" ) == "" ||
os . Getenv ( "OBS_ACCESS_KEY" ) == "" ||
os . Getenv ( "OBS_SECRET_KEY" ) == "" ||
os . Getenv ( "OBS_BUCKET_NAME" ) == "" {
return nil , fmt . Errorf ( "missing OBS configuration" )
}
obsRegion := os . Getenv ( "OBS_REGION" )
obsPathPrefix := os . Getenv ( "OBS_PATH_PREFIX" )
if obsPathPrefix == "" {
obsPathPrefix = "weknora/"
}
return file . NewObsFileService (
os . Getenv ( "OBS_ENDPOINT" ) ,
obsRegion ,
os . Getenv ( "OBS_ACCESS_KEY" ) ,
os . Getenv ( "OBS_SECRET_KEY" ) ,
os . Getenv ( "OBS_BUCKET_NAME" ) ,
obsPathPrefix ,
)
2026-04-13 03:57:47 +00:00
case "oss" :
if os . Getenv ( "OSS_ENDPOINT" ) == "" ||
os . Getenv ( "OSS_REGION" ) == "" ||
os . Getenv ( "OSS_ACCESS_KEY" ) == "" ||
os . Getenv ( "OSS_SECRET_KEY" ) == "" ||
os . Getenv ( "OSS_BUCKET_NAME" ) == "" {
return nil , fmt . Errorf ( "missing OSS configuration" )
}
pathPrefix := os . Getenv ( "OSS_PATH_PREFIX" )
if pathPrefix == "" {
pathPrefix = "weknora/"
}
return file . NewOssFileServiceWithTempBucket (
os . Getenv ( "OSS_ENDPOINT" ) ,
os . Getenv ( "OSS_REGION" ) ,
os . Getenv ( "OSS_ACCESS_KEY" ) ,
os . Getenv ( "OSS_SECRET_KEY" ) ,
os . Getenv ( "OSS_BUCKET_NAME" ) ,
pathPrefix ,
os . Getenv ( "OSS_TEMP_BUCKET_NAME" ) ,
os . Getenv ( "OSS_TEMP_REGION" ) ,
)
2025-08-05 07:08:07 +00:00
case "local" :
2026-02-28 05:22:07 +00:00
baseDir := os . Getenv ( "LOCAL_STORAGE_BASE_DIR" )
if baseDir == "" {
baseDir = "/data/files"
}
fix(im): rewrite private storage URLs to HTTP in IM channel replies
IM platforms (Feishu, Slack, Telegram, DingTalk, Mattermost, WeCom) cannot
render provider:// URLs (local://, minio://, s3://, etc.) that appear in
LLM answers containing knowledge base images. The web frontend handles
these via the authenticated /files endpoint, but IM clients need publicly
resolvable HTTP URLs.
Changes:
- Add HMAC-SHA256 presigned URL utility (internal/utils/presign.go) for
generating time-limited, signature-verified file access URLs
- Add GET /api/v1/files/presigned endpoint that serves files without
session auth, verified by HMAC signature and expiry
- Update localFileService.GetFileURL() to return presigned HTTP URLs
when APP_EXTERNAL_URL is configured (cloud backends already return
presigned URLs via their SDKs)
- Add IM content rewriting pipeline: strip <image> XML tags, strip
citation tags, rewrite storage URLs to HTTP — applied at all IM
output points (streaming flush, non-streaming reply, fallback)
- Add holdback buffer in streaming flush to prevent URL/tag splitting
across chunk boundaries
Closes #1058
2026-04-28 12:22:04 +00:00
externalURL := strings . TrimSpace ( os . Getenv ( "APP_EXTERNAL_URL" ) )
return file . NewLocalFileService ( baseDir , externalURL ) , nil
2025-08-05 07:08:07 +00:00
case "dummy" :
return file . NewDummyFileService ( ) , nil
default :
2026-02-28 05:22:07 +00:00
return nil , fmt . Errorf ( "unsupported storage type: %s" , storageType )
2025-08-05 07:08:07 +00:00
}
}
// initRetrieveEngineRegistry initializes the retrieval engine registry
// Sets up and configures various search engine backends based on configuration
// Supports multiple retrieval engines (PostgreSQL, ElasticsearchV7, ElasticsearchV8)
// Parameters:
// - db: Database connection
// - cfg: Application configuration
//
// Returns:
// - Configured retrieval engine registry
// - Error if initialization fails
feat(retriever): activate OpenSearch k-NN driver (PR 3 of 3)
Phase 3 (#1440) gate flip. PR 1 (#1445) + PR 2a (#1481) + PR 2b (#1482)
laid the type prep + driver skeleton + read/write paths as gated dead
code; this PR wires every activation surface so opensearch becomes a
registerable VectorStore engine.
Activation wiring
- internal/types: validEngineTypes / GetVectorStoreTypes (with HNSW
bounds + knn_engine enum + Immutable hints) / retrieverEngineMapping /
buildEnvStoreForDriver — every gated surface now recognises
"opensearch". IndexConfig grows four omitempty HNSW fields (HNSWM /
HNSWEFConstruction / HNSWEFSearch / KNNEngine), keeping other engines'
serialised config byte-identical.
- internal/container: createOpenSearchEngine + the switch case in
createEngineServiceFromStore; the RETRIEVE_DRIVER=opensearch env path
in initRetrieveEngineRegistry; NewEngineFactory now closes over the
AuditLogService (the EngineFactory type itself is unchanged).
- internal/application/service/vectorstore_healthcheck.go: a
testOpenSearchConnection case so CreateStore's connectivity probe
accepts opensearch instead of returning 400.
- internal/application/repository/retriever/opensearch/transport.go:
NewOpenSearchClient is exported so the factory and env path can build
the TLS-hardened client; healthcheck.go reuses the unexported
probeVersion / probeKNNPlugin for the service-layer probe.
Service-layer validation
- validateOpenSearchIndexConfig validates the HNSW caps (m 2-100,
ef_construction 2-4096, ef_search 1-10000, knn_engine ∈ lucene|faiss).
Shards/replicas continue to be enforced by the flat ValidateIndexConfig.
Create-only: UpdateStore mutates the name only.
- validateConnectionConfig requires addr for opensearch.
Sync implementations (stubs.go shrinks)
- CopyIndices (copy.go) mirrors the Elasticsearch / Qdrant pattern —
search → BatchSave with the source_id remap for generated questions —
so dim/keyword routing and the source_id contract come from BatchSave
for free. embeddingMap is keyed by the *target* SourceID because
OpenSearch's BatchSave looks up embeddings by SourceID
(lookupEmbedding), not by chunk_id (the ES driver's convention).
Pagination is from/size; copies larger than max_result_window
(default 10000) need the scroll-based async path that lands later.
- BatchUpdateChunkEnabledStatus / BatchUpdateChunkTagID (bulk_update.go)
group the input by target value and issue one _update_by_query per
group over the cross-dim <base>_* pattern. Caller values flow through
bound script params only — never string-interpolated into the Painless
source — closing the script-injection surface.
- inspectByQueryResponse (byquery.go) mirrors inspectBulkResponse: the
full failure reason goes to the debug log only; the returned error
carries the bounded id + type.
- UpdateByQueryParams.Refresh is *bool in opensearch-go v4.6.0 (the same
shape as DeleteByQuery's quirk), so refresh=wait_for is not
expressible; we use refresh=true.
Driver-owned audit (DIP)
- A new opensearch.AuditSink interface (with nopSink + WithAuditSink
functional option) lets the driver emit opensearch.index_created and
opensearch.reindex_executed events without importing any service
package — the service layer implements the interface. NewRepository
takes opts, so existing 4-arg test call sites keep compiling unchanged.
- internal/container/audit_sink.go bridges AuditSink to AuditLogService.
When the context carries no tenant (the env-path registration ctx
during boot, for example) the adapter skips the emit with a warning
rather than silently writing tenant_id=0, which would collide with the
system-scope sentinel.
Frontend + polish
- FieldSchema (frontend/src/api/vector-store.ts) gains min/max/enum/
immutable. VectorStoreSettings.vue is now schema-driven: a closed
`enum` renders a t-select; number inputs use the schema's `:min`/`:max`
and fall back to the legacy replica-vs-shard heuristic only when the
schema does not pin them; a danger-coloured warning fires when
insecure_skip_verify is toggled on (the switch and warning are wrapped
in a vertical stack so the warning sits on its own row below the switch).
- i18n: labels for hnsw_m / hnsw_ef_construction / hnsw_ef_search /
knn_engine / insecure_skip_verify plus the warning copy in en-US,
ko-KR, zh-CN, ru-RU.
- docker-compose.dev.yml: an opensearch profile (single-node 3.3.2 with
security plugin disabled for dev only). OpenSearch Dashboards lives in a
separate, opt-in opensearch-ui profile so the heavy UI container is not
forced up alongside the cluster (the driver e2e is fully curl-verifiable
against :9200). The new docs/dev/opensearch-integration-test.md covers the
end-to-end exercise and the single-node guidance (set replicas=0 to keep
the cluster Green).
Gating-guard tests flipped
- The "OpenSearch is NOT in validEngineTypes / mapping / types list /
env builder / stubs" guard tests from PR 1 / PR 2 are replaced by
their positive counterparts in this PR. The test suite was the
activation checklist; the activation flip is its diff.
Backward compatibility
- Additive everywhere. IndexConfig's new HNSW fields are omitempty so
other engines' serialised config is byte-identical. Existing
Elasticsearch / Qdrant / Milvus / Weaviate / Doris / TencentVectorDB
stores are untouched. No migrations.
Test plan
- go build ./... clean
- go vet ./... clean
- gofmt -l clean on touched files
- go test ./... — only TestOssEnsureBucket_CreateFails (Aliyun OSS
endpoint), the docreader gRPC tests, and the doris SQL-shape tests
fail; all three are pre-existing on upstream/main and untouched by
this PR.
- New tests across internal/types, opensearch, service and container —
including a full end-to-end env-path test that exercises
initRetrieveEngineRegistry with RETRIEVE_DRIVER=opensearch against an
httptest cluster.
2026-05-28 09:01:17 +00:00
func initRetrieveEngineRegistry (
db * gorm . DB , cfg * config . Config , auditSvc interfaces . AuditLogService ,
) ( interfaces . RetrieveEngineRegistry , error ) {
2025-08-05 07:08:07 +00:00
registry := retriever . NewRetrieveEngineRegistry ( )
retrieveDriver := strings . Split ( os . Getenv ( "RETRIEVE_DRIVER" ) , "," )
log := logger . GetLogger ( context . Background ( ) )
feat(retriever): activate OpenSearch k-NN driver (PR 3 of 3)
Phase 3 (#1440) gate flip. PR 1 (#1445) + PR 2a (#1481) + PR 2b (#1482)
laid the type prep + driver skeleton + read/write paths as gated dead
code; this PR wires every activation surface so opensearch becomes a
registerable VectorStore engine.
Activation wiring
- internal/types: validEngineTypes / GetVectorStoreTypes (with HNSW
bounds + knn_engine enum + Immutable hints) / retrieverEngineMapping /
buildEnvStoreForDriver — every gated surface now recognises
"opensearch". IndexConfig grows four omitempty HNSW fields (HNSWM /
HNSWEFConstruction / HNSWEFSearch / KNNEngine), keeping other engines'
serialised config byte-identical.
- internal/container: createOpenSearchEngine + the switch case in
createEngineServiceFromStore; the RETRIEVE_DRIVER=opensearch env path
in initRetrieveEngineRegistry; NewEngineFactory now closes over the
AuditLogService (the EngineFactory type itself is unchanged).
- internal/application/service/vectorstore_healthcheck.go: a
testOpenSearchConnection case so CreateStore's connectivity probe
accepts opensearch instead of returning 400.
- internal/application/repository/retriever/opensearch/transport.go:
NewOpenSearchClient is exported so the factory and env path can build
the TLS-hardened client; healthcheck.go reuses the unexported
probeVersion / probeKNNPlugin for the service-layer probe.
Service-layer validation
- validateOpenSearchIndexConfig validates the HNSW caps (m 2-100,
ef_construction 2-4096, ef_search 1-10000, knn_engine ∈ lucene|faiss).
Shards/replicas continue to be enforced by the flat ValidateIndexConfig.
Create-only: UpdateStore mutates the name only.
- validateConnectionConfig requires addr for opensearch.
Sync implementations (stubs.go shrinks)
- CopyIndices (copy.go) mirrors the Elasticsearch / Qdrant pattern —
search → BatchSave with the source_id remap for generated questions —
so dim/keyword routing and the source_id contract come from BatchSave
for free. embeddingMap is keyed by the *target* SourceID because
OpenSearch's BatchSave looks up embeddings by SourceID
(lookupEmbedding), not by chunk_id (the ES driver's convention).
Pagination is from/size; copies larger than max_result_window
(default 10000) need the scroll-based async path that lands later.
- BatchUpdateChunkEnabledStatus / BatchUpdateChunkTagID (bulk_update.go)
group the input by target value and issue one _update_by_query per
group over the cross-dim <base>_* pattern. Caller values flow through
bound script params only — never string-interpolated into the Painless
source — closing the script-injection surface.
- inspectByQueryResponse (byquery.go) mirrors inspectBulkResponse: the
full failure reason goes to the debug log only; the returned error
carries the bounded id + type.
- UpdateByQueryParams.Refresh is *bool in opensearch-go v4.6.0 (the same
shape as DeleteByQuery's quirk), so refresh=wait_for is not
expressible; we use refresh=true.
Driver-owned audit (DIP)
- A new opensearch.AuditSink interface (with nopSink + WithAuditSink
functional option) lets the driver emit opensearch.index_created and
opensearch.reindex_executed events without importing any service
package — the service layer implements the interface. NewRepository
takes opts, so existing 4-arg test call sites keep compiling unchanged.
- internal/container/audit_sink.go bridges AuditSink to AuditLogService.
When the context carries no tenant (the env-path registration ctx
during boot, for example) the adapter skips the emit with a warning
rather than silently writing tenant_id=0, which would collide with the
system-scope sentinel.
Frontend + polish
- FieldSchema (frontend/src/api/vector-store.ts) gains min/max/enum/
immutable. VectorStoreSettings.vue is now schema-driven: a closed
`enum` renders a t-select; number inputs use the schema's `:min`/`:max`
and fall back to the legacy replica-vs-shard heuristic only when the
schema does not pin them; a danger-coloured warning fires when
insecure_skip_verify is toggled on (the switch and warning are wrapped
in a vertical stack so the warning sits on its own row below the switch).
- i18n: labels for hnsw_m / hnsw_ef_construction / hnsw_ef_search /
knn_engine / insecure_skip_verify plus the warning copy in en-US,
ko-KR, zh-CN, ru-RU.
- docker-compose.dev.yml: an opensearch profile (single-node 3.3.2 with
security plugin disabled for dev only). OpenSearch Dashboards lives in a
separate, opt-in opensearch-ui profile so the heavy UI container is not
forced up alongside the cluster (the driver e2e is fully curl-verifiable
against :9200). The new docs/dev/opensearch-integration-test.md covers the
end-to-end exercise and the single-node guidance (set replicas=0 to keep
the cluster Green).
Gating-guard tests flipped
- The "OpenSearch is NOT in validEngineTypes / mapping / types list /
env builder / stubs" guard tests from PR 1 / PR 2 are replaced by
their positive counterparts in this PR. The test suite was the
activation checklist; the activation flip is its diff.
Backward compatibility
- Additive everywhere. IndexConfig's new HNSW fields are omitempty so
other engines' serialised config is byte-identical. Existing
Elasticsearch / Qdrant / Milvus / Weaviate / Doris / TencentVectorDB
stores are untouched. No migrations.
Test plan
- go build ./... clean
- go vet ./... clean
- gofmt -l clean on touched files
- go test ./... — only TestOssEnsureBucket_CreateFails (Aliyun OSS
endpoint), the docreader gRPC tests, and the doris SQL-shape tests
fail; all three are pre-existing on upstream/main and untouched by
this PR.
- New tests across internal/types, opensearch, service and container —
including a full end-to-end env-path test that exercises
initRetrieveEngineRegistry with RETRIEVE_DRIVER=opensearch against an
httptest cluster.
2026-05-28 09:01:17 +00:00
// Audit sink for OpenSearch driver events (index created / reindex). Driver
// events fire under a tenant-scoped ctx at indexing time; the env-path
// registration ctx below has no tenant, so those emits self-skip.
auditSink := newAuditSinkAdapter ( auditSvc )
2025-08-05 07:08:07 +00:00
if slices . Contains ( retrieveDriver , "postgres" ) {
postgresRepo := postgresRepo . NewPostgresRetrieveEngineRepository ( db )
if err := registry . Register (
retriever . NewKVHybridRetrieveEngine ( postgresRepo , types . PostgresRetrieverEngineType ) ,
) ; err != nil {
log . Errorf ( "Register postgres retrieve engine failed: %v" , err )
} else {
log . Infof ( "Register postgres retrieve engine success" )
}
}
2026-02-28 05:22:07 +00:00
if slices . Contains ( retrieveDriver , "sqlite" ) {
sqliteRepo := sqliteRetrieverRepo . NewSQLiteRetrieveEngineRepository ( db )
if err := registry . Register (
retriever . NewKVHybridRetrieveEngine ( sqliteRepo , types . SQLiteRetrieverEngineType ) ,
) ; err != nil {
log . Errorf ( "Register sqlite retrieve engine failed: %v" , err )
} else {
log . Infof ( "Register sqlite retrieve engine success" )
}
}
2025-08-05 07:08:07 +00:00
if slices . Contains ( retrieveDriver , "elasticsearch_v8" ) {
client , err := elasticsearch . NewTypedClient ( elasticsearch . Config {
Addresses : [ ] string { os . Getenv ( "ELASTICSEARCH_ADDR" ) } ,
Username : os . Getenv ( "ELASTICSEARCH_USERNAME" ) ,
Password : os . Getenv ( "ELASTICSEARCH_PASSWORD" ) ,
} )
if err != nil {
log . Errorf ( "Create elasticsearch_v8 client failed: %v" , err )
} else {
2026-04-16 06:12:42 +00:00
elasticsearchRepo := elasticsearchRepoV8 . NewElasticsearchEngineRepository ( client , cfg , nil )
2025-08-05 07:08:07 +00:00
if err := registry . Register (
retriever . NewKVHybridRetrieveEngine (
elasticsearchRepo , types . ElasticsearchRetrieverEngineType ,
) ,
) ; err != nil {
log . Errorf ( "Register elasticsearch_v8 retrieve engine failed: %v" , err )
} else {
log . Infof ( "Register elasticsearch_v8 retrieve engine success" )
}
}
}
if slices . Contains ( retrieveDriver , "elasticsearch_v7" ) {
client , err := esv7 . NewClient ( esv7 . Config {
Addresses : [ ] string { os . Getenv ( "ELASTICSEARCH_ADDR" ) } ,
Username : os . Getenv ( "ELASTICSEARCH_USERNAME" ) ,
Password : os . Getenv ( "ELASTICSEARCH_PASSWORD" ) ,
} )
if err != nil {
log . Errorf ( "Create elasticsearch_v7 client failed: %v" , err )
} else {
2026-04-16 06:12:42 +00:00
elasticsearchRepo := elasticsearchRepoV7 . NewElasticsearchEngineRepository ( client , cfg , nil )
2025-08-05 07:08:07 +00:00
if err := registry . Register (
retriever . NewKVHybridRetrieveEngine (
elasticsearchRepo , types . ElasticsearchRetrieverEngineType ,
) ,
) ; err != nil {
log . Errorf ( "Register elasticsearch_v7 retrieve engine failed: %v" , err )
} else {
log . Infof ( "Register elasticsearch_v7 retrieve engine success" )
}
}
}
2025-11-26 10:58:53 +00:00
feat(retriever): activate OpenSearch k-NN driver (PR 3 of 3)
Phase 3 (#1440) gate flip. PR 1 (#1445) + PR 2a (#1481) + PR 2b (#1482)
laid the type prep + driver skeleton + read/write paths as gated dead
code; this PR wires every activation surface so opensearch becomes a
registerable VectorStore engine.
Activation wiring
- internal/types: validEngineTypes / GetVectorStoreTypes (with HNSW
bounds + knn_engine enum + Immutable hints) / retrieverEngineMapping /
buildEnvStoreForDriver — every gated surface now recognises
"opensearch". IndexConfig grows four omitempty HNSW fields (HNSWM /
HNSWEFConstruction / HNSWEFSearch / KNNEngine), keeping other engines'
serialised config byte-identical.
- internal/container: createOpenSearchEngine + the switch case in
createEngineServiceFromStore; the RETRIEVE_DRIVER=opensearch env path
in initRetrieveEngineRegistry; NewEngineFactory now closes over the
AuditLogService (the EngineFactory type itself is unchanged).
- internal/application/service/vectorstore_healthcheck.go: a
testOpenSearchConnection case so CreateStore's connectivity probe
accepts opensearch instead of returning 400.
- internal/application/repository/retriever/opensearch/transport.go:
NewOpenSearchClient is exported so the factory and env path can build
the TLS-hardened client; healthcheck.go reuses the unexported
probeVersion / probeKNNPlugin for the service-layer probe.
Service-layer validation
- validateOpenSearchIndexConfig validates the HNSW caps (m 2-100,
ef_construction 2-4096, ef_search 1-10000, knn_engine ∈ lucene|faiss).
Shards/replicas continue to be enforced by the flat ValidateIndexConfig.
Create-only: UpdateStore mutates the name only.
- validateConnectionConfig requires addr for opensearch.
Sync implementations (stubs.go shrinks)
- CopyIndices (copy.go) mirrors the Elasticsearch / Qdrant pattern —
search → BatchSave with the source_id remap for generated questions —
so dim/keyword routing and the source_id contract come from BatchSave
for free. embeddingMap is keyed by the *target* SourceID because
OpenSearch's BatchSave looks up embeddings by SourceID
(lookupEmbedding), not by chunk_id (the ES driver's convention).
Pagination is from/size; copies larger than max_result_window
(default 10000) need the scroll-based async path that lands later.
- BatchUpdateChunkEnabledStatus / BatchUpdateChunkTagID (bulk_update.go)
group the input by target value and issue one _update_by_query per
group over the cross-dim <base>_* pattern. Caller values flow through
bound script params only — never string-interpolated into the Painless
source — closing the script-injection surface.
- inspectByQueryResponse (byquery.go) mirrors inspectBulkResponse: the
full failure reason goes to the debug log only; the returned error
carries the bounded id + type.
- UpdateByQueryParams.Refresh is *bool in opensearch-go v4.6.0 (the same
shape as DeleteByQuery's quirk), so refresh=wait_for is not
expressible; we use refresh=true.
Driver-owned audit (DIP)
- A new opensearch.AuditSink interface (with nopSink + WithAuditSink
functional option) lets the driver emit opensearch.index_created and
opensearch.reindex_executed events without importing any service
package — the service layer implements the interface. NewRepository
takes opts, so existing 4-arg test call sites keep compiling unchanged.
- internal/container/audit_sink.go bridges AuditSink to AuditLogService.
When the context carries no tenant (the env-path registration ctx
during boot, for example) the adapter skips the emit with a warning
rather than silently writing tenant_id=0, which would collide with the
system-scope sentinel.
Frontend + polish
- FieldSchema (frontend/src/api/vector-store.ts) gains min/max/enum/
immutable. VectorStoreSettings.vue is now schema-driven: a closed
`enum` renders a t-select; number inputs use the schema's `:min`/`:max`
and fall back to the legacy replica-vs-shard heuristic only when the
schema does not pin them; a danger-coloured warning fires when
insecure_skip_verify is toggled on (the switch and warning are wrapped
in a vertical stack so the warning sits on its own row below the switch).
- i18n: labels for hnsw_m / hnsw_ef_construction / hnsw_ef_search /
knn_engine / insecure_skip_verify plus the warning copy in en-US,
ko-KR, zh-CN, ru-RU.
- docker-compose.dev.yml: an opensearch profile (single-node 3.3.2 with
security plugin disabled for dev only). OpenSearch Dashboards lives in a
separate, opt-in opensearch-ui profile so the heavy UI container is not
forced up alongside the cluster (the driver e2e is fully curl-verifiable
against :9200). The new docs/dev/opensearch-integration-test.md covers the
end-to-end exercise and the single-node guidance (set replicas=0 to keep
the cluster Green).
Gating-guard tests flipped
- The "OpenSearch is NOT in validEngineTypes / mapping / types list /
env builder / stubs" guard tests from PR 1 / PR 2 are replaced by
their positive counterparts in this PR. The test suite was the
activation checklist; the activation flip is its diff.
Backward compatibility
- Additive everywhere. IndexConfig's new HNSW fields are omitempty so
other engines' serialised config is byte-identical. Existing
Elasticsearch / Qdrant / Milvus / Weaviate / Doris / TencentVectorDB
stores are untouched. No migrations.
Test plan
- go build ./... clean
- go vet ./... clean
- gofmt -l clean on touched files
- go test ./... — only TestOssEnsureBucket_CreateFails (Aliyun OSS
endpoint), the docreader gRPC tests, and the doris SQL-shape tests
fail; all three are pre-existing on upstream/main and untouched by
this PR.
- New tests across internal/types, opensearch, service and container —
including a full end-to-end env-path test that exercises
initRetrieveEngineRegistry with RETRIEVE_DRIVER=opensearch against an
httptest cluster.
2026-05-28 09:01:17 +00:00
if slices . Contains ( retrieveDriver , "opensearch" ) {
cc := & types . ConnectionConfig {
Addr : os . Getenv ( "OPENSEARCH_ADDR" ) ,
Username : os . Getenv ( "OPENSEARCH_USERNAME" ) ,
Password : os . Getenv ( "OPENSEARCH_PASSWORD" ) ,
InsecureSkipVerify : strings . EqualFold ( os . Getenv ( "OPENSEARCH_INSECURE_SKIP_VERIFY" ) , "true" ) ,
}
client , err := openSearchRepo . NewOpenSearchClient ( cc )
if err != nil {
log . Errorf ( "Create opensearch client failed: %v" , err )
} else if repo , err := openSearchRepo . NewRepository (
context . Background ( ) , client , "" , nil , openSearchRepo . WithAuditSink ( auditSink ) ,
) ; err != nil {
log . Errorf ( "Create opensearch repository failed: %v" , err )
} else if err := registry . Register (
retriever . NewKVHybridRetrieveEngine ( repo , types . OpenSearchRetrieverEngineType ) ,
) ; err != nil {
log . Errorf ( "Register opensearch retrieve engine failed: %v" , err )
} else {
log . Infof ( "Register opensearch retrieve engine success" )
}
}
2025-11-26 10:58:53 +00:00
if slices . Contains ( retrieveDriver , "qdrant" ) {
qdrantHost := os . Getenv ( "QDRANT_HOST" )
if qdrantHost == "" {
qdrantHost = "localhost"
}
qdrantPort := 6334 // Default port
if portStr := os . Getenv ( "QDRANT_PORT" ) ; portStr != "" {
if port , err := strconv . Atoi ( portStr ) ; err == nil {
qdrantPort = port
}
}
// API key for authentication (optional)
qdrantAPIKey := os . Getenv ( "QDRANT_API_KEY" )
// TLS configuration (optional, defaults to false)
// Enable TLS unless explicitly set to "false" or "0" (case insensitive)
qdrantUseTLS := false
if useTLSStr := os . Getenv ( "QDRANT_USE_TLS" ) ; useTLSStr != "" {
useTLSLower := strings . ToLower ( strings . TrimSpace ( useTLSStr ) )
qdrantUseTLS = useTLSLower != "false" && useTLSLower != "0"
}
log . Infof ( "Connecting to Qdrant at %s:%d (TLS: %v)" , qdrantHost , qdrantPort , qdrantUseTLS )
client , err := qdrant . NewClient ( & qdrant . Config {
Host : qdrantHost ,
Port : qdrantPort ,
APIKey : qdrantAPIKey ,
UseTLS : qdrantUseTLS ,
} )
if err != nil {
log . Errorf ( "Create qdrant client failed: %v" , err )
} else {
2026-04-16 06:12:42 +00:00
qdrantRepository := qdrantRepo . NewQdrantRetrieveEngineRepository ( client , nil )
2025-11-26 10:58:53 +00:00
if err := registry . Register (
retriever . NewKVHybridRetrieveEngine (
qdrantRepository , types . QdrantRetrieverEngineType ,
) ,
) ; err != nil {
log . Errorf ( "Register qdrant retrieve engine failed: %v" , err )
} else {
log . Infof ( "Register qdrant retrieve engine success" )
}
}
}
2026-03-07 07:17:27 +00:00
if slices . Contains ( retrieveDriver , "weaviate" ) {
weaviateHost := os . Getenv ( "WEAVIATE_HOST" )
if weaviateHost == "" {
// Docker compose default (service name inside network)
weaviateHost = "weaviate:8080"
}
weaviateGrpcAddress := os . Getenv ( "WEAVIATE_GRPC_ADDRESS" )
if weaviateGrpcAddress == "" {
weaviateGrpcAddress = "weaviate:50051"
}
weaviateScheme := os . Getenv ( "WEAVIATE_SCHEME" )
if weaviateScheme == "" {
weaviateScheme = "http"
}
var authConfig auth . Config
if strings . EqualFold ( strings . TrimSpace ( os . Getenv ( "WEAVIATE_AUTH_ENABLED" ) ) , "true" ) {
if apiKey := strings . TrimSpace ( os . Getenv ( "WEAVIATE_API_KEY" ) ) ; apiKey != "" {
authConfig = auth . ApiKey { Value : apiKey }
}
}
weaviateClient , err := weaviate . NewClient ( weaviate . Config {
Host : weaviateHost ,
GrpcConfig : & wgrpc . Config {
Host : weaviateGrpcAddress ,
} ,
Scheme : weaviateScheme ,
AuthConfig : authConfig ,
} )
if err != nil {
log . Errorf ( "Create weaviate client failed: %v" , err )
} else {
2026-04-16 06:12:42 +00:00
weaviateRepository := weaviateRepo . NewWeaviateRetrieveEngineRepository ( weaviateClient , nil )
2026-03-07 07:17:27 +00:00
if err := registry . Register (
retriever . NewKVHybridRetrieveEngine (
weaviateRepository , types . WeaviateRetrieverEngineType ,
) ,
) ; err != nil {
log . Errorf ( "Register weaviate retrieve engine failed: %v" , err )
} else {
log . Infof ( "Register weaviate retrieve engine success" )
}
}
}
2026-02-26 13:48:38 +00:00
if slices . Contains ( retrieveDriver , "milvus" ) {
milvusCfg := milvusclient . ClientConfig {
DialOptions : [ ] grpc . DialOption { grpc . WithTimeout ( 5 * time . Second ) } ,
}
milvusAddress := os . Getenv ( "MILVUS_ADDRESS" )
if milvusAddress == "" {
milvusAddress = "localhost:19530"
}
milvusCfg . Address = milvusAddress
milvusUsername := os . Getenv ( "MILVUS_USERNAME" )
if milvusUsername != "" {
milvusCfg . Username = milvusUsername
}
milvusPassword := os . Getenv ( "MILVUS_PASSWORD" )
if milvusPassword != "" {
milvusCfg . Password = milvusPassword
}
milvusDBName := os . Getenv ( "MILVUS_DB_NAME" )
if milvusDBName != "" {
milvusCfg . DBName = milvusDBName
}
milvusCli , err := milvusclient . New ( context . Background ( ) , & milvusCfg )
if err != nil {
log . Errorf ( "Create milvus client failed: %v" , err )
} else {
2026-04-16 06:12:42 +00:00
milvusRepository := milvusRepo . NewMilvusRetrieveEngineRepository ( milvusCli , nil )
2026-02-26 13:48:38 +00:00
if err := registry . Register (
retriever . NewKVHybridRetrieveEngine (
milvusRepository , types . MilvusRetrieverEngineType ,
) ,
) ; err != nil {
log . Errorf ( "Register milvus retrieve engine failed: %v" , err )
} else {
log . Infof ( "Register milvus retrieve engine success" )
}
}
}
feat(retriever): 接入 Apache Doris 4.1 作为向量数据库
为 RetrieveEngine 体系新增 Doris 后端,与现有 Qdrant/Milvus/Weaviate
等保持完整能力对齐:向量检索、关键词检索、健康检查、环境变量与多实例
DB 配置、前端类型注册、单元测试、Docker Compose 模板。
实现要点:
- 协议分工:主链路用 MySQL 协议(database/sql + go-sql-driver/mysql)
做 DDL / 查询 / 删除;批量更新走 Stream Load HTTP API,并启用
partial_update=true、merge_type=APPEND,自动按 1MiB 切分批次并处理
307 重定向。
- 表结构:UNIQUE KEY(id) + enable_unique_key_merge_on_write=true 以
支持 upsert/部分列更新;按维度分表(<base>_<dim>),每张表上建
HNSW ANN 索引(metric_type=cosine_distance)和 INVERTED 索引
(parser=chinese)。
- 分数语义:使用 cosine_distance_approximate,再以 1 - dist 转换为
"越大越相似",与现有 KVHybridRetrieveEngine 约定一致。
- 异步索引:ANN 索引为后台构建,ensureTable 通过轮询 SHOW INDEX 等
待索引就绪后再放行写入,避免首次检索召回为空。
- ARRAY<FLOAT> 序列化:go-sql-driver/mysql 不支持数组占位符,
embeddingLiteral 将 []float32 转成 SQL 字面量字符串再拼接。
新增文件:
- internal/application/repository/retriever/doris/{structs,schema,
query,repository,streamload,repository_test}.go
- scripts/e2e-doris.sh:E2E 验证清单
- docs/wiki/集成扩展/Doris改动与上游同步.md:fork-and-rebase 工作流
与改动清单
修改文件(接线 + 文档):
- internal/types/{retriever,tenant,vectorstore}.go:新增
DorisRetrieverEngineType、env 解析、表单 schema 与索引参数校验
- internal/container/{container,engine_factory}.go:环境变量驱动
与 VectorStore 配置驱动两条路径都支持 Doris
- internal/application/service/vectorstore{,_healthcheck}.go:连接
校验 + Ping/Version 健康检查
- docker-compose.yml:新增 doris-fe / doris-be 服务(profile=doris)
- .env.example:DORIS_* 环境变量与示例
- docs/{使用其他向量数据库,wiki/集成扩展/集成向量数据库}.md:
使用说明与索引/分数行为说明
依赖:go.mod/go.sum 新增 github.com/go-sql-driver/mysql(运行时)和
github.com/DATA-DOG/go-sqlmock(测试)。
测试:repository 层 SQL 形状、Stream Load HTTP 行为、whereBuilder
逻辑、embeddingLiteral 往返、健康检查错误路径均有单测覆盖。
2026-05-07 09:58:37 +00:00
if slices . Contains ( retrieveDriver , "doris" ) {
dorisAddr := os . Getenv ( "DORIS_ADDR" )
if dorisAddr == "" {
// docker-compose 默认服务名 + Doris FE MySQL 端口
dorisAddr = "doris-fe:9030"
}
dorisDatabase := os . Getenv ( "DORIS_DATABASE" )
if dorisDatabase == "" {
dorisDatabase = "weknora"
}
dorisUsername := os . Getenv ( "DORIS_USERNAME" )
if dorisUsername == "" {
dorisUsername = "root"
}
dorisPassword := os . Getenv ( "DORIS_PASSWORD" )
dorisHTTPPort := 8030
if portStr := os . Getenv ( "DORIS_HTTP_PORT" ) ; portStr != "" {
if port , err := strconv . Atoi ( portStr ) ; err == nil {
dorisHTTPPort = port
}
}
2026-05-26 03:01:39 +00:00
dsn := fmt . Sprintf ( "%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=true&loc=Local&interpolateParams=true" ,
feat(retriever): 接入 Apache Doris 4.1 作为向量数据库
为 RetrieveEngine 体系新增 Doris 后端,与现有 Qdrant/Milvus/Weaviate
等保持完整能力对齐:向量检索、关键词检索、健康检查、环境变量与多实例
DB 配置、前端类型注册、单元测试、Docker Compose 模板。
实现要点:
- 协议分工:主链路用 MySQL 协议(database/sql + go-sql-driver/mysql)
做 DDL / 查询 / 删除;批量更新走 Stream Load HTTP API,并启用
partial_update=true、merge_type=APPEND,自动按 1MiB 切分批次并处理
307 重定向。
- 表结构:UNIQUE KEY(id) + enable_unique_key_merge_on_write=true 以
支持 upsert/部分列更新;按维度分表(<base>_<dim>),每张表上建
HNSW ANN 索引(metric_type=cosine_distance)和 INVERTED 索引
(parser=chinese)。
- 分数语义:使用 cosine_distance_approximate,再以 1 - dist 转换为
"越大越相似",与现有 KVHybridRetrieveEngine 约定一致。
- 异步索引:ANN 索引为后台构建,ensureTable 通过轮询 SHOW INDEX 等
待索引就绪后再放行写入,避免首次检索召回为空。
- ARRAY<FLOAT> 序列化:go-sql-driver/mysql 不支持数组占位符,
embeddingLiteral 将 []float32 转成 SQL 字面量字符串再拼接。
新增文件:
- internal/application/repository/retriever/doris/{structs,schema,
query,repository,streamload,repository_test}.go
- scripts/e2e-doris.sh:E2E 验证清单
- docs/wiki/集成扩展/Doris改动与上游同步.md:fork-and-rebase 工作流
与改动清单
修改文件(接线 + 文档):
- internal/types/{retriever,tenant,vectorstore}.go:新增
DorisRetrieverEngineType、env 解析、表单 schema 与索引参数校验
- internal/container/{container,engine_factory}.go:环境变量驱动
与 VectorStore 配置驱动两条路径都支持 Doris
- internal/application/service/vectorstore{,_healthcheck}.go:连接
校验 + Ping/Version 健康检查
- docker-compose.yml:新增 doris-fe / doris-be 服务(profile=doris)
- .env.example:DORIS_* 环境变量与示例
- docs/{使用其他向量数据库,wiki/集成扩展/集成向量数据库}.md:
使用说明与索引/分数行为说明
依赖:go.mod/go.sum 新增 github.com/go-sql-driver/mysql(运行时)和
github.com/DATA-DOG/go-sqlmock(测试)。
测试:repository 层 SQL 形状、Stream Load HTTP 行为、whereBuilder
逻辑、embeddingLiteral 往返、健康检查错误路径均有单测覆盖。
2026-05-07 09:58:37 +00:00
dorisUsername , dorisPassword , dorisAddr , dorisDatabase )
dorisDB , err := sql . Open ( "mysql" , dsn )
if err != nil {
log . Errorf ( "Create doris client failed: %v" , err )
} else {
dorisDB . SetMaxOpenConns ( 20 )
dorisDB . SetMaxIdleConns ( 5 )
dorisDB . SetConnMaxLifetime ( time . Hour )
httpBase := "http://" + hostFromAddr ( dorisAddr ) + ":" + strconv . Itoa ( dorisHTTPPort )
dorisRepository := dorisRepo . NewDorisRetrieveEngineRepository (
dorisDB , httpBase , dorisUsername , dorisPassword , dorisDatabase , nil ,
)
if err := registry . Register (
retriever . NewKVHybridRetrieveEngine (
dorisRepository , types . DorisRetrieverEngineType ,
) ,
) ; err != nil {
log . Errorf ( "Register doris retrieve engine failed: %v" , err )
} else {
log . Infof ( "Register doris retrieve engine success: %s db=%s" , dorisAddr , dorisDatabase )
}
}
}
2026-05-08 08:09:55 +00:00
if slices . Contains ( retrieveDriver , "tencent_vectordb" ) {
addr := os . Getenv ( "TENCENT_VECTORDB_ADDR" )
username := os . Getenv ( "TENCENT_VECTORDB_USERNAME" )
apiKey := os . Getenv ( "TENCENT_VECTORDB_API_KEY" )
if addr == "" || username == "" || apiKey == "" {
log . Errorf ( "Missing Tencent VectorDB configuration" )
} else {
client , err := tcvectordb . NewRpcClient ( addr , username , apiKey , & tcvectordb . ClientOption {
ReadConsistency : tcvectordb . EventualConsistency ,
Timeout : 10 * time . Second ,
} )
if err != nil {
log . Errorf ( "Create tencent_vectordb client failed: %v" , err )
} else {
tencentRepository := tencentVectorDBRepo . NewTencentVectorDBRetrieveEngineRepository (
client ,
os . Getenv ( "TENCENT_VECTORDB_DATABASE" ) ,
nil ,
)
if err := registry . Register (
retriever . NewKVHybridRetrieveEngine (
tencentRepository , types . TencentVectorDBRetrieverEngineType ,
) ,
) ; err != nil {
log . Errorf ( "Register tencent_vectordb retrieve engine failed: %v" , err )
} else {
log . Infof ( "Register tencent_vectordb retrieve engine success" )
}
}
}
}
2026-04-15 03:44:52 +00:00
// ─── DB store registration (byStoreID) ───
if storeReg , ok := registry . ( * retriever . RetrieveEngineRegistry ) ; ok {
feat(retriever): activate OpenSearch k-NN driver (PR 3 of 3)
Phase 3 (#1440) gate flip. PR 1 (#1445) + PR 2a (#1481) + PR 2b (#1482)
laid the type prep + driver skeleton + read/write paths as gated dead
code; this PR wires every activation surface so opensearch becomes a
registerable VectorStore engine.
Activation wiring
- internal/types: validEngineTypes / GetVectorStoreTypes (with HNSW
bounds + knn_engine enum + Immutable hints) / retrieverEngineMapping /
buildEnvStoreForDriver — every gated surface now recognises
"opensearch". IndexConfig grows four omitempty HNSW fields (HNSWM /
HNSWEFConstruction / HNSWEFSearch / KNNEngine), keeping other engines'
serialised config byte-identical.
- internal/container: createOpenSearchEngine + the switch case in
createEngineServiceFromStore; the RETRIEVE_DRIVER=opensearch env path
in initRetrieveEngineRegistry; NewEngineFactory now closes over the
AuditLogService (the EngineFactory type itself is unchanged).
- internal/application/service/vectorstore_healthcheck.go: a
testOpenSearchConnection case so CreateStore's connectivity probe
accepts opensearch instead of returning 400.
- internal/application/repository/retriever/opensearch/transport.go:
NewOpenSearchClient is exported so the factory and env path can build
the TLS-hardened client; healthcheck.go reuses the unexported
probeVersion / probeKNNPlugin for the service-layer probe.
Service-layer validation
- validateOpenSearchIndexConfig validates the HNSW caps (m 2-100,
ef_construction 2-4096, ef_search 1-10000, knn_engine ∈ lucene|faiss).
Shards/replicas continue to be enforced by the flat ValidateIndexConfig.
Create-only: UpdateStore mutates the name only.
- validateConnectionConfig requires addr for opensearch.
Sync implementations (stubs.go shrinks)
- CopyIndices (copy.go) mirrors the Elasticsearch / Qdrant pattern —
search → BatchSave with the source_id remap for generated questions —
so dim/keyword routing and the source_id contract come from BatchSave
for free. embeddingMap is keyed by the *target* SourceID because
OpenSearch's BatchSave looks up embeddings by SourceID
(lookupEmbedding), not by chunk_id (the ES driver's convention).
Pagination is from/size; copies larger than max_result_window
(default 10000) need the scroll-based async path that lands later.
- BatchUpdateChunkEnabledStatus / BatchUpdateChunkTagID (bulk_update.go)
group the input by target value and issue one _update_by_query per
group over the cross-dim <base>_* pattern. Caller values flow through
bound script params only — never string-interpolated into the Painless
source — closing the script-injection surface.
- inspectByQueryResponse (byquery.go) mirrors inspectBulkResponse: the
full failure reason goes to the debug log only; the returned error
carries the bounded id + type.
- UpdateByQueryParams.Refresh is *bool in opensearch-go v4.6.0 (the same
shape as DeleteByQuery's quirk), so refresh=wait_for is not
expressible; we use refresh=true.
Driver-owned audit (DIP)
- A new opensearch.AuditSink interface (with nopSink + WithAuditSink
functional option) lets the driver emit opensearch.index_created and
opensearch.reindex_executed events without importing any service
package — the service layer implements the interface. NewRepository
takes opts, so existing 4-arg test call sites keep compiling unchanged.
- internal/container/audit_sink.go bridges AuditSink to AuditLogService.
When the context carries no tenant (the env-path registration ctx
during boot, for example) the adapter skips the emit with a warning
rather than silently writing tenant_id=0, which would collide with the
system-scope sentinel.
Frontend + polish
- FieldSchema (frontend/src/api/vector-store.ts) gains min/max/enum/
immutable. VectorStoreSettings.vue is now schema-driven: a closed
`enum` renders a t-select; number inputs use the schema's `:min`/`:max`
and fall back to the legacy replica-vs-shard heuristic only when the
schema does not pin them; a danger-coloured warning fires when
insecure_skip_verify is toggled on (the switch and warning are wrapped
in a vertical stack so the warning sits on its own row below the switch).
- i18n: labels for hnsw_m / hnsw_ef_construction / hnsw_ef_search /
knn_engine / insecure_skip_verify plus the warning copy in en-US,
ko-KR, zh-CN, ru-RU.
- docker-compose.dev.yml: an opensearch profile (single-node 3.3.2 with
security plugin disabled for dev only). OpenSearch Dashboards lives in a
separate, opt-in opensearch-ui profile so the heavy UI container is not
forced up alongside the cluster (the driver e2e is fully curl-verifiable
against :9200). The new docs/dev/opensearch-integration-test.md covers the
end-to-end exercise and the single-node guidance (set replicas=0 to keep
the cluster Green).
Gating-guard tests flipped
- The "OpenSearch is NOT in validEngineTypes / mapping / types list /
env builder / stubs" guard tests from PR 1 / PR 2 are replaced by
their positive counterparts in this PR. The test suite was the
activation checklist; the activation flip is its diff.
Backward compatibility
- Additive everywhere. IndexConfig's new HNSW fields are omitempty so
other engines' serialised config is byte-identical. Existing
Elasticsearch / Qdrant / Milvus / Weaviate / Doris / TencentVectorDB
stores are untouched. No migrations.
Test plan
- go build ./... clean
- go vet ./... clean
- gofmt -l clean on touched files
- go test ./... — only TestOssEnsureBucket_CreateFails (Aliyun OSS
endpoint), the docreader gRPC tests, and the doris SQL-shape tests
fail; all three are pre-existing on upstream/main and untouched by
this PR.
- New tests across internal/types, opensearch, service and container —
including a full end-to-end env-path test that exercises
initRetrieveEngineRegistry with RETRIEVE_DRIVER=opensearch against an
httptest cluster.
2026-05-28 09:01:17 +00:00
loadDBStoresIntoRegistry ( storeReg , db , cfg , auditSink )
2026-04-15 03:44:52 +00:00
}
2025-08-05 07:08:07 +00:00
return registry , nil
}
2026-04-15 03:44:52 +00:00
// loadDBStoresIntoRegistry loads VectorStore records from DB and registers them
// in the registry's byStoreID map. Failures are logged and skipped (non-fatal).
feat(retriever): activate OpenSearch k-NN driver (PR 3 of 3)
Phase 3 (#1440) gate flip. PR 1 (#1445) + PR 2a (#1481) + PR 2b (#1482)
laid the type prep + driver skeleton + read/write paths as gated dead
code; this PR wires every activation surface so opensearch becomes a
registerable VectorStore engine.
Activation wiring
- internal/types: validEngineTypes / GetVectorStoreTypes (with HNSW
bounds + knn_engine enum + Immutable hints) / retrieverEngineMapping /
buildEnvStoreForDriver — every gated surface now recognises
"opensearch". IndexConfig grows four omitempty HNSW fields (HNSWM /
HNSWEFConstruction / HNSWEFSearch / KNNEngine), keeping other engines'
serialised config byte-identical.
- internal/container: createOpenSearchEngine + the switch case in
createEngineServiceFromStore; the RETRIEVE_DRIVER=opensearch env path
in initRetrieveEngineRegistry; NewEngineFactory now closes over the
AuditLogService (the EngineFactory type itself is unchanged).
- internal/application/service/vectorstore_healthcheck.go: a
testOpenSearchConnection case so CreateStore's connectivity probe
accepts opensearch instead of returning 400.
- internal/application/repository/retriever/opensearch/transport.go:
NewOpenSearchClient is exported so the factory and env path can build
the TLS-hardened client; healthcheck.go reuses the unexported
probeVersion / probeKNNPlugin for the service-layer probe.
Service-layer validation
- validateOpenSearchIndexConfig validates the HNSW caps (m 2-100,
ef_construction 2-4096, ef_search 1-10000, knn_engine ∈ lucene|faiss).
Shards/replicas continue to be enforced by the flat ValidateIndexConfig.
Create-only: UpdateStore mutates the name only.
- validateConnectionConfig requires addr for opensearch.
Sync implementations (stubs.go shrinks)
- CopyIndices (copy.go) mirrors the Elasticsearch / Qdrant pattern —
search → BatchSave with the source_id remap for generated questions —
so dim/keyword routing and the source_id contract come from BatchSave
for free. embeddingMap is keyed by the *target* SourceID because
OpenSearch's BatchSave looks up embeddings by SourceID
(lookupEmbedding), not by chunk_id (the ES driver's convention).
Pagination is from/size; copies larger than max_result_window
(default 10000) need the scroll-based async path that lands later.
- BatchUpdateChunkEnabledStatus / BatchUpdateChunkTagID (bulk_update.go)
group the input by target value and issue one _update_by_query per
group over the cross-dim <base>_* pattern. Caller values flow through
bound script params only — never string-interpolated into the Painless
source — closing the script-injection surface.
- inspectByQueryResponse (byquery.go) mirrors inspectBulkResponse: the
full failure reason goes to the debug log only; the returned error
carries the bounded id + type.
- UpdateByQueryParams.Refresh is *bool in opensearch-go v4.6.0 (the same
shape as DeleteByQuery's quirk), so refresh=wait_for is not
expressible; we use refresh=true.
Driver-owned audit (DIP)
- A new opensearch.AuditSink interface (with nopSink + WithAuditSink
functional option) lets the driver emit opensearch.index_created and
opensearch.reindex_executed events without importing any service
package — the service layer implements the interface. NewRepository
takes opts, so existing 4-arg test call sites keep compiling unchanged.
- internal/container/audit_sink.go bridges AuditSink to AuditLogService.
When the context carries no tenant (the env-path registration ctx
during boot, for example) the adapter skips the emit with a warning
rather than silently writing tenant_id=0, which would collide with the
system-scope sentinel.
Frontend + polish
- FieldSchema (frontend/src/api/vector-store.ts) gains min/max/enum/
immutable. VectorStoreSettings.vue is now schema-driven: a closed
`enum` renders a t-select; number inputs use the schema's `:min`/`:max`
and fall back to the legacy replica-vs-shard heuristic only when the
schema does not pin them; a danger-coloured warning fires when
insecure_skip_verify is toggled on (the switch and warning are wrapped
in a vertical stack so the warning sits on its own row below the switch).
- i18n: labels for hnsw_m / hnsw_ef_construction / hnsw_ef_search /
knn_engine / insecure_skip_verify plus the warning copy in en-US,
ko-KR, zh-CN, ru-RU.
- docker-compose.dev.yml: an opensearch profile (single-node 3.3.2 with
security plugin disabled for dev only). OpenSearch Dashboards lives in a
separate, opt-in opensearch-ui profile so the heavy UI container is not
forced up alongside the cluster (the driver e2e is fully curl-verifiable
against :9200). The new docs/dev/opensearch-integration-test.md covers the
end-to-end exercise and the single-node guidance (set replicas=0 to keep
the cluster Green).
Gating-guard tests flipped
- The "OpenSearch is NOT in validEngineTypes / mapping / types list /
env builder / stubs" guard tests from PR 1 / PR 2 are replaced by
their positive counterparts in this PR. The test suite was the
activation checklist; the activation flip is its diff.
Backward compatibility
- Additive everywhere. IndexConfig's new HNSW fields are omitempty so
other engines' serialised config is byte-identical. Existing
Elasticsearch / Qdrant / Milvus / Weaviate / Doris / TencentVectorDB
stores are untouched. No migrations.
Test plan
- go build ./... clean
- go vet ./... clean
- gofmt -l clean on touched files
- go test ./... — only TestOssEnsureBucket_CreateFails (Aliyun OSS
endpoint), the docreader gRPC tests, and the doris SQL-shape tests
fail; all three are pre-existing on upstream/main and untouched by
this PR.
- New tests across internal/types, opensearch, service and container —
including a full end-to-end env-path test that exercises
initRetrieveEngineRegistry with RETRIEVE_DRIVER=opensearch against an
httptest cluster.
2026-05-28 09:01:17 +00:00
func loadDBStoresIntoRegistry (
storeRegistry interfaces . StoreRegistry , db * gorm . DB , cfg * config . Config , auditSink openSearchRepo . AuditSink ,
) {
2026-04-15 03:44:52 +00:00
ctx := context . Background ( )
log := logger . GetLogger ( ctx )
var stores [ ] types . VectorStore
// GORM soft delete automatically adds "deleted_at IS NULL" condition
if err := db . Find ( & stores ) . Error ; err != nil {
log . Warnf ( "Failed to load vector stores from DB: %v" , err )
return
}
if len ( stores ) == 0 {
return
}
log . Infof ( "Loading %d vector store(s) from database" , len ( stores ) )
for _ , store := range stores {
feat(retriever): activate OpenSearch k-NN driver (PR 3 of 3)
Phase 3 (#1440) gate flip. PR 1 (#1445) + PR 2a (#1481) + PR 2b (#1482)
laid the type prep + driver skeleton + read/write paths as gated dead
code; this PR wires every activation surface so opensearch becomes a
registerable VectorStore engine.
Activation wiring
- internal/types: validEngineTypes / GetVectorStoreTypes (with HNSW
bounds + knn_engine enum + Immutable hints) / retrieverEngineMapping /
buildEnvStoreForDriver — every gated surface now recognises
"opensearch". IndexConfig grows four omitempty HNSW fields (HNSWM /
HNSWEFConstruction / HNSWEFSearch / KNNEngine), keeping other engines'
serialised config byte-identical.
- internal/container: createOpenSearchEngine + the switch case in
createEngineServiceFromStore; the RETRIEVE_DRIVER=opensearch env path
in initRetrieveEngineRegistry; NewEngineFactory now closes over the
AuditLogService (the EngineFactory type itself is unchanged).
- internal/application/service/vectorstore_healthcheck.go: a
testOpenSearchConnection case so CreateStore's connectivity probe
accepts opensearch instead of returning 400.
- internal/application/repository/retriever/opensearch/transport.go:
NewOpenSearchClient is exported so the factory and env path can build
the TLS-hardened client; healthcheck.go reuses the unexported
probeVersion / probeKNNPlugin for the service-layer probe.
Service-layer validation
- validateOpenSearchIndexConfig validates the HNSW caps (m 2-100,
ef_construction 2-4096, ef_search 1-10000, knn_engine ∈ lucene|faiss).
Shards/replicas continue to be enforced by the flat ValidateIndexConfig.
Create-only: UpdateStore mutates the name only.
- validateConnectionConfig requires addr for opensearch.
Sync implementations (stubs.go shrinks)
- CopyIndices (copy.go) mirrors the Elasticsearch / Qdrant pattern —
search → BatchSave with the source_id remap for generated questions —
so dim/keyword routing and the source_id contract come from BatchSave
for free. embeddingMap is keyed by the *target* SourceID because
OpenSearch's BatchSave looks up embeddings by SourceID
(lookupEmbedding), not by chunk_id (the ES driver's convention).
Pagination is from/size; copies larger than max_result_window
(default 10000) need the scroll-based async path that lands later.
- BatchUpdateChunkEnabledStatus / BatchUpdateChunkTagID (bulk_update.go)
group the input by target value and issue one _update_by_query per
group over the cross-dim <base>_* pattern. Caller values flow through
bound script params only — never string-interpolated into the Painless
source — closing the script-injection surface.
- inspectByQueryResponse (byquery.go) mirrors inspectBulkResponse: the
full failure reason goes to the debug log only; the returned error
carries the bounded id + type.
- UpdateByQueryParams.Refresh is *bool in opensearch-go v4.6.0 (the same
shape as DeleteByQuery's quirk), so refresh=wait_for is not
expressible; we use refresh=true.
Driver-owned audit (DIP)
- A new opensearch.AuditSink interface (with nopSink + WithAuditSink
functional option) lets the driver emit opensearch.index_created and
opensearch.reindex_executed events without importing any service
package — the service layer implements the interface. NewRepository
takes opts, so existing 4-arg test call sites keep compiling unchanged.
- internal/container/audit_sink.go bridges AuditSink to AuditLogService.
When the context carries no tenant (the env-path registration ctx
during boot, for example) the adapter skips the emit with a warning
rather than silently writing tenant_id=0, which would collide with the
system-scope sentinel.
Frontend + polish
- FieldSchema (frontend/src/api/vector-store.ts) gains min/max/enum/
immutable. VectorStoreSettings.vue is now schema-driven: a closed
`enum` renders a t-select; number inputs use the schema's `:min`/`:max`
and fall back to the legacy replica-vs-shard heuristic only when the
schema does not pin them; a danger-coloured warning fires when
insecure_skip_verify is toggled on (the switch and warning are wrapped
in a vertical stack so the warning sits on its own row below the switch).
- i18n: labels for hnsw_m / hnsw_ef_construction / hnsw_ef_search /
knn_engine / insecure_skip_verify plus the warning copy in en-US,
ko-KR, zh-CN, ru-RU.
- docker-compose.dev.yml: an opensearch profile (single-node 3.3.2 with
security plugin disabled for dev only). OpenSearch Dashboards lives in a
separate, opt-in opensearch-ui profile so the heavy UI container is not
forced up alongside the cluster (the driver e2e is fully curl-verifiable
against :9200). The new docs/dev/opensearch-integration-test.md covers the
end-to-end exercise and the single-node guidance (set replicas=0 to keep
the cluster Green).
Gating-guard tests flipped
- The "OpenSearch is NOT in validEngineTypes / mapping / types list /
env builder / stubs" guard tests from PR 1 / PR 2 are replaced by
their positive counterparts in this PR. The test suite was the
activation checklist; the activation flip is its diff.
Backward compatibility
- Additive everywhere. IndexConfig's new HNSW fields are omitempty so
other engines' serialised config is byte-identical. Existing
Elasticsearch / Qdrant / Milvus / Weaviate / Doris / TencentVectorDB
stores are untouched. No migrations.
Test plan
- go build ./... clean
- go vet ./... clean
- gofmt -l clean on touched files
- go test ./... — only TestOssEnsureBucket_CreateFails (Aliyun OSS
endpoint), the docreader gRPC tests, and the doris SQL-shape tests
fail; all three are pre-existing on upstream/main and untouched by
this PR.
- New tests across internal/types, opensearch, service and container —
including a full end-to-end env-path test that exercises
initRetrieveEngineRegistry with RETRIEVE_DRIVER=opensearch against an
httptest cluster.
2026-05-28 09:01:17 +00:00
svc , err := createEngineServiceFromStore ( ctx , store , db , cfg , auditSink )
2026-04-15 03:44:52 +00:00
if err != nil {
log . Errorf ( "Failed to create engine for store %s (%s): %v" , store . ID , store . Name , err )
continue
}
storeRegistry . RegisterWithStoreID ( store . ID , svc )
log . Infof ( "Registered DB vector store: id=%s, name=%s, engine=%s" , store . ID , store . Name , store . EngineType )
}
}
2025-08-05 07:08:07 +00:00
// initAntsPool initializes the goroutine pool
// Creates a managed goroutine pool for concurrent task execution
// Parameters:
// - cfg: Application configuration
//
// Returns:
// - Configured goroutine pool
// - Error if initialization fails
func initAntsPool ( cfg * config . Config ) ( * ants . Pool , error ) {
2025-08-16 05:13:52 +00:00
// Default to 5 if not specified in config
poolSize := os . Getenv ( "CONCURRENCY_POOL_SIZE" )
if poolSize == "" {
poolSize = "5"
}
poolSizeInt , err := strconv . Atoi ( poolSize )
if err != nil {
return nil , err
}
2025-08-05 07:08:07 +00:00
// Set up the pool with pre-allocation for better performance
2025-08-16 05:13:52 +00:00
return ants . NewPool ( poolSizeInt , ants . WithPreAlloc ( true ) )
2025-08-05 07:08:07 +00:00
}
// registerPoolCleanup registers the goroutine pool for cleanup
// Ensures proper cleanup of the goroutine pool when application shuts down
// Parameters:
// - pool: Goroutine pool
// - cleaner: Resource cleaner
func registerPoolCleanup ( pool * ants . Pool , cleaner interfaces . ResourceCleaner ) {
cleaner . RegisterWithName ( "AntsPool" , func ( ) error {
pool . Release ( )
return nil
} )
}
feat(observability): integrate Langfuse for LLM token tracking and tracing
Closes #620 #497. Add opt-in Langfuse observability covering all five
model types (chat, embedding, rerank, VLM, ASR) with HTTP-request-scoped
traces and Docker Compose support (both cloud and self-hosted).
Core package internal/tracing/langfuse:
- HTTP client with batched async ingestion (non-blocking in request path)
- Sampling, environment / release tagging, and graceful fallback when
LANGFUSE_* env vars are absent (wrappers become no-ops)
- Gin middleware opens one trace per traced request and finishes it after
the handler chain returns, attaching method / path / user / session
- Trace context is stored under a typed key exported from internal/types
so logger.CloneContext can preserve it across handler / goroutine
boundaries (otherwise each LLM call auto-created an orphan trace,
fragmenting one request into many)
Per-model generation wrappers (opt-in via NewChat/NewEmbedder/...):
- chat: captures prompt, streaming output, token usage + TTFT
- embedding: approximates tokens when the provider omits usage
- rerank: previews query/docs, summarizes results to keep payload small
- vlm: records image count and total bytes, never uploads raw pixels
- asr: records file size and audio duration, never uploads audio bytes
Async title generation (GenerateTitleAsync) now forwards the trace key
into the goroutine so title calls appear under the parent chat trace.
Docker Compose:
- LANGFUSE_* env passthrough on the `app` service for cloud deployments
- Optional `langfuse` profile spins up a self-hosted Langfuse stack that
reuses WeKnora's existing PostgreSQL (separate database via an idempotent
init container that fixes ICU collation drift) and Redis (separate DB
number), adding only ClickHouse, MinIO, web and worker containers
- web/worker entrypoints URL-encode DB_PASSWORD / REDIS_PASSWORD at start
to avoid Prisma P1013 when passwords contain @ / # / etc.
Docs: docs/Langfuse集成.md covers cloud vs self-hosted, per-model usage
strategy, code map, and resource footprint.
2026-04-23 17:57:12 +00:00
// registerLangfuseCleanup ensures buffered Langfuse events are flushed on
// shutdown. A 5-second timeout matches other external-service cleanups and
// balances data durability against a slow remote endpoint holding up exit.
func registerLangfuseCleanup ( mgr * langfuse . Manager , cleaner interfaces . ResourceCleaner ) {
if mgr == nil {
return
}
cleaner . RegisterWithName ( "Langfuse" , func ( ) error {
ctx , cancel := context . WithTimeout ( context . Background ( ) , 5 * time . Second )
defer cancel ( )
return mgr . Shutdown ( ctx )
} )
}
2026-02-28 05:22:07 +00:00
// initDocReaderClient initializes the DocumentReader client (lightweight API).
func initDocReaderClient ( cfg * config . Config ) ( interfaces . DocumentReader , error ) {
addr := strings . TrimSpace ( os . Getenv ( "DOCREADER_ADDR" ) )
transport := strings . TrimSpace ( os . Getenv ( "DOCREADER_TRANSPORT" ) )
if transport == "" {
transport = "grpc"
}
if addr == "" {
logger . Infof ( context . Background ( ) , "[DocConverter] No DOCREADER_ADDR configured, starting disconnected" )
}
transport = strings . ToLower ( transport )
switch transport {
case "http" , "https" :
if addr != "" && ! strings . HasPrefix ( addr , "http://" ) && ! strings . HasPrefix ( addr , "https://" ) {
addr = "http://" + addr
}
return docparser . NewHTTPDocumentReader ( addr )
default :
return docparser . NewGRPCDocumentReader ( addr )
}
}
2025-08-05 07:08:07 +00:00
// initOllamaService initializes the Ollama service client
// Creates a client for interacting with Ollama API for model inference
// Parameters:
// - None
//
// Returns:
// - Configured Ollama service client
// - Error if initialization fails
func initOllamaService ( ) ( * ollama . OllamaService , error ) {
// Get Ollama service from existing factory function
return ollama . GetOllamaService ( )
}
2025-09-24 04:15:17 +00:00
func initNeo4jClient ( ) ( neo4j . Driver , error ) {
2025-12-08 09:40:10 +00:00
ctx := context . Background ( )
2025-09-24 04:15:17 +00:00
if strings . ToLower ( os . Getenv ( "NEO4J_ENABLE" ) ) != "true" {
2025-12-08 09:40:10 +00:00
logger . Debugf ( ctx , "NOT SUPPORT RETRIEVE GRAPH" )
2025-09-24 04:15:17 +00:00
return nil , nil
}
uri := os . Getenv ( "NEO4J_URI" )
username := os . Getenv ( "NEO4J_USERNAME" )
password := os . Getenv ( "NEO4J_PASSWORD" )
2025-12-08 09:40:10 +00:00
// Retry configuration
maxRetries := 30 // Max retry attempts
retryInterval := 2 * time . Second // Wait between retries
var driver neo4j . Driver
var err error
for attempt := 1 ; attempt <= maxRetries ; attempt ++ {
driver , err = neo4j . NewDriver ( uri , neo4j . BasicAuth ( username , password , "" ) )
if err != nil {
logger . Warnf ( ctx , "Failed to create Neo4j driver (attempt %d/%d): %v" , attempt , maxRetries , err )
time . Sleep ( retryInterval )
continue
}
err = driver . VerifyAuthentication ( ctx , nil )
if err == nil {
if attempt > 1 {
logger . Infof ( ctx , "Successfully connected to Neo4j after %d attempts" , attempt )
}
return driver , nil
}
logger . Warnf ( ctx , "Failed to verify Neo4j authentication (attempt %d/%d): %v" , attempt , maxRetries , err )
driver . Close ( ctx )
time . Sleep ( retryInterval )
2025-09-24 04:15:17 +00:00
}
2025-12-08 09:40:10 +00:00
return nil , fmt . Errorf ( "failed to connect to Neo4j after %d attempts: %w" , maxRetries , err )
2025-09-24 04:15:17 +00:00
}
2025-12-23 08:56:30 +00:00
func NewDuckDB ( ) ( * sql . DB , error ) {
sqlDB , err := sql . Open ( "duckdb" , ":memory:" )
if err != nil {
return nil , fmt . Errorf ( "failed to open duckdb: %w" , err )
}
2026-01-05 02:15:55 +00:00
2026-06-05 08:53:09 +00:00
// Try to install and load required extensions unless explicitly disabled.
2026-04-24 11:32:51 +00:00
// - spatial: used for st_read_meta() to enumerate layer (sheet) names from .xlsx/.xls
// - excel: used for read_xlsx() which gives proper type inference per sheet
2026-06-05 08:53:09 +00:00
//
// INSTALL hits extensions.duckdb.org (public internet). In locked-down
// runtimes with no egress, set DUCKDB_SKIP_EXTENSION_LOAD=1 to avoid a
// startup hang; xlsx/xls ingest may fail later without these extensions.
if strings . EqualFold ( os . Getenv ( "DUCKDB_SKIP_EXTENSION_LOAD" ) , "true" ) ||
os . Getenv ( "DUCKDB_SKIP_EXTENSION_LOAD" ) == "1" {
logger . Infof ( context . Background ( ) ,
"[DuckDB] Skipping spatial/excel extension install/load " +
"(DUCKDB_SKIP_EXTENSION_LOAD is set; xlsx ingest may fail without them)" )
} else {
bgCtx := context . Background ( )
for _ , ext := range [ ] string { "spatial" , "excel" } {
if _ , err := sqlDB . ExecContext ( bgCtx , fmt . Sprintf ( "INSTALL %s;" , ext ) ) ; err != nil {
logger . Warnf ( bgCtx , "[DuckDB] Failed to install %s extension: %v" , ext , err )
}
if _ , err := sqlDB . ExecContext ( bgCtx , fmt . Sprintf ( "LOAD %s;" , ext ) ) ; err != nil {
logger . Warnf ( bgCtx , "[DuckDB] Failed to load %s extension: %v" , ext , err )
}
2026-04-24 11:32:51 +00:00
}
2025-12-23 08:56:30 +00:00
}
2026-01-05 02:15:55 +00:00
2025-12-23 08:56:30 +00:00
return sqlDB , nil
}
2026-01-19 12:28:31 +00:00
2026-03-31 12:14:26 +00:00
// registerWebSearchProviders registers all web search provider types to the registry.
// Each provider type is registered with its factory function that accepts parameters.
// Provider instances are created on-demand when tenants configure them.
func registerWebSearchProviders ( registry * infra_web_search . Registry ) {
registry . Register ( "duckduckgo" , infra_web_search . NewDuckDuckGoProvider )
registry . Register ( "google" , infra_web_search . NewGoogleProvider )
registry . Register ( "bing" , infra_web_search . NewBingProvider )
registry . Register ( "tavily" , infra_web_search . NewTavilyProvider )
2026-04-09 13:20:31 +00:00
registry . Register ( "ollama" , infra_web_search . NewOllamaProvider )
2026-04-12 07:58:42 +00:00
registry . Register ( "baidu" , infra_web_search . NewBaiduProvider )
2026-05-10 14:01:28 +00:00
registry . Register ( "searxng" , infra_web_search . NewSearxngProvider )
2026-01-19 12:28:31 +00:00
}
2026-03-15 10:45:53 +00:00
2026-03-15 18:23:22 +00:00
// registerIMAdapterFactories registers adapter factories for each IM platform
refactor(im): move adapter factories into per-platform subpackages
registerIMAdapterFactories in internal/container/container.go had grown
to ~290 lines of platform-specific config parsing and runtime start/stop
logic across 7 IM platforms, plus three private credential helpers. The
container package is meant to wire dependencies, not own each platform's
credentials schema and websocket lifecycle.
Extract each platform's factory into its own subpackage file and expose
the credential helpers on the im package:
- New im.ParseCredentials / im.GetString / im.GetBool (formerly the
unexported parseCredentials / getString / credentialBool in container).
- New im.ResolveMode helper collapses the six identical "default to
websocket when Mode is empty" blocks.
- New {wecom,feishu,slack,telegram,dingtalk,mattermost,wechat}.NewFactory
returns an im.AdapterFactory; container.go now calls each one in a
single line.
Behavior is preserved: adapter construction, goroutine start/stop,
log messages, default modes (mattermost still defaults to "webhook";
others to "websocket"), and error strings are unchanged. The WeCom
corp_agent_id float64/int switch and the WeChat long-poll-only path
are preserved as-is.
Net: container.go drops ~320 lines and no longer needs to be touched
when adding or tuning an IM platform.
2026-04-29 10:27:26 +00:00
// and loads enabled channels from the database. Each platform's factory lives
// in its own subpackage to keep this file focused on wiring.
2026-03-15 18:23:22 +00:00
func registerIMAdapterFactories ( imService * imPkg . Service ) {
refactor(im): move adapter factories into per-platform subpackages
registerIMAdapterFactories in internal/container/container.go had grown
to ~290 lines of platform-specific config parsing and runtime start/stop
logic across 7 IM platforms, plus three private credential helpers. The
container package is meant to wire dependencies, not own each platform's
credentials schema and websocket lifecycle.
Extract each platform's factory into its own subpackage file and expose
the credential helpers on the im package:
- New im.ParseCredentials / im.GetString / im.GetBool (formerly the
unexported parseCredentials / getString / credentialBool in container).
- New im.ResolveMode helper collapses the six identical "default to
websocket when Mode is empty" blocks.
- New {wecom,feishu,slack,telegram,dingtalk,mattermost,wechat}.NewFactory
returns an im.AdapterFactory; container.go now calls each one in a
single line.
Behavior is preserved: adapter construction, goroutine start/stop,
log messages, default modes (mattermost still defaults to "webhook";
others to "websocket"), and error strings are unchanged. The WeCom
corp_agent_id float64/int switch and the WeChat long-poll-only path
are preserved as-is.
Net: container.go drops ~320 lines and no longer needs to be touched
when adding or tuning an IM platform.
2026-04-29 10:27:26 +00:00
imService . RegisterAdapterFactory ( "wecom" , wecom . NewFactory ( ) )
imService . RegisterAdapterFactory ( "feishu" , feishu . NewFactory ( ) )
imService . RegisterAdapterFactory ( "slack" , slack . NewFactory ( ) )
imService . RegisterAdapterFactory ( "telegram" , telegram . NewFactory ( ) )
imService . RegisterAdapterFactory ( "dingtalk" , dingtalk . NewFactory ( ) )
imService . RegisterAdapterFactory ( "mattermost" , mattermost . NewFactory ( ) )
imService . RegisterAdapterFactory ( "wechat" , wechat . NewFactory ( ) )
2026-03-27 03:07:09 +00:00
2026-03-15 18:23:22 +00:00
// Load and start all enabled channels from database
if err := imService . LoadAndStartChannels ( ) ; err != nil {
refactor(im): move adapter factories into per-platform subpackages
registerIMAdapterFactories in internal/container/container.go had grown
to ~290 lines of platform-specific config parsing and runtime start/stop
logic across 7 IM platforms, plus three private credential helpers. The
container package is meant to wire dependencies, not own each platform's
credentials schema and websocket lifecycle.
Extract each platform's factory into its own subpackage file and expose
the credential helpers on the im package:
- New im.ParseCredentials / im.GetString / im.GetBool (formerly the
unexported parseCredentials / getString / credentialBool in container).
- New im.ResolveMode helper collapses the six identical "default to
websocket when Mode is empty" blocks.
- New {wecom,feishu,slack,telegram,dingtalk,mattermost,wechat}.NewFactory
returns an im.AdapterFactory; container.go now calls each one in a
single line.
Behavior is preserved: adapter construction, goroutine start/stop,
log messages, default modes (mattermost still defaults to "webhook";
others to "websocket"), and error strings are unchanged. The WeCom
corp_agent_id float64/int switch and the WeChat long-poll-only path
are preserved as-is.
Net: container.go drops ~320 lines and no longer needs to be touched
when adding or tuning an IM platform.
2026-04-29 10:27:26 +00:00
logger . Warnf ( context . Background ( ) , "[IM] Failed to load channels from database: %v" , err )
2026-03-27 03:07:09 +00:00
}
}
2026-03-27 07:02:40 +00:00
// initConnectorRegistry creates and populates the connector registry with all available connectors.
2026-04-27 08:56:30 +00:00
// Aggregates registration errors via errors.Join so a misconfigured or duplicated connector fails
// container initialization loudly instead of silently disabling the feature at runtime.
func initConnectorRegistry ( ) ( * datasource . ConnectorRegistry , error ) {
2026-03-27 07:02:40 +00:00
registry := datasource . NewConnectorRegistry ( )
2026-04-27 08:56:30 +00:00
var errs error
if err := registry . Register ( feishuConnector . NewConnector ( ) ) ; err != nil {
errs = errors . Join ( errs , fmt . Errorf ( "register feishu connector: %w" , err ) )
}
if err := registry . Register ( notionConnector . NewConnector ( ) ) ; err != nil {
errs = errors . Join ( errs , fmt . Errorf ( "register notion connector: %w" , err ) )
}
if err := registry . Register ( yuqueConnector . NewConnector ( ) ) ; err != nil {
errs = errors . Join ( errs , fmt . Errorf ( "register yuque connector: %w" , err ) )
}
2026-04-21 09:29:37 +00:00
2026-03-27 07:02:40 +00:00
// Future connectors will be registered here:
2026-04-27 08:56:30 +00:00
// if err := registry.Register(confluenceConnector.NewConnector()); err != nil { ... }
// if err := registry.Register(githubConnector.NewConnector()); err != nil { ... }
2026-03-27 07:02:40 +00:00
2026-04-27 08:56:30 +00:00
if errs != nil {
return nil , errs
}
return registry , nil
2026-03-27 07:02:40 +00:00
}
// startDataSourceScheduler starts the data source cron scheduler and registers cleanup.
func startDataSourceScheduler ( scheduler * datasource . Scheduler , cleaner interfaces . ResourceCleaner ) {
if err := scheduler . Start ( context . Background ( ) ) ; err != nil {
logger . Warnf ( context . Background ( ) , "[Container] data source scheduler start failed: %v" , err )
}
cleaner . RegisterWithName ( "DataSourceScheduler" , func ( ) error {
scheduler . Stop ( )
return nil
} )
}
feat(rbac): daily retention sweep for audit_logs (default 90 days)
The audit_logs table grows monotonically until something purges it.
PR 6 explicitly listed retention as out of scope for v1; this picks
that up.
Adds an `audit.retention_days` config (default 90, 0 disables) and a
small background goroutine `AuditLogRetentionRunner` that fires once
~10 minutes after boot and then every 24h, calling
`AuditLogService.Purge` which DELETEs rows older than the cutoff in a
single statement. The dependency surface is intentionally minimal —
no robfig/cron, no asynq, no migration — because retention has no
wall-clock alignment requirement.
Wiring is the same shape as the existing data source scheduler:
container `Provide(NewAuditLogRetentionRunner)`, an `Invoke` that
calls `Start`, and a `ResourceCleaner.RegisterWithName` for graceful
shutdown.
Defaults preserve operator intent:
- `audit:` section omitted from YAML -> retention_days=90.
- explicit `audit.retention_days: 0` in YAML -> purge disabled.
- `WEKNORA_AUDIT_RETENTION_DAYS=N` env override (incl. N=0).
- `retention_days < 0` is rejected by ValidateConfig.
Tests cover the service Purge contract (no-op when disabled, cutoff
math, error propagation) and the runner lifecycle (Start no-op when
disabled, idempotent Start/Stop, ticker cadence, runOnce swallows
errors). 10 new tests, all green.
docs/rbac.md updated with the new YAML / env / behaviour.
Refs: #1303
2026-05-15 12:10:47 +00:00
2026-05-27 05:17:08 +00:00
// startHousekeepingService starts the knowledge housekeeping cron and registers
// cleanup. This is the safety net that recovers any knowledge stuck in
// "processing" past a configurable threshold (see HousekeepingService for
// rationale). Best-effort: a startup error is logged but does NOT abort the
// container — the rest of the system stays usable.
func startHousekeepingService ( svc * service . HousekeepingService , cleaner interfaces . ResourceCleaner ) {
if svc == nil {
return
}
if err := svc . Start ( context . Background ( ) ) ; err != nil {
logger . Warnf ( context . Background ( ) , "[Container] housekeeping start failed: %v" , err )
}
cleaner . RegisterWithName ( "KnowledgeHousekeeping" , func ( ) error {
svc . Stop ( )
return nil
} )
}
feat(rbac): daily retention sweep for audit_logs (default 90 days)
The audit_logs table grows monotonically until something purges it.
PR 6 explicitly listed retention as out of scope for v1; this picks
that up.
Adds an `audit.retention_days` config (default 90, 0 disables) and a
small background goroutine `AuditLogRetentionRunner` that fires once
~10 minutes after boot and then every 24h, calling
`AuditLogService.Purge` which DELETEs rows older than the cutoff in a
single statement. The dependency surface is intentionally minimal —
no robfig/cron, no asynq, no migration — because retention has no
wall-clock alignment requirement.
Wiring is the same shape as the existing data source scheduler:
container `Provide(NewAuditLogRetentionRunner)`, an `Invoke` that
calls `Start`, and a `ResourceCleaner.RegisterWithName` for graceful
shutdown.
Defaults preserve operator intent:
- `audit:` section omitted from YAML -> retention_days=90.
- explicit `audit.retention_days: 0` in YAML -> purge disabled.
- `WEKNORA_AUDIT_RETENTION_DAYS=N` env override (incl. N=0).
- `retention_days < 0` is rejected by ValidateConfig.
Tests cover the service Purge contract (no-op when disabled, cutoff
math, error propagation) and the runner lifecycle (Start no-op when
disabled, idempotent Start/Stop, ticker cadence, runOnce swallows
errors). 10 new tests, all green.
docs/rbac.md updated with the new YAML / env / behaviour.
Refs: #1303
2026-05-15 12:10:47 +00:00
// startAuditLogRetention spins up the daily audit_logs purge sweep
// and registers shutdown cleanup. Mirrors the data-source-scheduler
// pattern: container init kicks the goroutine, ResourceCleaner stops
// it during graceful shutdown so a SIGTERM during a sweep doesn't
// orphan the goroutine.
//
// retention_days <= 0 is the configured way to disable retention;
// the runner short-circuits Start() on that path so we don't need
// to gate the wiring here.
func startAuditLogRetention (
runner * service . AuditLogRetentionRunner , cleaner interfaces . ResourceCleaner ,
) {
runner . Start ( context . Background ( ) )
cleaner . RegisterWithName ( "AuditLogRetentionRunner" , func ( ) error {
runner . Stop ( )
return nil
} )
}