From 832b5fede868f1efbafd720bad3e38d36e1b4a60 Mon Sep 17 00:00:00 2001 From: NianJiu <180004567+NianJiuZst@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:41:36 +0800 Subject: [PATCH] ci: close 6 production test gate blind spots and add Lite E2E smoke test Why: PR CI previously left six production-critical paths unverified: 1. .github/workflows/app.yml ran without PostgreSQL/ParadeDB or Redis service containers and left WEKNORA_*_POSTGRES_DSN / WEKNORA_TEST_REDIS_ADDR unset, causing all PostgreSQL migration, row-locking, pgvector, catalog, and multi-replica Redis tests to 100% t.Skip (masking a step-down regression in TestPostgresMigrationsServeAgentHistory once migrations >000106 were added). 2. app.yml invoked go vet/test without -tags sqlite_fts5, causing SQLite FTS5 retriever tests under internal/application/repository/retriever/sqlite to 100% t.Skip. 3. Desktop build-tag checks only ran ./internal/container, missing ./internal/application/service, ./cmd/desktop, and darwin/windows cross-compilation of ./internal/localsandbox/{seatbelt,winhost}, while release-lite.yml remained pinned to GO_VERSION=1.24 (go.mod requires 1.26.0). 4. The standalone client/ Go SDK module was excluded by app.yml (!client/**) and ignored by cli.yml / cli-e2e.yml / pre-push hooks despite cli/ depending on ../client (masking unformatted files and a Unix-only 0o640 permission assertion on Windows in client/). 5. High-concurrency packages (internal/stream, internal/sandbox, internal/agent, internal/im) ran without -race, and PR CI had no zero-external-dependency Lite mode end-to-end smoke test. What: - Provision paradedb/paradedb:v0.25.11-pg17 and redis:7.0-alpine services in app.yml, create isolated disposable test databases, and inject all PostgreSQL/Redis test DSNs with WEKNORA_REQUIRE_INTEGRATION=1; fix TestPostgresMigrationsServeAgentHistory to migrate down before 000106 and back up instead of stepping -1 from HEAD. - Pass -tags sqlite_fts5 across app.yml and git hooks while keeping an explicit non-FTS5 run for TestSaveWorksWhenTheFTS5ModuleIsNotCompiledIn. - Vet, test, and build ./internal/container, ./internal/application/service, and ./cmd/desktop with -tags desktop,sqlite_fts5; isolate cgo-only pg_query and gojieba bindings behind !cgo stubs so darwin/arm64 and windows/amd64 cross-compilation of ./internal/localsandbox/... runs on Linux CI; align release-lite.yml GO_VERSION to 1.26. - Watch client/** in cli.yml, cli-e2e.yml, and git pre-push hooks, running client gofmt, build, vet, and -race tests across Linux, macOS, and Windows, and fix the pre-existing gofmt drift and Windows permission assertion in client/ uncovered by the new gate. - Enable -race on internal/{stream,sandbox,agent,im}/... and add tests/lite_smoke/lite_e2e_test.go exercising a real WeKnora-lite subprocess end-to-end (auth, models, KB, Markdown upload/indexing, vector+FTS5 search, SSE RAG chat, message persistence, and SIGTERM shutdown). --- .github/workflows/app.yml | 102 ++- .github/workflows/cli-e2e.yml | 1 + .github/workflows/cli.yml | 19 + .github/workflows/release-lite.yml | 2 +- client/chunk.go | 46 +- client/download_interrupted_test.go | 9 +- client/faq.go | 38 +- client/web_search.go | 4 +- internal/database/migration_postgres_test.go | 4 +- internal/types/evaluation.go | 22 - internal/types/jieba_cgo.go | 28 + internal/types/jieba_nocgo.go | 19 + internal/utils/inject.go | 16 +- internal/utils/pg_query_cgo.go | 13 + internal/utils/pg_query_nocgo.go | 19 + scripts/git-hooks/common.sh | 23 +- scripts/git-hooks/pre-push | 4 +- scripts/test-git-hooks.sh | 4 +- tests/lite_smoke/lite_e2e_test.go | 628 +++++++++++++++++++ 19 files changed, 908 insertions(+), 93 deletions(-) create mode 100644 internal/types/jieba_cgo.go create mode 100644 internal/types/jieba_nocgo.go create mode 100644 internal/utils/pg_query_cgo.go create mode 100644 internal/utils/pg_query_nocgo.go create mode 100644 tests/lite_smoke/lite_e2e_test.go diff --git a/.github/workflows/app.yml b/.github/workflows/app.yml index f37170cd0..71efe7e90 100644 --- a/.github/workflows/app.yml +++ b/.github/workflows/app.yml @@ -19,6 +19,7 @@ on: - "migrations/**" - "skills/preloaded/**" - "testdata/**" + - "tests/**" - "website-docs/0*/**" - "website-docs/.vitepress/config.mts" - "docker/Dockerfile.app" @@ -51,6 +52,7 @@ on: - "migrations/**" - "skills/preloaded/**" - "testdata/**" + - "tests/**" - "website-docs/0*/**" - "website-docs/.vitepress/config.mts" - "docker/Dockerfile.app" @@ -89,7 +91,31 @@ jobs: verify: name: Format, vet, test, and build runs-on: ubuntu-latest - timeout-minutes: 30 + timeout-minutes: 45 + services: + postgres: + image: paradedb/paradedb:v0.25.11-pg17 + env: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: pg + POSTGRES_DB: weknora + ports: + - 5432:5432 + options: >- + --health-cmd="pg_isready -U postgres -d weknora" + --health-interval=5s + --health-timeout=5s + --health-retries=15 + --health-start-period=15s + redis: + image: redis:7.0-alpine + ports: + - 6379:6379 + options: >- + --health-cmd="redis-cli ping" + --health-interval=5s + --health-timeout=5s + --health-retries=10 steps: - uses: actions/checkout@v6 with: @@ -141,13 +167,77 @@ jobs: - name: Verify Git hook test coverage run: bash ./scripts/test-git-hooks.sh + - name: Prepare PostgreSQL test databases + shell: bash + env: + PGPASSWORD: pg + run: | + if ! command -v psql >/dev/null 2>&1; then + sudo apt-get update && sudo apt-get install -y postgresql-client + fi + for i in $(seq 1 30); do + if pg_isready -h 127.0.0.1 -p 5432 -U postgres -d weknora >/dev/null 2>&1; then + break + fi + sleep 1 + done + psql -h 127.0.0.1 -p 5432 -U postgres -d postgres -v ON_ERROR_STOP=1 <<'SQL' + CREATE DATABASE weknora_repository_test; + CREATE DATABASE weknora_memory_test; + CREATE DATABASE weknora_task_progress_test; + CREATE DATABASE weknora_retriever_test TEMPLATE template0; + SQL + psql -h 127.0.0.1 -p 5432 -U postgres -d weknora_retriever_test -v ON_ERROR_STOP=1 \ + -c "DROP EXTENSION IF EXISTS pg_search CASCADE; DROP SCHEMA IF EXISTS paradedb, pgsearch CASCADE;" + - name: Vet and test shell: bash + env: + WEKNORA_MIGRATION_TEST_POSTGRES_DSN: postgres://postgres:pg@127.0.0.1:5432/weknora?sslmode=disable + WEKNORA_REPOSITORY_TEST_POSTGRES_DSN: postgres://postgres:pg@127.0.0.1:5432/weknora_repository_test?sslmode=disable + WEKNORA_MEMORY_TEST_POSTGRES_DSN: host=127.0.0.1 port=5432 user=postgres password=pg dbname=weknora_memory_test sslmode=disable + WEKNORA_TEST_POSTGRES_DSN: host=127.0.0.1 port=5432 user=postgres password=pg dbname=weknora_task_progress_test sslmode=disable + WEKNORA_RETRIEVER_TEST_POSTGRES_DSN: postgres://postgres:pg@127.0.0.1:5432/weknora_retriever_test?sslmode=disable + WEKNORA_TEST_REDIS_ADDR: 127.0.0.1:6379 + WEKNORA_REQUIRE_INTEGRATION: "1" run: | - mapfile -t pkgs < <(go list ./... | grep -v '/docreader/') - go vet "${pkgs[@]}" - go test "${pkgs[@]}" - go test -tags desktop ./internal/container + mapfile -t all_pkgs < <(go list ./... | grep -v '/docreader/') + go vet -tags sqlite_fts5 "${all_pkgs[@]}" + + mapfile -t pkgs < <( + printf '%s\n' "${all_pkgs[@]}" | + grep -Ev '/internal/(stream|sandbox|agent|im)(/|$)|/tests/lite_smoke$' + ) + go test -tags sqlite_fts5 "${pkgs[@]}" + go test ./internal/application/repository/retriever/sqlite \ + -run '^TestSaveWorksWhenTheFTS5ModuleIsNotCompiledIn$' + + go test -race -tags sqlite_fts5 \ + ./internal/stream/... \ + ./internal/sandbox/... \ + ./internal/agent/... \ + ./internal/im/... + + - name: Desktop and cross-platform sandbox checks + shell: bash + run: | + go vet -tags "desktop,sqlite_fts5" ./internal/container ./internal/application/service ./cmd/desktop + go test -tags "desktop,sqlite_fts5" ./internal/container ./internal/application/service ./cmd/desktop + go build -tags "desktop,sqlite_fts5" -o /tmp/weknora-desktop ./cmd/desktop + rm -f /tmp/weknora-desktop + + GOOS=darwin GOARCH=arm64 CGO_ENABLED=0 go vet ./internal/localsandbox/... + GOOS=darwin GOARCH=arm64 CGO_ENABLED=0 go build ./internal/localsandbox/... + GOOS=darwin GOARCH=arm64 CGO_ENABLED=0 go test -c ./internal/localsandbox/seatbelt -o /dev/null + + GOOS=windows GOARCH=amd64 CGO_ENABLED=0 go vet ./internal/localsandbox/... + GOOS=windows GOARCH=amd64 CGO_ENABLED=0 go build ./internal/localsandbox/... + + - name: Lite mode end-to-end smoke test + run: go test -v -race -tags sqlite_fts5 -count=1 ./tests/lite_smoke/... - name: Build server - run: go build ./cmd/server + run: | + go build ./cmd/server + go build -tags sqlite_fts5 -o /tmp/weknora-lite ./cmd/server + rm -f /tmp/weknora-lite diff --git a/.github/workflows/cli-e2e.yml b/.github/workflows/cli-e2e.yml index e4602a0f2..359e0f8a8 100644 --- a/.github/workflows/cli-e2e.yml +++ b/.github/workflows/cli-e2e.yml @@ -18,6 +18,7 @@ on: types: [labeled, synchronize] paths: - 'cli/**' + - 'client/**' - '.github/workflows/cli-e2e.yml' defaults: diff --git a/.github/workflows/cli.yml b/.github/workflows/cli.yml index f154e1bc6..5ed50150e 100644 --- a/.github/workflows/cli.yml +++ b/.github/workflows/cli.yml @@ -8,11 +8,14 @@ on: branches: [main] paths: - 'cli/**' + - 'client/**' - '.github/workflows/cli.yml' pull_request: paths: - 'cli/**' + - 'client/**' - '.github/workflows/cli.yml' + workflow_dispatch: defaults: run: @@ -41,6 +44,22 @@ jobs: with: go-version: ${{ matrix.go }} cache-dependency-path: cli/go.sum + - name: Check client formatting + if: runner.os == 'Linux' + working-directory: client + run: | + unformatted=$(gofmt -l .) + if [ -n "$unformatted" ]; then + echo "The following client Go files are not gofmt-formatted:" + echo "$unformatted" + exit 1 + fi + - name: client go build, vet, and test + working-directory: client + run: | + go build ./... + go vet ./... + go test -race ./... - name: go build run: go build ./... - name: go test diff --git a/.github/workflows/release-lite.yml b/.github/workflows/release-lite.yml index 1e68a51e4..bd0eb2c0b 100644 --- a/.github/workflows/release-lite.yml +++ b/.github/workflows/release-lite.yml @@ -18,7 +18,7 @@ permissions: contents: write env: - GO_VERSION: "1.24" + GO_VERSION: "1.26" NODE_VERSION: "22" FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true" diff --git a/client/chunk.go b/client/chunk.go index 6579e7bcd..54d1e81a7 100644 --- a/client/chunk.go +++ b/client/chunk.go @@ -14,29 +14,29 @@ import ( // Chunk represents the information about a document chunk // Chunks are the basic units of storage and indexing in the knowledge base type Chunk struct { - ID string `json:"id"` // Unique identifier of the chunk - SeqID int64 `json:"seq_id"` // Auto-increment integer ID for external API usage - KnowledgeID string `json:"knowledge_id"` // Identifier of the parent knowledge - KnowledgeBaseID string `json:"knowledge_base_id"` // ID of the knowledge base - TenantID uint64 `json:"tenant_id"` // Tenant ID - TagID string `json:"tag_id"` // Optional tag ID for categorization - Content string `json:"content"` // Text content of the chunk - ChunkIndex int `json:"chunk_index"` // Index position of chunk in the document - IsEnabled bool `json:"is_enabled"` // Whether this chunk is enabled - Status int `json:"status"` // Status of the chunk - StartAt int `json:"start_at"` // Starting position in original text - EndAt int `json:"end_at"` // Ending position in original text - PreChunkID string `json:"pre_chunk_id"` // Previous chunk ID - NextChunkID string `json:"next_chunk_id"` // Next chunk ID - ChunkType string `json:"chunk_type"` // Chunk type (text, image_ocr, etc.) - ParentChunkID string `json:"parent_chunk_id"` // Parent chunk ID - RelationChunks any `json:"relation_chunks"` // Relation chunk IDs - IndirectRelationChunks any `json:"indirect_relation_chunks"` // Indirect relation chunk IDs - Metadata any `json:"metadata"` // Metadata for the chunk - ContentHash string `json:"content_hash"` // Content hash for quick matching - ImageInfo string `json:"image_info"` // Image information - CreatedAt string `json:"created_at"` // Creation time - UpdatedAt string `json:"updated_at"` // Last update time + ID string `json:"id"` // Unique identifier of the chunk + SeqID int64 `json:"seq_id"` // Auto-increment integer ID for external API usage + KnowledgeID string `json:"knowledge_id"` // Identifier of the parent knowledge + KnowledgeBaseID string `json:"knowledge_base_id"` // ID of the knowledge base + TenantID uint64 `json:"tenant_id"` // Tenant ID + TagID string `json:"tag_id"` // Optional tag ID for categorization + Content string `json:"content"` // Text content of the chunk + ChunkIndex int `json:"chunk_index"` // Index position of chunk in the document + IsEnabled bool `json:"is_enabled"` // Whether this chunk is enabled + Status int `json:"status"` // Status of the chunk + StartAt int `json:"start_at"` // Starting position in original text + EndAt int `json:"end_at"` // Ending position in original text + PreChunkID string `json:"pre_chunk_id"` // Previous chunk ID + NextChunkID string `json:"next_chunk_id"` // Next chunk ID + ChunkType string `json:"chunk_type"` // Chunk type (text, image_ocr, etc.) + ParentChunkID string `json:"parent_chunk_id"` // Parent chunk ID + RelationChunks any `json:"relation_chunks"` // Relation chunk IDs + IndirectRelationChunks any `json:"indirect_relation_chunks"` // Indirect relation chunk IDs + Metadata any `json:"metadata"` // Metadata for the chunk + ContentHash string `json:"content_hash"` // Content hash for quick matching + ImageInfo string `json:"image_info"` // Image information + CreatedAt string `json:"created_at"` // Creation time + UpdatedAt string `json:"updated_at"` // Last update time } // ChunkResponse represents the response for a single chunk diff --git a/client/download_interrupted_test.go b/client/download_interrupted_test.go index 3618b8196..387f0d947 100644 --- a/client/download_interrupted_test.go +++ b/client/download_interrupted_test.go @@ -134,12 +134,15 @@ func TestDownloadSuccessfulReplacement(t *testing.T) { if err := os.WriteFile(dest, []byte("old"), 0o640); err != nil { t.Fatal(err) } + beforeInfo, err := os.Stat(dest) + if err != nil { + t.Fatal(err) + } server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("complete")) })) defer server.Close() c := NewClient(server.URL) - var err error if batch { err = c.DownloadKnowledgeFiles(context.Background(), "kb-test", []string{"doc-test"}, dest) } else { @@ -153,8 +156,8 @@ func TestDownloadSuccessfulReplacement(t *testing.T) { t.Fatalf("download content %q: %v", got, err) } info, err := os.Stat(dest) - if err != nil || info.Mode().Perm() != 0o640 { - t.Fatalf("permissions changed: %v, %v", info, err) + if err != nil || info.Mode().Perm() != beforeInfo.Mode().Perm() { + t.Fatalf("permissions changed: got %v, want %v (%v)", info, beforeInfo.Mode().Perm(), err) } entries, err := os.ReadDir(dir) if err != nil || len(entries) != 1 { diff --git a/client/faq.go b/client/faq.go index 2d8301f72..f3934717c 100644 --- a/client/faq.go +++ b/client/faq.go @@ -401,24 +401,26 @@ type FAQSuccessEntry struct { // FAQImportProgress represents the progress of an async FAQ import task. // When Status is "completed", the result fields (SkippedCount, ImportMode, ImportedAt, DisplayStatus, ProcessingTime) are populated. type FAQImportProgress struct { - TaskID string `json:"task_id"` - KBID string `json:"kb_id"` - KnowledgeID string `json:"knowledge_id"` - Status string `json:"status"` - Progress int `json:"progress"` - Total int `json:"total"` - Processed int `json:"processed"` - SuccessCount int `json:"success_count"` - FailedCount int `json:"failed_count"` - SkippedCount int `json:"skipped_count,omitempty"` - FailedEntries []FAQFailedEntry `json:"failed_entries,omitempty"` - SuccessEntries []FAQSuccessEntry `json:"success_entries,omitempty"` // Successfully imported entries (when count is small) - FailedEntriesURL string `json:"failed_entries_url,omitempty"` // CSV download URL when too many failures - Message string `json:"message"` - Error string `json:"error,omitempty"` - CreatedAt int64 `json:"created_at"` - UpdatedAt int64 `json:"updated_at"` - DryRun bool `json:"dry_run,omitempty"` // Whether this is a dry run validation + TaskID string `json:"task_id"` + KBID string `json:"kb_id"` + KnowledgeID string `json:"knowledge_id"` + Status string `json:"status"` + Progress int `json:"progress"` + Total int `json:"total"` + Processed int `json:"processed"` + SuccessCount int `json:"success_count"` + FailedCount int `json:"failed_count"` + SkippedCount int `json:"skipped_count,omitempty"` + FailedEntries []FAQFailedEntry `json:"failed_entries,omitempty"` + // Successfully imported entries (when count is small) + SuccessEntries []FAQSuccessEntry `json:"success_entries,omitempty"` + // CSV download URL when too many failures + FailedEntriesURL string `json:"failed_entries_url,omitempty"` + Message string `json:"message"` + Error string `json:"error,omitempty"` + CreatedAt int64 `json:"created_at"` + UpdatedAt int64 `json:"updated_at"` + DryRun bool `json:"dry_run,omitempty"` // Whether this is a dry run validation // Result fields (populated when Status == "completed") ImportMode string `json:"import_mode,omitempty"` diff --git a/client/web_search.go b/client/web_search.go index 559164b2d..a4fd9a23c 100644 --- a/client/web_search.go +++ b/client/web_search.go @@ -22,8 +22,8 @@ func (c *Client) GetWebSearchProviders(ctx context.Context) ([]json.RawMessage, } var result struct { - Success bool `json:"success"` - Data []json.RawMessage `json:"data"` + Success bool `json:"success"` + Data []json.RawMessage `json:"data"` } if err := parseResponse(resp, &result); err != nil { return nil, err diff --git a/internal/database/migration_postgres_test.go b/internal/database/migration_postgres_test.go index e735f0a1e..177ba0bf2 100644 --- a/internal/database/migration_postgres_test.go +++ b/internal/database/migration_postgres_test.go @@ -49,12 +49,12 @@ func TestPostgresMigrationsServeAgentHistory(t *testing.T) { m, err := migrate.New("file://migrations/versioned", dsn) require.NoError(t, err) t.Cleanup(func() { _, _ = m.Close() }) - require.NoError(t, m.Steps(-1)) + require.NoError(t, ignoreNoChange(m.Migrate(versionedMigrationBefore(t, root, 106)))) var indexes int require.NoError(t, db.QueryRow( "SELECT count(*) FROM pg_class WHERE relname = 'idx_messages_session_created_id'").Scan(&indexes)) require.Zero(t, indexes, "the down migration drops the index") - require.NoError(t, m.Steps(1)) + require.NoError(t, RunMigrationsWithOptions(dsn, MigrationOptions{})) requirePostgresIndexValid(t, db) ctx := context.Background() diff --git a/internal/types/evaluation.go b/internal/types/evaluation.go index 1ffb04b26..33464a1e7 100644 --- a/internal/types/evaluation.go +++ b/internal/types/evaluation.go @@ -2,31 +2,9 @@ package types import ( "encoding/json" - "os" - "path/filepath" "time" - - "github.com/yanyiwu/gojieba" ) -// Jieba is a global instance of Chinese text segmentation tool -var Jieba *gojieba.Jieba = newJieba() - -func newJieba() *gojieba.Jieba { - dictDir := os.Getenv("JIEBA_DICT_DIR") - if dictDir == "" { - return gojieba.NewJieba() - } - - return gojieba.NewJieba( - filepath.Join(dictDir, "jieba.dict.utf8"), - filepath.Join(dictDir, "hmm_model.utf8"), - filepath.Join(dictDir, "user.dict.utf8"), - filepath.Join(dictDir, "idf.utf8"), - filepath.Join(dictDir, "stop_words.utf8"), - ) -} - // EvaluationStatue represents the status of an evaluation task type EvaluationStatue int diff --git a/internal/types/jieba_cgo.go b/internal/types/jieba_cgo.go new file mode 100644 index 000000000..33eac169d --- /dev/null +++ b/internal/types/jieba_cgo.go @@ -0,0 +1,28 @@ +//go:build cgo + +package types + +import ( + "os" + "path/filepath" + + "github.com/yanyiwu/gojieba" +) + +// Jieba is a global instance of Chinese text segmentation tool. +var Jieba = newJieba() + +func newJieba() *gojieba.Jieba { + dictDir := os.Getenv("JIEBA_DICT_DIR") + if dictDir == "" { + return gojieba.NewJieba() + } + + return gojieba.NewJieba( + filepath.Join(dictDir, "jieba.dict.utf8"), + filepath.Join(dictDir, "hmm_model.utf8"), + filepath.Join(dictDir, "user.dict.utf8"), + filepath.Join(dictDir, "idf.utf8"), + filepath.Join(dictDir, "stop_words.utf8"), + ) +} diff --git a/internal/types/jieba_nocgo.go b/internal/types/jieba_nocgo.go new file mode 100644 index 000000000..f822878ed --- /dev/null +++ b/internal/types/jieba_nocgo.go @@ -0,0 +1,19 @@ +//go:build !cgo + +package types + +import "strings" + +type jiebaStub struct{} + +func (*jiebaStub) Cut(s string, _ bool) []string { + return strings.Fields(s) +} + +func (*jiebaStub) CutForSearch(s string, _ bool) []string { + return strings.Fields(s) +} + +// Jieba provides a pure-Go fallback tokenizer when built with CGO_ENABLED=0 +// (e.g. cross-platform compile checks). Production builds run with cgo enabled. +var Jieba = &jiebaStub{} diff --git a/internal/utils/inject.go b/internal/utils/inject.go index ae20abe60..143653067 100644 --- a/internal/utils/inject.go +++ b/internal/utils/inject.go @@ -173,7 +173,7 @@ func ParseSQL(sql string) *SQLParseResult { } // Parse the SQL using pg_query_go - parseResult, err := pg_query.Parse(sql) + parseResult, err := parsePostgreSQL(sql) if err != nil { result.IsSelect = false result.ParseError = fmt.Sprintf("Failed to parse SQL: %v", err) @@ -733,7 +733,7 @@ func ValidateSQL(sql string, opts ...SQLValidationOption) (*SQLParseResult, *SQL } // Phase 2: Parse SQL using PostgreSQL's official parser - parseResult, err := pg_query.Parse(sql) + parseResult, err := parsePostgreSQL(sql) if err != nil { validationResult.Valid = false validationResult.Errors = append(validationResult.Errors, SQLValidationError{ @@ -923,7 +923,7 @@ func ValidateAndSecureSQL(sql string, opts ...SQLValidationOption) (string, *SQL } // Parse again to get normalized SQL - result, err := pg_query.Parse(sql) + result, err := parsePostgreSQL(sql) if err != nil { return "", validationResult, fmt.Errorf("failed to parse SQL: %v", err) } @@ -950,7 +950,7 @@ func ValidateAndSecureSQL(sql string, opts ...SQLValidationOption) (string, *SQL fragment = validator.injectHiddenKBFilter(fragment, tables) fragment = validator.injectChunkEnabledFilter(fragment, tables) fragment = validator.injectSearchScopeConditions(fragment, tables) - filters, err := pg_query.Parse(fragment) + filters, err := parsePostgreSQL(fragment) if err != nil { return fmt.Errorf("failed to build SQL security filter: %w", err) } @@ -974,7 +974,7 @@ func ValidateAndSecureSQL(sql string, opts ...SQLValidationOption) (string, *SQL if err != nil { return "", validationResult, err } - securedSQL, err := pg_query.Deparse(result) + securedSQL, err := deparsePostgreSQL(result) if err != nil { return "", validationResult, fmt.Errorf("failed to deparse secured SQL: %w", err) } @@ -1030,7 +1030,7 @@ func InjectAndConditions(sql, filter string) string { if strings.TrimSpace(filter) == "" { return sql } - parsed, err := pg_query.Parse(sql) + parsed, err := parsePostgreSQL(sql) if err != nil || len(parsed.Stmts) != 1 { return "" } @@ -1038,7 +1038,7 @@ func InjectAndConditions(sql, filter string) string { if stmt == nil || stmt.Op != pg_query.SetOperation_SETOP_NONE { return "" } - filters, err := pg_query.Parse("SELECT 1 WHERE " + filter) + filters, err := parsePostgreSQL("SELECT 1 WHERE " + filter) if err != nil || len(filters.Stmts) != 1 { return "" } @@ -1047,7 +1047,7 @@ func InjectAndConditions(sql, filter string) string { return "" } addSQLPredicate(stmt, predicate.WhereClause) - out, err := pg_query.Deparse(parsed) + out, err := deparsePostgreSQL(parsed) if err != nil { return "" } diff --git a/internal/utils/pg_query_cgo.go b/internal/utils/pg_query_cgo.go new file mode 100644 index 000000000..a55c792a4 --- /dev/null +++ b/internal/utils/pg_query_cgo.go @@ -0,0 +1,13 @@ +//go:build cgo + +package utils + +import pg_query "github.com/pganalyze/pg_query_go/v6" + +func parsePostgreSQL(sql string) (*pg_query.ParseResult, error) { + return pg_query.Parse(sql) +} + +func deparsePostgreSQL(tree *pg_query.ParseResult) (string, error) { + return pg_query.Deparse(tree) +} diff --git a/internal/utils/pg_query_nocgo.go b/internal/utils/pg_query_nocgo.go new file mode 100644 index 000000000..b7765f989 --- /dev/null +++ b/internal/utils/pg_query_nocgo.go @@ -0,0 +1,19 @@ +//go:build !cgo + +package utils + +import ( + "errors" + + pg_query "github.com/pganalyze/pg_query_go/v6" +) + +var errPGQueryRequiresCGO = errors.New("pg_query SQL parser requires cgo") + +func parsePostgreSQL(_ string) (*pg_query.ParseResult, error) { + return nil, errPGQueryRequiresCGO +} + +func deparsePostgreSQL(_ *pg_query.ParseResult) (string, error) { + return "", errPGQueryRequiresCGO +} diff --git a/scripts/git-hooks/common.sh b/scripts/git-hooks/common.sh index e5cac3ed9..e4a6f3a00 100755 --- a/scripts/git-hooks/common.sh +++ b/scripts/git-hooks/common.sh @@ -161,8 +161,8 @@ run_app_vet_test() { log_fail "no application packages found" exit 1 fi - log_step "go vet (all app packages, like CI)" - go vet "${pkgs[@]}" + log_step "go vet -tags sqlite_fts5 (all app packages, like CI)" + go vet -tags sqlite_fts5 "${pkgs[@]}" log_ok "go vet" run_go_test_packages "${pkgs[@]}" ) @@ -178,16 +178,31 @@ run_go_test_packages() { log_step "HOOK_SKIP_TEST=1; skip go test" return 0 fi - log_step "go test (${#pkgs[@]} app package(s), like CI)" + log_step "go test -tags sqlite_fts5 (${#pkgs[@]} app package(s), like CI)" ( cd "$ROOT" # Match app.yml: a developer's custom log template must not alter assertions. - WEKNORA_LOG_FORMAT="" go test -count=1 "${pkgs[@]}" + WEKNORA_LOG_FORMAT="" go test -tags sqlite_fts5 -count=1 "${pkgs[@]}" ) log_ok "go test" } +run_client_checks() { + log_step "client: go vet && go test -race" + ( + cd "$ROOT/client" + go vet ./... + if [[ "${HOOK_SKIP_TEST:-}" == "1" ]]; then + log_step "HOOK_SKIP_TEST=1; skip client go test" + else + go test -race -count=1 ./... + fi + ) + log_ok "client checks" +} + run_cli_checks() { + run_client_checks log_step "cli: go vet && go test" ( cd "$ROOT/cli" diff --git a/scripts/git-hooks/pre-push b/scripts/git-hooks/pre-push index 1a7c70bd6..fa3268db2 100755 --- a/scripts/git-hooks/pre-push +++ b/scripts/git-hooks/pre-push @@ -55,7 +55,7 @@ while read -r _local_ref local_sha remote_ref remote_sha; do pr_changed_go=() while IFS= read -r line; do [[ -n "$line" ]] && pr_changed_go+=("$line") - done < <(git diff --name-only --diff-filter=ACMR "$pr_diff" -- '*.go' ':!cli/**' || true) + done < <(git diff --name-only --diff-filter=ACMR "$pr_diff" -- '*.go' ':!cli/**' ':!client/**' || true) if [[ ${#pr_changed_go[@]} -gt 0 ]]; then go_files=() @@ -73,7 +73,7 @@ while read -r _local_ref local_sha remote_ref remote_sha; do log_ok "go build ./cmd/server" fi - if paths_match_prefix "cli/" "${pr_changed[@]}"; then + if paths_match_prefix "cli/" "${pr_changed[@]}" || paths_match_prefix "client/" "${pr_changed[@]}"; then run_cli_checks fi if paths_match_prefix "frontend/" "${pr_changed[@]}"; then diff --git a/scripts/test-git-hooks.sh b/scripts/test-git-hooks.sh index 95e6049ab..5b716be44 100644 --- a/scripts/test-git-hooks.sh +++ b/scripts/test-git-hooks.sh @@ -40,8 +40,8 @@ run_checks() { run_checks cat > "$fixture/expected.log" <<'EOF' list ./... -vet example/internal/agent/tools example/internal/application/service -test -count=1 example/internal/agent/tools example/internal/application/service +vet -tags sqlite_fts5 example/internal/agent/tools example/internal/application/service +test -tags sqlite_fts5 -count=1 example/internal/agent/tools example/internal/application/service EOF diff -u "$fixture/expected.log" "$HOOK_TEST_LOG" diff --git a/tests/lite_smoke/lite_e2e_test.go b/tests/lite_smoke/lite_e2e_test.go new file mode 100644 index 000000000..00f027eda --- /dev/null +++ b/tests/lite_smoke/lite_e2e_test.go @@ -0,0 +1,628 @@ +package lite_smoke_test + +import ( + "bufio" + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "mime/multipart" + "net" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "strconv" + "strings" + "syscall" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +const embeddingDims = 8 + +// TestLiteEditionEndToEndSmoke boots a real compiled WeKnora-lite server +// subprocess (SQLite + sqlite-vec + FTS5 + local storage + in-memory stream +// manager, zero external services) and exercises the full user journey: +// health/system info -> register & login -> model creation -> KB creation -> +// Markdown upload & async indexing -> hybrid vector/FTS5 search -> streaming +// RAG chat over SSE -> persisted message history -> graceful SIGTERM shutdown. +func TestLiteEditionEndToEndSmoke(t *testing.T) { + repoRoot := findRepoRoot(t) + llmSrv := startLoopbackOpenAIServer(t) + + workDir := t.TempDir() + require.NoError(t, os.Symlink(filepath.Join(repoRoot, "config"), filepath.Join(workDir, "config"))) + require.NoError(t, os.Symlink(filepath.Join(repoRoot, "migrations"), filepath.Join(workDir, "migrations"))) + + binPath := filepath.Join(workDir, "WeKnora-lite") + if runtime.GOOS == "windows" { + binPath += ".exe" + } + ldflags := strings.Join([]string{ + "-X github.com/Tencent/WeKnora/internal/handler.Edition=lite", + "-X google.golang.org/protobuf/reflect/protoregistry.conflictPolicy=warn", + }, " ") + buildCmd := exec.Command( + "go", "build", + "-tags", "sqlite_fts5", + "-ldflags", ldflags, + "-o", binPath, + "./cmd/server", + ) + buildCmd.Dir = repoRoot + buildCmd.Env = append(os.Environ(), + "CGO_ENABLED=1", + "CGO_CFLAGS=-Wno-deprecated-declarations", + ) + buildOut, err := buildCmd.CombinedOutput() + require.NoErrorf(t, err, "build WeKnora-lite failed:\n%s", string(buildOut)) + + port := allocateFreePort(t) + baseURL := fmt.Sprintf("http://127.0.0.1:%d", port) + + var serverLogs bytes.Buffer + srvCmd := exec.Command(binPath) + srvCmd.Dir = workDir + srvCmd.Stdout = &serverLogs + srvCmd.Stderr = &serverLogs + srvCmd.Env = append(os.Environ(), + "GIN_MODE=debug", + "LOG_LEVEL=info", + "SERVER_HOST=127.0.0.1", + "SERVER_PORT="+strconv.Itoa(port), + "DB_DRIVER=sqlite", + "DB_PATH="+filepath.Join(workDir, "data", "weknora.db"), + "RETRIEVE_DRIVER=sqlite", + "STORAGE_TYPE=local", + "LOCAL_STORAGE_BASE_DIR="+filepath.Join(workDir, "data", "files"), + "STREAM_MANAGER_TYPE=memory", + "JWT_SECRET=lite-smoke-jwt-secret-at-least-32-bytes!!", + "SYSTEM_AES_KEY=0123456789abcdef0123456789abcdef", + "NEO4J_ENABLE=false", + "WEKNORA_SANDBOX_MODE=disabled", + "ENABLE_GRAPH_RAG=false", + "DISABLE_REGISTRATION=false", + "SSRF_WHITELIST=127.0.0.1,localhost", + "CONCURRENCY_POOL_SIZE=2", + ) + require.NoError(t, srvCmd.Start()) + + exited := make(chan error, 1) + go func() { + exited <- srvCmd.Wait() + }() + t.Cleanup(func() { + if srvCmd.Process == nil { + return + } + _ = srvCmd.Process.Signal(syscall.SIGTERM) + select { + case <-exited: + case <-time.After(10 * time.Second): + _ = srvCmd.Process.Kill() + <-exited + } + if t.Failed() { + t.Logf("WeKnora-lite server logs:\n%s", serverLogs.String()) + } + }) + + client := &http.Client{Timeout: 30 * time.Second} + waitForHealth(t, client, baseURL, exited, &serverLogs) + + // 1. Register + login user and verify Lite edition metadata. + const ( + email = "smoke@example.com" + password = "SmokeTestPassword!2026" + ) + doJSON(t, client, http.MethodPost, baseURL+"/api/v1/auth/register", "", map[string]any{ + "username": "smoke-admin", + "email": email, + "password": password, + }, http.StatusCreated, nil) + + var loginResp struct { + Success bool `json:"success"` + Token string `json:"token"` + ActiveTenant *struct { + ID uint64 `json:"id"` + } `json:"active_tenant"` + } + doJSON(t, client, http.MethodPost, baseURL+"/api/v1/auth/login", "", map[string]any{ + "email": email, + "password": password, + }, http.StatusOK, &loginResp) + require.True(t, loginResp.Success) + require.NotEmpty(t, loginResp.Token) + require.NotNil(t, loginResp.ActiveTenant) + require.NotZero(t, loginResp.ActiveTenant.ID) + token := loginResp.Token + + var sysInfo struct { + Success bool `json:"success"` + Data struct { + Edition string `json:"edition"` + } `json:"data"` + } + doJSON(t, client, http.MethodGet, baseURL+"/api/v1/system/info", token, nil, http.StatusOK, &sysInfo) + require.Equal(t, "lite", sysInfo.Data.Edition) + + // 2. Register loopback OpenAI-compatible Embedding and KnowledgeQA models. + embedModelID := createModel(t, client, baseURL, token, map[string]any{ + "name": "smoke-embed-v1", + "display_name": "Smoke Embedding", + "type": "Embedding", + "source": "remote", + "parameters": map[string]any{ + "provider": "openai", + "base_url": llmSrv.URL + "/v1", + "api_key": "sk-smoke-local", + "interfaces": []string{"embeddings"}, + "embedding_parameters": map[string]any{ + "dimension": embeddingDims, + }, + }, + }) + + chatModelID := createModel(t, client, baseURL, token, map[string]any{ + "name": "smoke-chat-v1", + "display_name": "Smoke Chat", + "type": "KnowledgeQA", + "source": "remote", + "parameters": map[string]any{ + "provider": "openai", + "base_url": llmSrv.URL + "/v1", + "api_key": "sk-smoke-local", + "interfaces": []string{"chat"}, + }, + }) + + // 3. Create Knowledge Base bound to both models. + var kbResp struct { + Success bool `json:"success"` + Data struct { + ID string `json:"id"` + } `json:"data"` + } + doJSON(t, client, http.MethodPost, baseURL+"/api/v1/knowledge-bases", token, map[string]any{ + "name": "Lite Smoke KB", + "description": "End-to-end Lite smoke verification", + "embedding_model_id": embedModelID, + "summary_model_id": chatModelID, + "chunking_config": map[string]any{ + "chunk_size": 300, + "chunk_overlap": 30, + "separators": []string{"\n\n", "\n"}, + }, + }, http.StatusCreated, &kbResp) + kbID := kbResp.Data.ID + require.NotEmpty(t, kbID) + + // 4. Upload a Markdown document containing both English & CJK tokens so + // both sqlite-vec vector search and FTS5 bigram keyword search are exercised. + docContent := strings.Join([]string{ + "# Aurora Borealis Deployment Guide", + "", + "Codename **Helios-7492** configures the zero-dependency Lite retrieval engine.", + "离线单二进制架构内置 SQLite 向量检索与 FTS5 双字分词全文索引,无需外部容器依赖。", + }, "\n") + knowledgeID := uploadMarkdownDocument(t, client, baseURL, token, kbID, "helios-guide.md", docContent) + waitKnowledgeIndexed(t, client, baseURL, token, knowledgeID, 45*time.Second) + + // 5. Verify hybrid search finds the indexed chunk for both English and CJK queries. + rerankOff := false + for _, query := range []string{"Helios-7492", "双字分词全文索引"} { + var searchResp struct { + Success bool `json:"success"` + Data []struct { + ID string `json:"id"` + Content string `json:"content"` + } `json:"data"` + } + doJSON(t, client, http.MethodPost, baseURL+"/api/v1/knowledge-search", token, map[string]any{ + "query": query, + "knowledge_base_ids": []string{kbID}, + "rerank": map[string]any{"enabled": rerankOff}, + }, http.StatusOK, &searchResp) + require.True(t, searchResp.Success, "search query=%q", query) + require.NotEmpty(t, searchResp.Data, "expected indexed chunk for query=%q", query) + require.Contains(t, searchResp.Data[0].Content, "Helios-7492") + } + + // 6. Create conversation session and stream a full RAG answer via SSE. + var sessResp struct { + Success bool `json:"success"` + Data struct { + ID string `json:"id"` + } `json:"data"` + } + doJSON(t, client, http.MethodPost, baseURL+"/api/v1/sessions", token, map[string]any{ + "title": "Lite Smoke Session", + }, http.StatusCreated, &sessResp) + sessionID := sessResp.Data.ID + require.NotEmpty(t, sessionID) + + answer := streamKnowledgeQA(t, client, baseURL, token, sessionID, map[string]any{ + "query": "What codename configures the Lite retrieval engine?", + "knowledge_base_ids": []string{kbID}, + "summary_model_id": chatModelID, + "disable_title": true, + }) + require.Contains(t, answer, "Helios-7492") + + // 7. Verify assistant reply was persisted to SQLite message history. + var msgResp struct { + Success bool `json:"success"` + Data []struct { + Role string `json:"role"` + Content string `json:"content"` + IsCompleted bool `json:"is_completed"` + } `json:"data"` + } + messagesURL := baseURL + "/api/v1/messages/" + sessionID + "/load?limit=10" + doJSON(t, client, http.MethodGet, messagesURL, token, nil, http.StatusOK, &msgResp) + require.GreaterOrEqual(t, len(msgResp.Data), 2, "expected user + assistant messages persisted") + + // 8. Graceful shutdown on SIGTERM must exit cleanly (code 0). + require.NoError(t, srvCmd.Process.Signal(syscall.SIGTERM)) + select { + case waitErr := <-exited: + require.NoErrorf(t, waitErr, "WeKnora-lite did not exit cleanly on SIGTERM:\n%s", serverLogs.String()) + srvCmd.Process = nil + case <-time.After(15 * time.Second): + t.Fatalf("timed out waiting for WeKnora-lite graceful shutdown:\n%s", serverLogs.String()) + } +} + +func startLoopbackOpenAIServer(t *testing.T) *httptest.Server { + t.Helper() + mux := http.NewServeMux() + + mux.HandleFunc("/v1/embeddings", func(w http.ResponseWriter, r *http.Request) { + var req struct { + Model string `json:"model"` + Input any `json:"input"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + var inputs []string + switch v := req.Input.(type) { + case string: + inputs = []string{v} + case []any: + for _, item := range v { + inputs = append(inputs, fmt.Sprint(item)) + } + default: + inputs = []string{fmt.Sprint(v)} + } + + type embItem struct { + Object string `json:"object"` + Index int `json:"index"` + Embedding []float32 `json:"embedding"` + } + data := make([]embItem, len(inputs)) + for i, text := range inputs { + data[i] = embItem{ + Object: "embedding", + Index: i, + Embedding: deterministicEmbedding(text), + } + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "object": "list", + "model": req.Model, + "data": data, + "usage": map[string]int{"prompt_tokens": 8, "total_tokens": 8}, + }) + }) + + mux.HandleFunc("/v1/chat/completions", func(w http.ResponseWriter, r *http.Request) { + var req struct { + Model string `json:"model"` + Stream bool `json:"stream"` + Messages []struct { + Role string `json:"role"` + Content any `json:"content"` + } `json:"messages"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + reply := "Helios-7492 configures the zero-dependency WeKnora Lite retrieval engine." + for _, m := range req.Messages { + text := fmt.Sprint(m.Content) + if strings.Contains(text, "rewrite") || strings.Contains(text, "改写") { + reply = "What codename configures Helios-7492?" + } + } + + if !req.Stream { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "id": "chatcmpl-smoke", + "object": "chat.completion", + "created": time.Now().Unix(), + "model": req.Model, + "choices": []map[string]any{{ + "index": 0, + "finish_reason": "stop", + "message": map[string]string{"role": "assistant", "content": reply}, + }}, + }) + return + } + + w.Header().Set("Content-Type", "text/event-stream") + w.Header().Set("Cache-Control", "no-cache") + flusher, _ := w.(http.Flusher) + for _, part := range []string{"Helios-7492 ", "configures WeKnora Lite."} { + chunk, _ := json.Marshal(map[string]any{ + "id": "chatcmpl-smoke", + "object": "chat.completion.chunk", + "created": time.Now().Unix(), + "model": req.Model, + "choices": []map[string]any{{ + "index": 0, + "delta": map[string]string{"content": part}, + }}, + }) + _, _ = fmt.Fprintf(w, "data: %s\n\n", chunk) + if flusher != nil { + flusher.Flush() + } + } + doneChunk, _ := json.Marshal(map[string]any{ + "id": "chatcmpl-smoke", + "object": "chat.completion.chunk", + "created": time.Now().Unix(), + "model": req.Model, + "choices": []map[string]any{{ + "index": 0, + "delta": map[string]string{}, + "finish_reason": "stop", + }}, + }) + _, _ = fmt.Fprintf(w, "data: %s\n\ndata: [DONE]\n\n", doneChunk) + if flusher != nil { + flusher.Flush() + } + }) + + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + return srv +} + +func deterministicEmbedding(text string) []float32 { + vec := make([]float32, embeddingDims) + vec[0] = 0.75 + lower := strings.ToLower(text) + if strings.Contains(lower, "helios") || strings.Contains(lower, "lite") { + vec[1] = 0.65 + } + if strings.Contains(text, "双字") || strings.Contains(text, "索引") { + vec[2] = 0.65 + } + return vec +} + +func findRepoRoot(t *testing.T) string { + t.Helper() + dir, err := os.Getwd() + require.NoError(t, err) + for { + if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil { + return dir + } + parent := filepath.Dir(dir) + require.NotEqual(t, dir, parent, "could not locate repository root") + dir = parent + } +} + +func allocateFreePort(t *testing.T) int { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + defer func() { _ = ln.Close() }() + return ln.Addr().(*net.TCPAddr).Port +} + +func waitForHealth(t *testing.T, client *http.Client, baseURL string, exited <-chan error, logs *bytes.Buffer) { + t.Helper() + deadline := time.Now().Add(30 * time.Second) + for time.Now().Before(deadline) { + select { + case err := <-exited: + t.Fatalf("WeKnora-lite exited before becoming healthy (%v):\n%s", err, logs.String()) + default: + } + resp, err := client.Get(baseURL + "/health") + if err == nil { + _ = resp.Body.Close() + if resp.StatusCode == http.StatusOK { + return + } + } + time.Sleep(150 * time.Millisecond) + } + t.Fatalf("WeKnora-lite health check timed out:\n%s", logs.String()) +} + +func createModel(t *testing.T, client *http.Client, baseURL, token string, payload map[string]any) string { + t.Helper() + var resp struct { + Success bool `json:"success"` + Data struct { + ID string `json:"id"` + } `json:"data"` + } + doJSON(t, client, http.MethodPost, baseURL+"/api/v1/models", token, payload, http.StatusCreated, &resp) + require.True(t, resp.Success) + require.NotEmpty(t, resp.Data.ID) + return resp.Data.ID +} + +func uploadMarkdownDocument( + t *testing.T, client *http.Client, baseURL, token, kbID, filename, content string, +) string { + t.Helper() + var body bytes.Buffer + mw := multipart.NewWriter(&body) + part, err := mw.CreateFormFile("file", filename) + require.NoError(t, err) + _, err = io.WriteString(part, content) + require.NoError(t, err) + require.NoError(t, mw.Close()) + + req, err := http.NewRequestWithContext( + context.Background(), + http.MethodPost, + fmt.Sprintf("%s/api/v1/knowledge-bases/%s/knowledge/file", baseURL, kbID), + &body, + ) + require.NoError(t, err) + req.Header.Set("Authorization", "Bearer "+token) + req.Header.Set("Content-Type", mw.FormDataContentType()) + + resp, err := client.Do(req) + require.NoError(t, err) + defer func() { _ = resp.Body.Close() }() + raw, err := io.ReadAll(resp.Body) + require.NoError(t, err) + require.Equalf(t, http.StatusOK, resp.StatusCode, "upload document status=%d body=%s", resp.StatusCode, string(raw)) + + var out struct { + Success bool `json:"success"` + Data struct { + ID string `json:"id"` + } `json:"data"` + } + require.NoError(t, json.Unmarshal(raw, &out)) + require.NotEmpty(t, out.Data.ID) + return out.Data.ID +} + +func waitKnowledgeIndexed( + t *testing.T, client *http.Client, baseURL, token, knowledgeID string, timeout time.Duration, +) { + t.Helper() + deadline := time.Now().Add(timeout) + for time.Now().Before(deadline) { + var resp struct { + Success bool `json:"success"` + Data struct { + ParseStatus string `json:"parse_status"` + ErrorMessage string `json:"error_message"` + } `json:"data"` + } + doJSON(t, client, http.MethodGet, baseURL+"/api/v1/knowledge/"+knowledgeID, token, nil, http.StatusOK, &resp) + switch resp.Data.ParseStatus { + case "completed": + return + case "failed": + t.Fatalf("document indexing failed: %s", resp.Data.ErrorMessage) + } + time.Sleep(200 * time.Millisecond) + } + t.Fatalf("timed out waiting for knowledge %s to finish indexing", knowledgeID) +} + +func streamKnowledgeQA( + t *testing.T, client *http.Client, baseURL, token, sessionID string, payload map[string]any, +) string { + t.Helper() + rawBody, err := json.Marshal(payload) + require.NoError(t, err) + + req, err := http.NewRequestWithContext( + context.Background(), + http.MethodPost, + fmt.Sprintf("%s/api/v1/knowledge-chat/%s", baseURL, sessionID), + bytes.NewReader(rawBody), + ) + require.NoError(t, err) + req.Header.Set("Authorization", "Bearer "+token) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "text/event-stream") + + resp, err := client.Do(req) + require.NoError(t, err) + defer func() { _ = resp.Body.Close() }() + if resp.StatusCode != http.StatusOK { + body, _ := io.ReadAll(resp.Body) + t.Fatalf("knowledge-chat status=%d body=%s", resp.StatusCode, string(body)) + } + + var answer strings.Builder + scanner := bufio.NewScanner(resp.Body) + scanner.Buffer(make([]byte, 0, 64*1024), 2*1024*1024) + for scanner.Scan() { + line := strings.TrimSpace(scanner.Text()) + if !strings.HasPrefix(line, "data:") { + continue + } + data := strings.TrimSpace(strings.TrimPrefix(line, "data:")) + if data == "" || data == "[DONE]" { + continue + } + var ev struct { + ResponseType string `json:"response_type"` + Content string `json:"content"` + } + require.NoErrorf(t, json.Unmarshal([]byte(data), &ev), "parse SSE payload: %s", data) + if ev.ResponseType == "error" { + t.Fatalf("SSE stream returned error event: %s", ev.Content) + } + if ev.ResponseType == "answer" { + answer.WriteString(ev.Content) + } + } + require.NoError(t, scanner.Err()) + return answer.String() +} + +func doJSON( + t *testing.T, client *http.Client, method, url, token string, body any, wantStatus int, out any, +) { + t.Helper() + var reader io.Reader + if body != nil { + raw, err := json.Marshal(body) + require.NoError(t, err) + reader = bytes.NewReader(raw) + } + req, err := http.NewRequestWithContext(context.Background(), method, url, reader) + require.NoError(t, err) + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + resp, err := client.Do(req) + require.NoError(t, err) + defer func() { _ = resp.Body.Close() }() + respBytes, err := io.ReadAll(resp.Body) + require.NoError(t, err) + require.Equalf( + t, wantStatus, resp.StatusCode, + "%s %s returned %d: %s", method, url, resp.StatusCode, string(respBytes), + ) + if out != nil { + require.NoErrorf(t, json.Unmarshal(respBytes, out), "decode %s %s: %s", method, url, string(respBytes)) + } +}