chore: 初始化仓库,导入项目基线代码
Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、 Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。 今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
commit
7ec21f35b0
5767 files changed
+1436788
No files matched your search
@@ -0,0 +1,222 @@
|
||||
package sqlite
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"academy/internal/logger"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// BatchUpdateChunkEnabledStatus / BatchUpdateChunkTagID only touch the index
|
||||
// copy (lite_embeddings) that retrieval reads, while the authoritative chunks
|
||||
// row is written by the service layer beforehand. Swallowing an UPDATE error
|
||||
// therefore makes the call look successful while retrieval keeps filtering on
|
||||
// the stale is_enabled / tag_id value, so the error has to reach the caller.
|
||||
|
||||
func TestBatchUpdateChunkEnabledStatusReturnsUpdateError(t *testing.T) {
|
||||
repository := newSQLiteRetrieverTestRepository(t)
|
||||
saveSQLiteTestVector(t, repository,
|
||||
sqliteTestIndex("chunk-1", "kb-1", "knowledge-1", "tag-1", true),
|
||||
[]float32{1, 0},
|
||||
)
|
||||
require.NoError(t, repository.db.Exec("DROP TABLE lite_embeddings").Error)
|
||||
|
||||
err := repository.BatchUpdateChunkEnabledStatus(context.Background(), map[string]bool{"chunk-1": false})
|
||||
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "chunk-1")
|
||||
assert.Contains(t, err.Error(), "is_enabled")
|
||||
}
|
||||
|
||||
func TestBatchUpdateChunkTagIDReturnsUpdateError(t *testing.T) {
|
||||
repository := newSQLiteRetrieverTestRepository(t)
|
||||
saveSQLiteTestVector(t, repository,
|
||||
sqliteTestIndex("chunk-1", "kb-1", "knowledge-1", "tag-1", true),
|
||||
[]float32{1, 0},
|
||||
)
|
||||
require.NoError(t, repository.db.Exec("DROP TABLE lite_embeddings").Error)
|
||||
|
||||
err := repository.BatchUpdateChunkTagID(context.Background(), map[string]string{"chunk-1": "tag-2"})
|
||||
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "chunk-1")
|
||||
assert.Contains(t, err.Error(), "tag_id")
|
||||
}
|
||||
|
||||
// A statement that fails inside a batch must not be masked by the remaining
|
||||
// statements of the same batch.
|
||||
func TestBatchUpdateChunkTagIDReportsFailingStatementInBatch(t *testing.T) {
|
||||
repository := newSQLiteRetrieverTestRepository(t)
|
||||
for _, chunkID := range []string{"chunk-ok", "chunk-fail"} {
|
||||
saveSQLiteTestVector(t, repository,
|
||||
sqliteTestIndex(chunkID, "kb-1", "knowledge-1", "tag-1", true),
|
||||
[]float32{1, 0},
|
||||
)
|
||||
}
|
||||
require.NoError(t, repository.db.Exec(`CREATE TRIGGER fail_chunk_tag_update
|
||||
BEFORE UPDATE ON lite_embeddings
|
||||
WHEN OLD.chunk_id = 'chunk-fail'
|
||||
BEGIN SELECT RAISE(ABORT, 'simulated index write failure'); END`).Error)
|
||||
|
||||
err := repository.BatchUpdateChunkTagID(context.Background(), map[string]string{
|
||||
"chunk-ok": "tag-2",
|
||||
"chunk-fail": "tag-2",
|
||||
})
|
||||
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "chunk-fail")
|
||||
assert.Contains(t, err.Error(), "simulated index write failure")
|
||||
}
|
||||
|
||||
// Every failing statement of a batch has to be reported, not just the one that
|
||||
// happened to be visited first: stopping at the first failure leaves an
|
||||
// arbitrary (map-iteration-order-dependent) prefix of the index copy updated
|
||||
// while blaming a single chunk. Each collected error can only exist if its own
|
||||
// UPDATE was attempted, so the count proves the whole batch was run.
|
||||
func TestBatchUpdateChunkTagIDReportsEveryFailingStatementInBatch(t *testing.T) {
|
||||
const batchSize = 5
|
||||
repository := newSQLiteRetrieverTestRepository(t)
|
||||
chunkTagMap := make(map[string]string, batchSize)
|
||||
for i := 1; i <= batchSize; i++ {
|
||||
chunkID := fmt.Sprintf("chunk-%d", i)
|
||||
chunkTagMap[chunkID] = "tag-2"
|
||||
saveSQLiteTestVector(t, repository,
|
||||
sqliteTestIndex(chunkID, "kb-1", "knowledge-1", "tag-1", true),
|
||||
[]float32{1, 0},
|
||||
)
|
||||
}
|
||||
require.NoError(t, repository.db.Exec(`CREATE TRIGGER fail_chunk_tag_update
|
||||
BEFORE UPDATE ON lite_embeddings
|
||||
BEGIN SELECT RAISE(ABORT, 'simulated index write failure'); END`).Error)
|
||||
|
||||
err := repository.BatchUpdateChunkTagID(context.Background(), chunkTagMap)
|
||||
|
||||
require.Error(t, err)
|
||||
for i := 1; i <= batchSize; i++ {
|
||||
assert.Contains(t, err.Error(), fmt.Sprintf("chunk-%d", i))
|
||||
}
|
||||
assert.Equal(t, batchSize, strings.Count(err.Error(), "simulated index write failure"))
|
||||
}
|
||||
|
||||
// A failing statement must not cut the batch short: the other engines (Milvus,
|
||||
// Qdrant) accumulate the error and finish the batch, so the rows the batch was
|
||||
// asked to update are still written. The assertions are on the resulting rows
|
||||
// rather than on a position in the batch because map iteration order is random.
|
||||
func TestBatchUpdateChunkTagIDKeepsUpdatingAfterStatementFailure(t *testing.T) {
|
||||
const batchSize = 5
|
||||
repository := newSQLiteRetrieverTestRepository(t)
|
||||
for i := 1; i <= batchSize; i++ {
|
||||
chunkID := fmt.Sprintf("chunk-%d", i)
|
||||
saveSQLiteTestVector(t, repository,
|
||||
sqliteTestIndex(chunkID, "kb-1", "knowledge-1", "tag-1", true),
|
||||
[]float32{1, 0},
|
||||
)
|
||||
}
|
||||
require.NoError(t, repository.db.Exec(`CREATE TRIGGER fail_chunk_tag_update
|
||||
BEFORE UPDATE ON lite_embeddings
|
||||
WHEN OLD.chunk_id = 'chunk-3'
|
||||
BEGIN SELECT RAISE(ABORT, 'simulated index write failure'); END`).Error)
|
||||
|
||||
err := repository.BatchUpdateChunkTagID(context.Background(), map[string]string{
|
||||
"chunk-1": "tag-2",
|
||||
"chunk-2": "tag-2",
|
||||
"chunk-3": "tag-2",
|
||||
"chunk-4": "tag-2",
|
||||
"chunk-5": "tag-2",
|
||||
})
|
||||
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "chunk-3")
|
||||
assert.Contains(t, err.Error(), "simulated index write failure")
|
||||
|
||||
var rows []sqliteEmbedding
|
||||
require.NoError(t, repository.db.Order("chunk_id").Find(&rows).Error)
|
||||
require.Len(t, rows, batchSize)
|
||||
for _, row := range rows {
|
||||
if row.ChunkID == "chunk-3" {
|
||||
assert.Equal(t, "tag-1", row.TagID, "the failing statement must not be applied")
|
||||
continue
|
||||
}
|
||||
assert.Equal(t, "tag-2", row.TagID, "chunk %s was not updated after the failure", row.ChunkID)
|
||||
}
|
||||
}
|
||||
|
||||
// Matching no row is not an error -- the index copy may legitimately lag behind
|
||||
// the authoritative chunks table -- but it used to be completely invisible, so
|
||||
// both batch updates warn with the table and the chunk they were meant for.
|
||||
func TestBatchUpdateChunkWarnsWhenStatementMatchesNoRow(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
column string
|
||||
update func(repository *sqliteRepository, ctx context.Context) error
|
||||
}{
|
||||
{
|
||||
name: "is_enabled",
|
||||
column: "is_enabled",
|
||||
update: func(repository *sqliteRepository, ctx context.Context) error {
|
||||
return repository.BatchUpdateChunkEnabledStatus(ctx, map[string]bool{
|
||||
"chunk-1": false,
|
||||
"chunk-missing": false,
|
||||
})
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "tag_id",
|
||||
column: "tag_id",
|
||||
update: func(repository *sqliteRepository, ctx context.Context) error {
|
||||
return repository.BatchUpdateChunkTagID(ctx, map[string]string{
|
||||
"chunk-1": "tag-2",
|
||||
"chunk-missing": "tag-2",
|
||||
})
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
repository := newSQLiteRetrieverTestRepository(t)
|
||||
saveSQLiteTestVector(t, repository,
|
||||
sqliteTestIndex("chunk-1", "kb-1", "knowledge-1", "tag-1", true),
|
||||
[]float32{1, 0},
|
||||
)
|
||||
|
||||
var logs bytes.Buffer
|
||||
logger.SetOutput(&logs)
|
||||
t.Cleanup(func() { logger.SetOutput(os.Stdout) })
|
||||
|
||||
require.NoError(t, testCase.update(repository, context.Background()))
|
||||
|
||||
output := logs.String()
|
||||
t.Logf("captured log output:\n%s", output)
|
||||
assert.Contains(t, output, "lite_embeddings."+testCase.column)
|
||||
assert.Contains(t, output, "matched 0 rows for chunk chunk-missing")
|
||||
assert.NotContains(t, output, "matched 0 rows for chunk chunk-1")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Happy path: the updates still apply and report success.
|
||||
func TestBatchUpdateChunkStatusAndTagApply(t *testing.T) {
|
||||
repository := newSQLiteRetrieverTestRepository(t)
|
||||
saveSQLiteTestVector(t, repository,
|
||||
sqliteTestIndex("chunk-1", "kb-1", "knowledge-1", "tag-1", true),
|
||||
[]float32{1, 0},
|
||||
)
|
||||
|
||||
require.NoError(t, repository.BatchUpdateChunkEnabledStatus(
|
||||
context.Background(), map[string]bool{"chunk-1": false}))
|
||||
require.NoError(t, repository.BatchUpdateChunkTagID(
|
||||
context.Background(), map[string]string{"chunk-1": "tag-2"}))
|
||||
|
||||
var row sqliteEmbedding
|
||||
require.NoError(t, repository.db.Where("chunk_id = ?", "chunk-1").First(&row).Error)
|
||||
require.NotNil(t, row.IsEnabled)
|
||||
assert.False(t, *row.IsEnabled)
|
||||
assert.Equal(t, "tag-2", row.TagID)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package sqlite
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestSanitizeFTS5QueryScopesToContent(t *testing.T) {
|
||||
t.Parallel()
|
||||
assert.Equal(t, `content : ("2023")`, sanitizeFTS5Query("2023"))
|
||||
// Quotes never reach an FTS string unescaped.
|
||||
assert.Equal(t, `content : ("say" OR "hi")`, sanitizeFTS5Query(`say"hi"`))
|
||||
// A lone Han character matches bigrams that start with it.
|
||||
assert.Equal(t, `content : ("A" OR "股"*)`, sanitizeFTS5Query("A股"))
|
||||
assert.Equal(t, "", sanitizeFTS5Query(" "))
|
||||
}
|
||||
|
||||
// Only the content column is searched: IDs indexed alongside it must not
|
||||
// match a query.
|
||||
func TestKeywordsRetrieveIgnoresIDColumns(t *testing.T) {
|
||||
repository := newSQLiteRetrieverTestRepository(t)
|
||||
if !repository.db.Migrator().HasTable("lite_embeddings_fts") {
|
||||
t.Skip("FTS5 unavailable (build without sqlite_fts5)")
|
||||
}
|
||||
info := sqliteTestIndex("chunk-2023", "kb", "knowledge", "", true)
|
||||
info.Content = "quarterly report"
|
||||
saveSQLiteTestVector(t, repository, info, []float32{1, 0})
|
||||
|
||||
assert.Empty(t, keywordSearch(t, repository, "2023"))
|
||||
assert.Len(t, keywordSearch(t, repository, "quarterly"), 1)
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
package sqlite
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// A chunk row is only useful when its vec0 and FTS rows exist too: retrieval
|
||||
// joins both index tables on lite_embeddings.id. A discarded index write used
|
||||
// to commit the chunk row while Save still returned nil, so these tests pin the
|
||||
// error and the rollback, not just the error.
|
||||
|
||||
func countSQLiteRows(t *testing.T, repository *sqliteRepository, sql string, args ...any) int64 {
|
||||
t.Helper()
|
||||
var count int64
|
||||
require.NoError(t, repository.db.Raw(sql, args...).Scan(&count).Error, "count query: %s", sql)
|
||||
return count
|
||||
}
|
||||
|
||||
func TestBatchSaveRollsBackWhenVecTableIsGone(t *testing.T) {
|
||||
repository := newSQLiteRetrieverTestRepository(t)
|
||||
ctx := context.Background()
|
||||
|
||||
control := sqliteTestIndex("ctl", "kb", "knowledge", "", true)
|
||||
saveSQLiteTestVector(t, repository, control, []float32{1, 0})
|
||||
require.EqualValues(t, 1, countSQLiteRows(t, repository, "SELECT count(*) FROM vec_embeddings_2"))
|
||||
|
||||
require.NoError(t, repository.db.Exec("DROP TABLE vec_embeddings_2").Error)
|
||||
|
||||
victim := sqliteTestIndex("victim", "kb", "knowledge", "", true)
|
||||
err := repository.Save(ctx, victim, map[string]any{
|
||||
"embedding": map[string][]float32{victim.SourceID: {0, 1}},
|
||||
})
|
||||
|
||||
require.Error(t, err, "a dropped vec0 table must not be reported as a successful save")
|
||||
assert.Contains(t, err.Error(), "vec_embeddings_2")
|
||||
assert.EqualValues(t, 0, countSQLiteRows(t, repository,
|
||||
"SELECT count(*) FROM lite_embeddings WHERE chunk_id = ?", victim.ChunkID),
|
||||
"the chunk row must roll back together with its vector row")
|
||||
|
||||
// The failed write drops the cached "ready" state, so the next save
|
||||
// recreates the table instead of failing forever.
|
||||
require.NoError(t, repository.Save(ctx, victim, map[string]any{
|
||||
"embedding": map[string][]float32{victim.SourceID: {0, 1}},
|
||||
}))
|
||||
assert.EqualValues(t, 1, countSQLiteRows(t, repository,
|
||||
"SELECT count(*) FROM lite_embeddings WHERE chunk_id = ?", victim.ChunkID))
|
||||
assert.EqualValues(t, 1, countSQLiteRows(t, repository, "SELECT count(*) FROM vec_embeddings_2"))
|
||||
}
|
||||
|
||||
func TestBatchSaveRollsBackWhenFTSTableIsGone(t *testing.T) {
|
||||
repository := newSQLiteRetrieverTestRepository(t)
|
||||
if !repository.db.Migrator().HasTable("lite_embeddings_fts") {
|
||||
t.Skip("FTS5 unavailable (build without sqlite_fts5)")
|
||||
}
|
||||
ctx := context.Background()
|
||||
|
||||
control := sqliteTestIndex("ctl", "kb", "knowledge", "", true)
|
||||
saveSQLiteTestVector(t, repository, control, []float32{1, 0})
|
||||
require.EqualValues(t, 1, countSQLiteRows(t, repository, "SELECT count(*) FROM lite_embeddings_fts"))
|
||||
|
||||
require.NoError(t, repository.db.Exec("DROP TABLE lite_embeddings_fts").Error)
|
||||
|
||||
victim := sqliteTestIndex("victim", "kb", "knowledge", "", true)
|
||||
err := repository.Save(ctx, victim, map[string]any{
|
||||
"embedding": map[string][]float32{victim.SourceID: {0, 1}},
|
||||
})
|
||||
|
||||
require.Error(t, err, "a dropped FTS table must not be reported as a successful save")
|
||||
assert.Contains(t, err.Error(), "lite_embeddings_fts")
|
||||
assert.EqualValues(t, 0, countSQLiteRows(t, repository,
|
||||
"SELECT count(*) FROM lite_embeddings WHERE chunk_id = ?", victim.ChunkID),
|
||||
"the chunk row must roll back together with its keyword index row")
|
||||
assert.EqualValues(t, 0, countSQLiteRows(t, repository, `SELECT count(*) FROM vec_embeddings_2
|
||||
WHERE rowid IN (SELECT id FROM lite_embeddings WHERE chunk_id = ?)`, victim.ChunkID))
|
||||
}
|
||||
|
||||
func TestBatchSaveRollsBackWhenVecInsertIsRejected(t *testing.T) {
|
||||
repository := newSQLiteRetrieverTestRepository(t)
|
||||
ctx := context.Background()
|
||||
|
||||
// A vec0 table of another dimension occupies the name: the table is real,
|
||||
// so only the insert itself can fail. A 2-dimension vector into float[3]
|
||||
// is rejected by vec0.
|
||||
require.NoError(t, repository.db.Exec(`CREATE VIRTUAL TABLE vec_embeddings_2
|
||||
USING vec0(embedding float[3] distance_metric=cosine)`).Error)
|
||||
|
||||
victim := sqliteTestIndex("victim", "kb", "knowledge", "", true)
|
||||
err := repository.Save(ctx, victim, map[string]any{
|
||||
"embedding": map[string][]float32{victim.SourceID: {0, 1}},
|
||||
})
|
||||
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "vec_embeddings_2")
|
||||
assert.EqualValues(t, 0, countSQLiteRows(t, repository,
|
||||
"SELECT count(*) FROM lite_embeddings WHERE chunk_id = ?", victim.ChunkID),
|
||||
"a rejected vector insert must roll the chunk row back")
|
||||
}
|
||||
|
||||
// An object that only occupies the vec0 table name used to be cached as a
|
||||
// ready dimension, which kept the whole process from ever creating the table.
|
||||
func TestSaveFailsWhenAnotherObjectOwnsTheVecTableName(t *testing.T) {
|
||||
repository := newSQLiteRetrieverTestRepository(t)
|
||||
ctx := context.Background()
|
||||
|
||||
require.NoError(t, repository.db.Exec(`CREATE VIEW vec_embeddings_2 AS SELECT 1 AS x WHERE 0`).Error)
|
||||
|
||||
victim := sqliteTestIndex("victim", "kb", "knowledge", "", true)
|
||||
err := repository.Save(ctx, victim, map[string]any{
|
||||
"embedding": map[string][]float32{victim.SourceID: {1, 0}},
|
||||
})
|
||||
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "vec_embeddings_2")
|
||||
assert.False(t, repository.hasVecTable(2), "a failed prepare must not be cached as ready")
|
||||
assert.EqualValues(t, 0, countSQLiteRows(t, repository,
|
||||
"SELECT count(*) FROM lite_embeddings WHERE chunk_id = ?", victim.ChunkID))
|
||||
|
||||
// Once the obstruction is gone the very next save must retry the table.
|
||||
require.NoError(t, repository.db.Exec("DROP VIEW vec_embeddings_2").Error)
|
||||
require.NoError(t, repository.Save(ctx, victim, map[string]any{
|
||||
"embedding": map[string][]float32{victim.SourceID: {1, 0}},
|
||||
}))
|
||||
assert.EqualValues(t, 1, countSQLiteRows(t, repository,
|
||||
"SELECT count(*) FROM vec_embeddings_2"))
|
||||
}
|
||||
|
||||
func TestDeleteByChunkIDListReportsIndexDeleteFailure(t *testing.T) {
|
||||
repository := newSQLiteRetrieverTestRepository(t)
|
||||
info := sqliteTestIndex("chunk", "kb", "knowledge", "", true)
|
||||
saveSQLiteTestVector(t, repository, info, []float32{1, 0})
|
||||
|
||||
require.NoError(t, repository.db.Exec("DROP TABLE vec_embeddings_2").Error)
|
||||
|
||||
err := repository.DeleteByChunkIDList(context.Background(), []string{info.ChunkID}, 2,
|
||||
string(types.KnowledgeTypeManual))
|
||||
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "vec_embeddings_2")
|
||||
assert.EqualValues(t, 1, countSQLiteRows(t, repository,
|
||||
"SELECT count(*) FROM lite_embeddings WHERE chunk_id = ?", info.ChunkID),
|
||||
"the chunk row must survive an index delete that failed")
|
||||
}
|
||||
|
||||
func TestCopyIndicesReportsVectorCopyFailure(t *testing.T) {
|
||||
repository := newSQLiteRetrieverTestRepository(t)
|
||||
source := sqliteTestIndex("chunk", "kb-src", "knowledge-src", "", true)
|
||||
saveSQLiteTestVector(t, repository, source, []float32{1, 0})
|
||||
|
||||
require.NoError(t, repository.db.Exec("DROP TABLE vec_embeddings_2").Error)
|
||||
|
||||
err := repository.CopyIndices(context.Background(), "kb-src",
|
||||
map[string]string{"knowledge-src": "knowledge-dst"},
|
||||
map[string]string{"chunk": "chunk-dst"},
|
||||
"kb-dst", 2, string(types.KnowledgeTypeManual),
|
||||
)
|
||||
|
||||
require.Error(t, err, "a copy without its vector row must not be reported as a success")
|
||||
assert.Contains(t, err.Error(), "vec_embeddings_2")
|
||||
}
|
||||
|
||||
// A rejected row used to be logged and skipped, so a clone could report success
|
||||
// while one chunk never became retrievable. The error must fail the copy and
|
||||
// name the lost row, without quoting content.
|
||||
func TestCopyIndicesReportsRejectedRowWithChunkIDs(t *testing.T) {
|
||||
repository := newSQLiteRetrieverTestRepository(t)
|
||||
chunk := sqliteTestIndex("src-chunk", "kb-src", "knowledge-src", "", true)
|
||||
chunk.SourceID = "src-chunk"
|
||||
chunk.Content = "secret chunk body"
|
||||
question := sqliteTestIndex("src-chunk", "kb-src", "knowledge-src", "", false)
|
||||
question.SourceID = "src-chunk-q1"
|
||||
question.Content = "secret question body"
|
||||
require.NoError(t, repository.BatchSave(context.Background(), []*types.IndexInfo{chunk, question}, map[string]any{
|
||||
"embedding": map[string][]float32{
|
||||
chunk.SourceID: {1, 0},
|
||||
question.SourceID: {0, 1},
|
||||
},
|
||||
}))
|
||||
|
||||
// Only the chunk row is rejected; the question row of the same chunk still
|
||||
// has to be copied, so the error can be shown to point at one row.
|
||||
require.NoError(t, repository.db.Exec(`CREATE TRIGGER reject_copied_chunk BEFORE INSERT ON lite_embeddings
|
||||
WHEN NEW.chunk_id = 'dst-chunk' AND NEW.source_id = 'dst-chunk'
|
||||
BEGIN SELECT RAISE(ABORT, 'rejected copy'); END`).Error)
|
||||
|
||||
err := repository.CopyIndices(context.Background(), "kb-src",
|
||||
map[string]string{"knowledge-src": "knowledge-dst"},
|
||||
map[string]string{"src-chunk": "dst-chunk"},
|
||||
"kb-dst", 2, string(types.KnowledgeTypeManual),
|
||||
)
|
||||
|
||||
require.Error(t, err, "a rejected row must not be reported as a successful copy")
|
||||
assert.Contains(t, err.Error(), "src-chunk", "the error must name the source chunk")
|
||||
assert.Contains(t, err.Error(), "dst-chunk", "the error must name the target chunk")
|
||||
assert.NotContains(t, err.Error(), "secret", "the error must locate the row without leaking its content")
|
||||
assert.NotContains(t, err.Error(), "src-chunk-q1", "only the rejected row may be reported")
|
||||
assert.EqualValues(t, 1, countSQLiteRows(t, repository,
|
||||
"SELECT count(*) FROM lite_embeddings WHERE source_id = ?", "dst-chunk-q1"),
|
||||
"the sibling row of the same chunk must still be copied")
|
||||
assert.EqualValues(t, 0, countSQLiteRows(t, repository,
|
||||
"SELECT count(*) FROM lite_embeddings WHERE source_id = ?", "dst-chunk"))
|
||||
}
|
||||
|
||||
// A failing keyword index write is accumulated instead of ending the copy: the
|
||||
// caller sees the row that lost its index row, and the copy keeps going so one
|
||||
// broken row cannot hide the remaining failures.
|
||||
func TestCopyIndicesReportsKeywordCopyFailureWithoutLosingTheRow(t *testing.T) {
|
||||
repository := newSQLiteRetrieverTestRepository(t)
|
||||
if !repository.db.Migrator().HasTable("lite_embeddings_fts") {
|
||||
t.Skip("FTS5 unavailable (build without sqlite_fts5)")
|
||||
}
|
||||
|
||||
source := sqliteTestIndex("src-chunk", "kb-src", "knowledge-src", "", true)
|
||||
source.SourceID = "src-chunk"
|
||||
saveSQLiteTestVector(t, repository, source, []float32{1, 0})
|
||||
require.NoError(t, repository.db.Exec("DROP TABLE lite_embeddings_fts").Error)
|
||||
|
||||
err := repository.CopyIndices(context.Background(), "kb-src",
|
||||
map[string]string{"knowledge-src": "knowledge-dst"},
|
||||
map[string]string{"src-chunk": "dst-chunk"},
|
||||
"kb-dst", 2, string(types.KnowledgeTypeManual),
|
||||
)
|
||||
|
||||
require.Error(t, err, "a copy whose keyword index row was lost must not report success")
|
||||
assert.Contains(t, err.Error(), "src-chunk")
|
||||
assert.Contains(t, err.Error(), "dst-chunk")
|
||||
assert.Contains(t, err.Error(), "lite_embeddings_fts")
|
||||
assert.EqualValues(t, 1, countSQLiteRows(t, repository,
|
||||
"SELECT count(*) FROM lite_embeddings WHERE source_id = ?", "dst-chunk"))
|
||||
assert.EqualValues(t, 1, countSQLiteRows(t, repository,
|
||||
`SELECT count(*) FROM vec_embeddings_2 WHERE rowid IN
|
||||
(SELECT id FROM lite_embeddings WHERE source_id = ?)`, "dst-chunk"),
|
||||
"the vector row must still be copied after the keyword index write failed")
|
||||
}
|
||||
|
||||
func TestSaveStillWritesEveryIndexRowOnHealthyTables(t *testing.T) {
|
||||
repository := newSQLiteRetrieverTestRepository(t)
|
||||
info := sqliteTestIndex("chunk", "kb", "knowledge", "", true)
|
||||
saveSQLiteTestVector(t, repository, info, []float32{1, 0})
|
||||
|
||||
assert.EqualValues(t, 1, countSQLiteRows(t, repository,
|
||||
"SELECT count(*) FROM lite_embeddings WHERE chunk_id = ?", info.ChunkID))
|
||||
assert.EqualValues(t, 1, countSQLiteRows(t, repository, "SELECT count(*) FROM vec_embeddings_2"))
|
||||
if repository.db.Migrator().HasTable("lite_embeddings_fts") {
|
||||
assert.EqualValues(t, 1, countSQLiteRows(t, repository,
|
||||
"SELECT count(*) FROM lite_embeddings_fts"))
|
||||
assert.Len(t, keywordSearch(t, repository, "content of chunk"), 1)
|
||||
}
|
||||
}
|
||||
|
||||
// A driver built without the fts5 module cannot host a keyword index at all.
|
||||
// That is a property of the build, so saving keeps working and the keyword
|
||||
// index is simply absent; a table that goes missing while fts5 is compiled in
|
||||
// is a real failure and is covered by TestBatchSaveRollsBackWhenFTSTableIsGone.
|
||||
func TestSaveWorksWhenTheFTS5ModuleIsNotCompiledIn(t *testing.T) {
|
||||
repository := newSQLiteRetrieverTestRepository(t)
|
||||
if repository.db.Migrator().HasTable("lite_embeddings_fts") {
|
||||
t.Skip("fts5 is compiled in; the keyword index is checked by the other tests")
|
||||
}
|
||||
|
||||
info := sqliteTestIndex("chunk", "kb", "knowledge", "", true)
|
||||
saveSQLiteTestVector(t, repository, info, []float32{1, 0})
|
||||
|
||||
assert.EqualValues(t, 1, countSQLiteRows(t, repository,
|
||||
"SELECT count(*) FROM lite_embeddings WHERE chunk_id = ?", info.ChunkID))
|
||||
assert.EqualValues(t, 1, countSQLiteRows(t, repository, "SELECT count(*) FROM vec_embeddings_2"))
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// Package sqlite implements local retrieval with SQLite FTS and vectors.
|
||||
package sqlite
|
||||
|
||||
import "context"
|
||||
|
||||
func (r *sqliteRepository) MoveKnowledgeIndices(
|
||||
ctx context.Context,
|
||||
sourceKB, targetKB, knowledgeID string,
|
||||
_ []string,
|
||||
_ int,
|
||||
_ string,
|
||||
) error {
|
||||
// FTS and vector rows keep their IDs. Queries join them to this metadata row.
|
||||
return r.db.WithContext(ctx).Model(&sqliteEmbedding{}).
|
||||
Where("knowledge_base_id = ? AND knowledge_id = ?", sourceKB, knowledgeID).
|
||||
Updates(map[string]any{"knowledge_base_id": targetKB, "tag_id": ""}).Error
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package sqlite
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestMoveIndicesPreservesVectorsAndExactScopeAcrossRetry(t *testing.T) {
|
||||
repo := newSQLiteRetrieverTestRepository(t)
|
||||
ctx := context.Background()
|
||||
for _, row := range []struct{ chunk, kb, doc string }{
|
||||
{
|
||||
"text",
|
||||
"source",
|
||||
"doc",
|
||||
},
|
||||
{
|
||||
"image",
|
||||
"source",
|
||||
"doc",
|
||||
},
|
||||
{
|
||||
"other",
|
||||
"source",
|
||||
"other-doc",
|
||||
},
|
||||
{
|
||||
"foreign",
|
||||
"third",
|
||||
"doc",
|
||||
},
|
||||
} {
|
||||
saveSQLiteTestVector(t, repo, sqliteTestIndex(row.chunk, row.kb, row.doc, "old-tag", true), []float32{1, 0})
|
||||
}
|
||||
var before []sqliteEmbedding
|
||||
require.NoError(t, repo.db.Order("id").Find(&before).Error)
|
||||
for range 2 {
|
||||
require.NoError(
|
||||
t,
|
||||
repo.MoveKnowledgeIndices(ctx, "source", "target", "doc", []string{"text", "image"}, 2, "document"),
|
||||
)
|
||||
}
|
||||
var after []sqliteEmbedding
|
||||
require.NoError(t, repo.db.Order("id").Find(&after).Error)
|
||||
require.Len(t, after, len(before))
|
||||
for i, row := range after {
|
||||
require.Equal(t, before[i].ID, row.ID)
|
||||
require.Equal(t, before[i].SourceID, row.SourceID)
|
||||
if row.KnowledgeID == "doc" && before[i].KnowledgeBaseID == "source" {
|
||||
require.Equal(t, "target", row.KnowledgeBaseID)
|
||||
require.Empty(t, row.TagID)
|
||||
} else {
|
||||
require.Equal(t, before[i].KnowledgeBaseID, row.KnowledgeBaseID)
|
||||
require.Equal(t, "old-tag", row.TagID)
|
||||
}
|
||||
}
|
||||
results, err := repo.vectorRetrieve(
|
||||
ctx,
|
||||
types.RetrieveParams{
|
||||
Embedding: []float32{1, 0},
|
||||
TopK: 10,
|
||||
KnowledgeBaseIDs: []string{"target"},
|
||||
RetrieverType: types.VectorRetrieverType,
|
||||
},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, results, 1)
|
||||
require.Len(t, results[0].Results, 2, "target vectors remain searchable after an identity-preserving move")
|
||||
}
|
||||
@@ -0,0 +1,994 @@
|
||||
package sqlite
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"academy/internal/common"
|
||||
"academy/internal/logger"
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
sqlite_vec "github.com/asg017/sqlite-vec-go-bindings/cgo"
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// sqliteEmbedding stores metadata alongside the vec0 virtual table rows
|
||||
type sqliteEmbedding struct {
|
||||
ID uint `gorm:"primarykey;autoIncrement"`
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at"`
|
||||
SourceID string `gorm:"column:source_id;not null;uniqueIndex:idx_sqlite_emb_source"`
|
||||
SourceType int `gorm:"column:source_type;not null;uniqueIndex:idx_sqlite_emb_source"`
|
||||
ChunkID string `gorm:"column:chunk_id;index"`
|
||||
KnowledgeID string `gorm:"column:knowledge_id;index"`
|
||||
KnowledgeBaseID string `gorm:"column:knowledge_base_id;index"`
|
||||
TagID string `gorm:"column:tag_id;index"`
|
||||
Content string `gorm:"column:content;not null"`
|
||||
Dimension int `gorm:"column:dimension;not null"`
|
||||
IsEnabled *bool `gorm:"column:is_enabled;default:true;index"`
|
||||
}
|
||||
|
||||
func (sqliteEmbedding) TableName() string { return "lite_embeddings" }
|
||||
|
||||
type sqliteRepository struct {
|
||||
db *gorm.DB
|
||||
// vecMu guards vecTables: concurrent BatchSave and retrieval goroutines
|
||||
// all consult it, and an unguarded map write is a fatal runtime error.
|
||||
vecMu sync.RWMutex
|
||||
vecTables map[int]bool // tracks which vec0 tables have been created (keyed by dimension)
|
||||
// ftsUnavailable records that the driver was built without the fts5 module
|
||||
// (upstream test runs do not pass -tags sqlite_fts5). Keyword indexing
|
||||
// cannot exist in such a build at all, so its writes are skipped instead of
|
||||
// failing every ingestion; Lite release builds always pass the tag.
|
||||
ftsUnavailable bool
|
||||
}
|
||||
|
||||
func NewSQLiteRetrieveEngineRepository(db *gorm.DB) interfaces.RetrieveEngineRepository {
|
||||
logger.GetLogger(context.Background()).Info("[SQLite] Initializing SQLite retriever engine repository with sqlite-vec")
|
||||
|
||||
if err := db.AutoMigrate(&sqliteEmbedding{}); err != nil {
|
||||
logger.GetLogger(context.Background()).Errorf("[SQLite] Failed to auto-migrate lite_embeddings: %v", err)
|
||||
}
|
||||
|
||||
repo := &sqliteRepository{
|
||||
db: db,
|
||||
vecTables: make(map[int]bool),
|
||||
}
|
||||
|
||||
if err := repo.initFTS5(); err != nil {
|
||||
if errors.Is(err, errFTS5ModuleMissing) {
|
||||
repo.ftsUnavailable = true
|
||||
logger.GetLogger(context.Background()).Warnf(
|
||||
"[SQLite] Keyword index disabled, driver has no fts5 module: %v", err)
|
||||
} else {
|
||||
logger.GetLogger(context.Background()).Errorf("[SQLite] Failed to initialize FTS5 index: %v", err)
|
||||
}
|
||||
}
|
||||
enableImageChunkIndexes(db)
|
||||
|
||||
repo.ensureExistingVecTables()
|
||||
|
||||
return repo
|
||||
}
|
||||
|
||||
// enableImageChunkIndexes repairs image OCR/caption rows that were indexed
|
||||
// with is_enabled = 0 because the multimodal indexer never set IsEnabled.
|
||||
// Retrieval filters on is_enabled, so those rows were never searchable.
|
||||
// Only rows whose chunk is itself enabled are touched, which leaves chunks a
|
||||
// user disabled alone; after the first run the statement matches nothing.
|
||||
func enableImageChunkIndexes(db *gorm.DB) {
|
||||
result := db.Exec(`UPDATE lite_embeddings SET is_enabled = 1
|
||||
WHERE is_enabled = 0 AND chunk_id IN (
|
||||
SELECT id FROM chunks
|
||||
WHERE chunk_type IN (?, ?) AND is_enabled = 1
|
||||
)`, string(types.ChunkTypeImageOCR), string(types.ChunkTypeImageCaption))
|
||||
if result.Error != nil {
|
||||
logger.GetLogger(context.Background()).Warnf(
|
||||
"[SQLite] Failed to re-enable image chunk indexes: %v", result.Error)
|
||||
return
|
||||
}
|
||||
if result.RowsAffected > 0 {
|
||||
logger.GetLogger(context.Background()).Infof(
|
||||
"[SQLite] Re-enabled %d image OCR/caption index rows", result.RowsAffected)
|
||||
}
|
||||
}
|
||||
|
||||
// errFTS5ModuleMissing reports a driver built without the fts5 module. The
|
||||
// keyword index cannot exist in such a build, which is a property of the build
|
||||
// rather than a write that failed at runtime.
|
||||
var errFTS5ModuleMissing = errors.New("sqlite driver built without the fts5 module")
|
||||
|
||||
// fts5InsertSQL is shared by the initial population and every later keyword
|
||||
// index write, so both always build the same row shape.
|
||||
const fts5InsertSQL = `INSERT INTO lite_embeddings_fts(
|
||||
rowid, content, source_id, chunk_id, knowledge_id, knowledge_base_id) VALUES(?, ?, ?, ?, ?, ?)`
|
||||
|
||||
// initFTS5 prepares the contentless FTS5 keyword index. A failure is returned
|
||||
// so it is not mistaken for a working index; the table and its content are
|
||||
// built in one transaction, because a half-populated index silently drops
|
||||
// keyword recall for every row that was left out.
|
||||
func (r *sqliteRepository) initFTS5() error {
|
||||
var sqlStr string
|
||||
err := r.db.Raw(
|
||||
"SELECT sql FROM sqlite_master WHERE type='table' AND name='lite_embeddings_fts'",
|
||||
).Scan(&sqlStr).Error
|
||||
if err != nil {
|
||||
return fmt.Errorf("[SQLite] failed to inspect lite_embeddings_fts: %w", err)
|
||||
}
|
||||
// If the table exists but is not contentless (i.e. uses content='lite_embeddings'), recreate it
|
||||
migrate := sqlStr != "" && strings.Contains(sqlStr, "content='lite_embeddings'")
|
||||
if migrate {
|
||||
logger.GetLogger(context.Background()).Infof(
|
||||
"[SQLite] Migrating FTS5 table to contentless table with manual bigram tokenization")
|
||||
} else if sqlStr != "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
err = r.db.Transaction(func(tx *gorm.DB) error {
|
||||
if migrate {
|
||||
if err := tx.Exec("DROP TABLE IF EXISTS lite_embeddings_fts").Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
createSQL := `CREATE VIRTUAL TABLE IF NOT EXISTS lite_embeddings_fts USING fts5(
|
||||
content, source_id, chunk_id, knowledge_id, knowledge_base_id,
|
||||
content='',
|
||||
contentless_delete=1,
|
||||
tokenize='unicode61'
|
||||
)`
|
||||
if err := tx.Exec(createSQL).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
logger.GetLogger(context.Background()).Infof(
|
||||
"[SQLite] Populating contentless FTS5 table from lite_embeddings with bigrams")
|
||||
|
||||
// To populate, we need to read all rows and insert them via Go to apply bigram tokenization
|
||||
type Row struct {
|
||||
ID uint
|
||||
Content string
|
||||
SourceID string
|
||||
ChunkID string
|
||||
KnowledgeID string
|
||||
KnowledgeBaseID string
|
||||
}
|
||||
var rows []Row
|
||||
if err := tx.Raw(
|
||||
"SELECT id, content, source_id, chunk_id, knowledge_id, knowledge_base_id FROM lite_embeddings",
|
||||
).Scan(&rows).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
for _, row := range rows {
|
||||
if err := tx.Exec(fts5InsertSQL, row.ID, tokenizeCJKBigram(row.Content), row.SourceID,
|
||||
row.ChunkID, row.KnowledgeID, row.KnowledgeBaseID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "no such module: fts5") {
|
||||
return fmt.Errorf("%w: %v", errFTS5ModuleMissing, err)
|
||||
}
|
||||
return fmt.Errorf("[SQLite] failed to initialize lite_embeddings_fts: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func vecTableName(dim int) string {
|
||||
return fmt.Sprintf("vec_embeddings_%d", dim)
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) hasVecTable(dim int) bool {
|
||||
r.vecMu.RLock()
|
||||
defer r.vecMu.RUnlock()
|
||||
return r.vecTables[dim]
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) markVecTable(dim int) {
|
||||
r.vecMu.Lock()
|
||||
defer r.vecMu.Unlock()
|
||||
r.vecTables[dim] = true
|
||||
}
|
||||
|
||||
// unmarkVecTable drops the cached "ready" state of a dimension after a write
|
||||
// against its table failed, so the next write re-checks the table instead of
|
||||
// trusting a marker that no longer describes it.
|
||||
func (r *sqliteRepository) unmarkVecTable(dim int) {
|
||||
r.vecMu.Lock()
|
||||
defer r.vecMu.Unlock()
|
||||
delete(r.vecTables, dim)
|
||||
}
|
||||
|
||||
// verifyVecTable rejects a same-named object that is not a vec0 table. It is
|
||||
// needed because CREATE VIRTUAL TABLE IF NOT EXISTS is a silent no-op when any
|
||||
// object already occupies the name, and a marker set from that no-op kept the
|
||||
// dimension unindexed for the rest of the process lifetime.
|
||||
func (r *sqliteRepository) verifyVecTable(tbl string) error {
|
||||
var createSQL string
|
||||
if err := r.db.Raw(
|
||||
`SELECT COALESCE(sql, '') FROM sqlite_master WHERE type = 'table' AND name = ?`, tbl,
|
||||
).Scan(&createSQL).Error; err != nil {
|
||||
return fmt.Errorf("[SQLite] failed to inspect %s: %w", tbl, err)
|
||||
}
|
||||
if createSQL == "" {
|
||||
return fmt.Errorf("[SQLite] %s is missing after CREATE VIRTUAL TABLE", tbl)
|
||||
}
|
||||
if !strings.Contains(strings.ToLower(createSQL), "using vec0") {
|
||||
return fmt.Errorf("[SQLite] %s exists but is not a vec0 table: %s", tbl, createSQL)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ensureVecTable makes the vec0 table of a dimension usable and returns an
|
||||
// error when it cannot, so callers never write vectors into a table that does
|
||||
// not exist. A dimension is only cached as ready once the table was verified.
|
||||
func (r *sqliteRepository) ensureVecTable(dim int) error {
|
||||
if dim <= 0 {
|
||||
return nil
|
||||
}
|
||||
if r.hasVecTable(dim) {
|
||||
return nil
|
||||
}
|
||||
tbl := vecTableName(dim)
|
||||
createSQL := fmt.Sprintf(
|
||||
`CREATE VIRTUAL TABLE IF NOT EXISTS %s USING vec0(embedding float[%d] distance_metric=cosine)`,
|
||||
tbl, dim,
|
||||
)
|
||||
if err := r.db.Exec(createSQL).Error; err != nil {
|
||||
return fmt.Errorf("[SQLite] failed to create vec0 table %s: %w", tbl, err)
|
||||
}
|
||||
if err := r.verifyVecTable(tbl); err != nil {
|
||||
return err
|
||||
}
|
||||
r.markVecTable(dim)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) ensureExistingVecTables() {
|
||||
var dims []int
|
||||
if err := r.db.Model(&sqliteEmbedding{}).Distinct("dimension").
|
||||
Where("dimension > 0").Pluck("dimension", &dims).Error; err != nil {
|
||||
logger.GetLogger(context.Background()).Warnf(
|
||||
"[SQLite] Failed to list indexed dimensions: %v", err)
|
||||
return
|
||||
}
|
||||
for _, dim := range dims {
|
||||
// A failure here is not cached: the next write retries and reports it.
|
||||
if err := r.ensureVecTable(dim); err != nil {
|
||||
logger.GetLogger(context.Background()).Errorf(
|
||||
"[SQLite] Failed to prepare vec0 table for dim %d: %v", dim, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) EngineType() types.RetrieverEngineType {
|
||||
return types.SQLiteRetrieverEngineType
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) Support() []types.RetrieverType {
|
||||
return []types.RetrieverType{types.KeywordsRetrieverType, types.VectorRetrieverType}
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) Save(ctx context.Context, indexInfo *types.IndexInfo, params map[string]any) error {
|
||||
return r.BatchSave(ctx, []*types.IndexInfo{indexInfo}, params)
|
||||
}
|
||||
|
||||
// BatchSave upserts by (source_id, source_type): rows already indexed for a
|
||||
// source are replaced together with their FTS and vec0 entries. Callers
|
||||
// re-index an edited FAQ entry under its old source ID and expect the new
|
||||
// content to win; ON CONFLICT DO NOTHING kept the stale row instead, and the
|
||||
// skipped rows also shifted the RETURNING ids GORM assigns back to the slice,
|
||||
// attaching vectors and FTS entries to the wrong rows.
|
||||
func (r *sqliteRepository) BatchSave(ctx context.Context, indexInfoList []*types.IndexInfo, params map[string]any) error {
|
||||
if len(indexInfoList) == 0 {
|
||||
return nil
|
||||
}
|
||||
type sourceKey struct {
|
||||
id string
|
||||
typ int
|
||||
}
|
||||
positions := make(map[sourceKey]int, len(indexInfoList))
|
||||
rows := make([]*sqliteEmbedding, 0, len(indexInfoList))
|
||||
embs := make([][]float32, 0, len(indexInfoList))
|
||||
for _, info := range indexInfoList {
|
||||
row := toSQLiteEmbedding(info)
|
||||
emb := extractEmbedding(params, info.SourceID)
|
||||
if len(emb) > 0 {
|
||||
row.Dimension = len(emb)
|
||||
}
|
||||
// A source repeated inside one batch keeps its last entry, as an
|
||||
// upsert would.
|
||||
key := sourceKey{id: row.SourceID, typ: row.SourceType}
|
||||
if i, ok := positions[key]; ok {
|
||||
rows[i], embs[i] = row, emb
|
||||
continue
|
||||
}
|
||||
positions[key] = len(rows)
|
||||
rows = append(rows, row)
|
||||
embs = append(embs, emb)
|
||||
}
|
||||
|
||||
sourceIDs := make([]string, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
sourceIDs = append(sourceIDs, row.SourceID)
|
||||
// vec0 tables are created outside the transaction below: production
|
||||
// SQLite runs on one connection, which the transaction holds.
|
||||
if err := r.ensureVecTable(row.Dimension); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// Replacing a source is one transaction, so a failed insert cannot
|
||||
// leave the source with its old rows deleted and no new ones.
|
||||
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var candidates []sqliteEmbedding
|
||||
if err := tx.Where("source_id IN ?", sourceIDs).Find(&candidates).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
existing := make([]sqliteEmbedding, 0, len(candidates))
|
||||
existingIDs := make([]uint, 0, len(candidates))
|
||||
for _, c := range candidates {
|
||||
if _, ok := positions[sourceKey{id: c.SourceID, typ: c.SourceType}]; ok {
|
||||
existing = append(existing, c)
|
||||
existingIDs = append(existingIDs, c.ID)
|
||||
}
|
||||
}
|
||||
if len(existing) > 0 {
|
||||
if err := r.deleteRowsAndVecs(tx, existing); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Where("id IN ?", existingIDs).Delete(&sqliteEmbedding{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Create(rows).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
// Every index row is written in the same transaction as the chunk row:
|
||||
// returning the error rolls the chunk row back instead of committing a
|
||||
// row that neither retrieval path can find.
|
||||
for i, row := range rows {
|
||||
if err := r.syncFTS5Insert(tx, row); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(embs[i]) > 0 {
|
||||
if err := r.insertVec(tx, row.ID, row.Dimension, embs[i]); err != nil {
|
||||
r.unmarkVecTable(row.Dimension)
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) EstimateStorageSize(_ context.Context, indexInfoList []*types.IndexInfo, _ map[string]any) int64 {
|
||||
var total int64
|
||||
for _, info := range indexInfoList {
|
||||
total += int64(len(info.Content)) + 200
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) DeleteByChunkIDList(ctx context.Context, chunkIDList []string, _ int, _ string) error {
|
||||
var rows []sqliteEmbedding
|
||||
if err := r.db.WithContext(ctx).Where("chunk_id IN ?", chunkIDList).Find(&rows).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := r.deleteRowsAndVecs(r.db.WithContext(ctx), rows); err != nil {
|
||||
return err
|
||||
}
|
||||
return r.db.WithContext(ctx).Where("chunk_id IN ?", chunkIDList).Delete(&sqliteEmbedding{}).Error
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) DeleteBySourceIDList(ctx context.Context, sourceIDList []string, _ int, _ string) error {
|
||||
var rows []sqliteEmbedding
|
||||
if err := r.db.WithContext(ctx).Where("source_id IN ?", sourceIDList).Find(&rows).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := r.deleteRowsAndVecs(r.db.WithContext(ctx), rows); err != nil {
|
||||
return err
|
||||
}
|
||||
return r.db.WithContext(ctx).Where("source_id IN ?", sourceIDList).Delete(&sqliteEmbedding{}).Error
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) DeleteByKnowledgeIDList(ctx context.Context, knowledgeIDList []string, _ int, _ string) error {
|
||||
var rows []sqliteEmbedding
|
||||
if err := r.db.WithContext(ctx).Where("knowledge_id IN ?", knowledgeIDList).Find(&rows).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := r.deleteRowsAndVecs(r.db.WithContext(ctx), rows); err != nil {
|
||||
return err
|
||||
}
|
||||
return r.db.WithContext(ctx).Where("knowledge_id IN ?", knowledgeIDList).Delete(&sqliteEmbedding{}).Error
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) CopyIndices(ctx context.Context,
|
||||
_ string,
|
||||
sourceToTargetKBIDMap map[string]string,
|
||||
sourceToTargetChunkIDMap map[string]string,
|
||||
targetKnowledgeBaseID string,
|
||||
_ int, _ string,
|
||||
) error {
|
||||
sourceChunkIDs := make([]string, 0, len(sourceToTargetChunkIDMap))
|
||||
for sourceChunkID := range sourceToTargetChunkIDMap {
|
||||
sourceChunkIDs = append(sourceChunkIDs, sourceChunkID)
|
||||
}
|
||||
const batchSize = 500
|
||||
// A copied chunk is only usable when its row, keyword index row and vector
|
||||
// row all land: retrieval joins both index tables on lite_embeddings.id, so
|
||||
// a dropped write leaves a chunk neither path can find while the copy still
|
||||
// reports success. Every failing row is collected and the loop keeps going,
|
||||
// so the caller learns all the rows that were lost, not just the first.
|
||||
var copyErrs []error
|
||||
for start := 0; start < len(sourceChunkIDs); start += batchSize {
|
||||
end := min(start+batchSize, len(sourceChunkIDs))
|
||||
// Every row of a chunk is copied: besides the chunk itself, generated
|
||||
// questions are indexed as extra rows under the same chunk_id.
|
||||
var sources []sqliteEmbedding
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("chunk_id IN ?", sourceChunkIDs[start:end]).
|
||||
Order("id").
|
||||
Find(&sources).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
for _, src := range sources {
|
||||
targetChunkID := sourceToTargetChunkIDMap[src.ChunkID]
|
||||
newRow := sqliteEmbedding{
|
||||
SourceID: copiedSourceID(src.SourceID, src.ChunkID, targetChunkID),
|
||||
SourceType: src.SourceType,
|
||||
ChunkID: targetChunkID,
|
||||
KnowledgeID: sourceToTargetKBIDMap[src.KnowledgeID],
|
||||
KnowledgeBaseID: targetKnowledgeBaseID,
|
||||
TagID: src.TagID,
|
||||
Content: src.Content,
|
||||
Dimension: src.Dimension,
|
||||
IsEnabled: src.IsEnabled,
|
||||
}
|
||||
// The source and target chunk IDs locate the lost row without
|
||||
// quoting its content into the error.
|
||||
if err := r.db.WithContext(ctx).Create(&newRow).Error; err != nil {
|
||||
copyErrs = append(copyErrs, fmt.Errorf(
|
||||
"[SQLite] CopyIndices: failed to copy source %s (chunk %s -> %s): %w",
|
||||
src.SourceID, src.ChunkID, targetChunkID, err))
|
||||
continue
|
||||
}
|
||||
if err := r.syncFTS5Insert(r.db.WithContext(ctx), &newRow); err != nil {
|
||||
copyErrs = append(copyErrs, fmt.Errorf(
|
||||
"[SQLite] CopyIndices: failed to copy keyword index of source %s (chunk %s -> %s): %w",
|
||||
src.SourceID, src.ChunkID, targetChunkID, err))
|
||||
}
|
||||
if src.Dimension > 0 {
|
||||
if err := r.copyVec(ctx, src.ID, newRow.ID, src.Dimension); err != nil {
|
||||
copyErrs = append(copyErrs, fmt.Errorf(
|
||||
"[SQLite] CopyIndices: failed to copy vector of source %s (chunk %s -> %s): %w",
|
||||
src.SourceID, src.ChunkID, targetChunkID, err))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return errors.Join(copyErrs...)
|
||||
}
|
||||
|
||||
// copiedSourceID maps a source row's SourceID onto the target chunk the way
|
||||
// the Postgres engine does, so the copy can later be deleted or re-indexed by
|
||||
// source ID: a chunk row uses the chunk ID and a generated question keeps its
|
||||
// "{chunkID}-{questionID}" suffix.
|
||||
func copiedSourceID(sourceID, sourceChunkID, targetChunkID string) string {
|
||||
if sourceID == sourceChunkID {
|
||||
return targetChunkID
|
||||
}
|
||||
if questionID, ok := strings.CutPrefix(sourceID, sourceChunkID+"-"); ok {
|
||||
return targetChunkID + "-" + questionID
|
||||
}
|
||||
return uuid.New().String()
|
||||
}
|
||||
|
||||
// Both batch updates write one statement per chunk, so a failing statement only
|
||||
// affects its own row. Errors are therefore accumulated and the whole batch is
|
||||
// attempted (like the Milvus and Qdrant engines do) instead of stopping at the
|
||||
// first failure and leaving an arbitrary prefix of the map applied, only to be
|
||||
// reported as a blanket failure.
|
||||
func (r *sqliteRepository) BatchUpdateChunkEnabledStatus(ctx context.Context, chunkStatusMap map[string]bool) error {
|
||||
var updateErrs []error
|
||||
for chunkID, enabled := range chunkStatusMap {
|
||||
if err := r.updateChunkIndexColumn(ctx, "is_enabled", chunkID, enabled); err != nil {
|
||||
updateErrs = append(updateErrs,
|
||||
fmt.Errorf("[SQLite] failed to update is_enabled for chunk %s: %w", chunkID, err))
|
||||
}
|
||||
}
|
||||
return errors.Join(updateErrs...)
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) BatchUpdateChunkTagID(ctx context.Context, chunkTagMap map[string]string) error {
|
||||
var updateErrs []error
|
||||
for chunkID, tagID := range chunkTagMap {
|
||||
if err := r.updateChunkIndexColumn(ctx, "tag_id", chunkID, tagID); err != nil {
|
||||
updateErrs = append(updateErrs,
|
||||
fmt.Errorf("[SQLite] failed to update tag_id for chunk %s: %w", chunkID, err))
|
||||
}
|
||||
}
|
||||
return errors.Join(updateErrs...)
|
||||
}
|
||||
|
||||
// updateChunkIndexColumn applies a single per-chunk UPDATE to the retrieval
|
||||
// index copy. A statement matching no row is not an error -- that row may never
|
||||
// have reached the index -- but it would otherwise stay completely invisible,
|
||||
// so it is warned about with the table and chunk it was meant for.
|
||||
func (r *sqliteRepository) updateChunkIndexColumn(
|
||||
ctx context.Context, column, chunkID string, value any,
|
||||
) error {
|
||||
result := r.db.WithContext(ctx).Model(&sqliteEmbedding{}).
|
||||
Where("chunk_id = ?", chunkID).
|
||||
Update(column, value)
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
logger.GetLogger(ctx).Warnf(
|
||||
"[SQLite] update of %s.%s matched 0 rows for chunk %s",
|
||||
sqliteEmbedding{}.TableName(), column, chunkID,
|
||||
)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// --- Retrieve ---
|
||||
|
||||
func (r *sqliteRepository) Retrieve(ctx context.Context, params types.RetrieveParams) ([]*types.RetrieveResult, error) {
|
||||
var results []*types.RetrieveResult
|
||||
|
||||
if params.RetrieverType == types.KeywordsRetrieverType || params.RetrieverType == "" {
|
||||
res, err := r.keywordsRetrieve(ctx, params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
results = append(results, res...)
|
||||
}
|
||||
|
||||
if params.RetrieverType == types.VectorRetrieverType || params.RetrieverType == "" {
|
||||
res, err := r.vectorRetrieve(ctx, params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
results = append(results, res...)
|
||||
}
|
||||
|
||||
return results, nil
|
||||
}
|
||||
|
||||
// --- Keywords retrieval via FTS5 ---
|
||||
func (r *sqliteRepository) keywordsRetrieve(ctx context.Context, params types.RetrieveParams) ([]*types.RetrieveResult, error) {
|
||||
if params.Query == "" {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
ftsQuery := sanitizeFTS5Query(params.Query)
|
||||
|
||||
sql := `
|
||||
SELECT e.id, e.source_id, e.source_type, e.chunk_id,
|
||||
e.knowledge_id, e.knowledge_base_id, e.tag_id,
|
||||
e.content,
|
||||
(bm25(lite_embeddings_fts) * -1000000.0) AS score
|
||||
FROM lite_embeddings_fts
|
||||
JOIN lite_embeddings e ON e.id = lite_embeddings_fts.rowid
|
||||
WHERE lite_embeddings_fts MATCH ?
|
||||
AND (e.is_enabled IS NULL OR e.is_enabled = 1)
|
||||
`
|
||||
|
||||
args := []interface{}{ftsQuery}
|
||||
|
||||
for _, wp := range buildFilterWhere(params, "e") {
|
||||
sql += " AND " + wp.clause
|
||||
args = append(args, wp.args...)
|
||||
}
|
||||
|
||||
sql += " ORDER BY score DESC LIMIT ?"
|
||||
args = append(args, params.TopK)
|
||||
|
||||
type ftsResult struct {
|
||||
ID uint
|
||||
SourceID string
|
||||
SourceType int
|
||||
ChunkID string
|
||||
KnowledgeID string
|
||||
KnowledgeBaseID string
|
||||
TagID string
|
||||
Content string
|
||||
Score float64
|
||||
}
|
||||
|
||||
var rows []ftsResult
|
||||
if err := r.db.WithContext(ctx).Raw(sql, args...).Scan(&rows).Error; err != nil {
|
||||
return nil, fmt.Errorf("FTS5 query failed: %w", err)
|
||||
}
|
||||
|
||||
logger.GetLogger(ctx).Infof("[SQLite] keywordsRetrieve: query=%q, ftsQuery=%q, matched=%d rows", params.Query, ftsQuery, len(rows))
|
||||
|
||||
items := make([]*types.IndexWithScore, len(rows))
|
||||
for i, row := range rows {
|
||||
|
||||
// bm25 is originally negative and very small, we multiplied it by -1000000.0 in SQL
|
||||
// to make it positive and human-readable.
|
||||
score := row.Score
|
||||
|
||||
logger.GetLogger(ctx).Infof("[SQLite] keywordsRetrieve: #%d chunk_id=%s, score=%.4f, content_preview=%.60s",
|
||||
i+1, row.ChunkID, score, row.Content)
|
||||
|
||||
items[i] = &types.IndexWithScore{
|
||||
ID: fmt.Sprintf("%d", row.ID),
|
||||
SourceID: row.SourceID,
|
||||
SourceType: types.SourceType(row.SourceType),
|
||||
ChunkID: row.ChunkID,
|
||||
KnowledgeID: row.KnowledgeID,
|
||||
KnowledgeBaseID: row.KnowledgeBaseID,
|
||||
TagID: row.TagID,
|
||||
Content: row.Content,
|
||||
Score: score,
|
||||
MatchType: types.MatchTypeKeywords,
|
||||
}
|
||||
}
|
||||
|
||||
return []*types.RetrieveResult{{
|
||||
Results: items,
|
||||
RetrieverEngineType: types.SQLiteRetrieverEngineType,
|
||||
RetrieverType: types.KeywordsRetrieverType,
|
||||
}}, nil
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) vectorRetrieve(ctx context.Context, params types.RetrieveParams) ([]*types.RetrieveResult, error) {
|
||||
if len(params.Embedding) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
dim := len(params.Embedding)
|
||||
if err := r.ensureVecTable(dim); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
queryBlob, err := sqlite_vec.SerializeFloat32(params.Embedding)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("serialize query vector failed: %w", err)
|
||||
}
|
||||
|
||||
tbl := vecTableName(dim)
|
||||
|
||||
// ⚠️ sqlite-vec 要求必须有 k = ?
|
||||
vecSQL := fmt.Sprintf(`
|
||||
SELECT v.rowid, v.distance,
|
||||
e.source_id, e.source_type, e.chunk_id,
|
||||
e.knowledge_id, e.knowledge_base_id,
|
||||
e.tag_id, e.content
|
||||
FROM %s v
|
||||
JOIN lite_embeddings e ON e.id = v.rowid
|
||||
WHERE v.embedding MATCH ?
|
||||
AND k = ?
|
||||
AND v.rowid IN (
|
||||
SELECT filtered.id
|
||||
FROM lite_embeddings filtered
|
||||
WHERE (filtered.is_enabled IS NULL OR filtered.is_enabled = 1)
|
||||
`, tbl)
|
||||
|
||||
args := []interface{}{
|
||||
queryBlob,
|
||||
params.TopK, // 这里就是 k
|
||||
}
|
||||
|
||||
// 追加过滤条件
|
||||
for _, wp := range buildFilterWhere(params, "filtered") {
|
||||
vecSQL += " AND " + wp.clause
|
||||
args = append(args, wp.args...)
|
||||
}
|
||||
|
||||
// ⚠️ 这里仍然建议加 ORDER BY,虽然 vec0 已经按距离返回
|
||||
vecSQL += ") ORDER BY v.distance ASC"
|
||||
|
||||
type row struct {
|
||||
Rowid uint
|
||||
Distance float64
|
||||
SourceID string
|
||||
SourceType int
|
||||
ChunkID string
|
||||
KnowledgeID string
|
||||
KnowledgeBaseID string
|
||||
TagID string
|
||||
Content string
|
||||
}
|
||||
|
||||
var rows []row
|
||||
if err := r.db.WithContext(ctx).
|
||||
Raw(vecSQL, args...).
|
||||
Scan(&rows).Error; err != nil {
|
||||
return nil, fmt.Errorf("sqlite-vec query failed: %w", err)
|
||||
}
|
||||
|
||||
logger.GetLogger(ctx).Infof("[SQLite] vectorRetrieve: query_dim=%d, threshold=%.4f, matched=%d rows", dim, params.Threshold, len(rows))
|
||||
|
||||
items := make([]*types.IndexWithScore, 0, len(rows))
|
||||
|
||||
for i, v := range rows {
|
||||
// cosine distance = 1 - cosine_similarity
|
||||
score := 1 - v.Distance
|
||||
if params.Threshold > 0 && score < params.Threshold {
|
||||
continue
|
||||
}
|
||||
|
||||
logger.GetLogger(ctx).Infof("[SQLite] vectorRetrieve: #%d chunk_id=%s, distance=%.4f, score=%.4f, content_preview=%.60s",
|
||||
i+1, v.ChunkID, v.Distance, score, v.Content)
|
||||
|
||||
items = append(items, &types.IndexWithScore{
|
||||
ID: fmt.Sprintf("%d", v.Rowid),
|
||||
SourceID: v.SourceID,
|
||||
SourceType: types.SourceType(v.SourceType),
|
||||
ChunkID: v.ChunkID,
|
||||
KnowledgeID: v.KnowledgeID,
|
||||
KnowledgeBaseID: v.KnowledgeBaseID,
|
||||
TagID: v.TagID,
|
||||
Content: v.Content,
|
||||
Score: score,
|
||||
MatchType: types.MatchTypeEmbedding,
|
||||
})
|
||||
}
|
||||
|
||||
return []*types.RetrieveResult{{
|
||||
Results: items,
|
||||
RetrieverEngineType: types.SQLiteRetrieverEngineType,
|
||||
RetrieverType: types.VectorRetrieverType,
|
||||
}}, nil
|
||||
}
|
||||
|
||||
// --- Internal helpers ---
|
||||
|
||||
func toSQLiteEmbedding(info *types.IndexInfo) *sqliteEmbedding {
|
||||
enabled := info.IsEnabled
|
||||
return &sqliteEmbedding{
|
||||
SourceID: info.SourceID,
|
||||
SourceType: int(info.SourceType),
|
||||
ChunkID: info.ChunkID,
|
||||
KnowledgeID: info.KnowledgeID,
|
||||
KnowledgeBaseID: info.KnowledgeBaseID,
|
||||
TagID: info.TagID,
|
||||
Content: common.CleanInvalidUTF8(info.Content),
|
||||
Dimension: 0,
|
||||
IsEnabled: &enabled,
|
||||
}
|
||||
}
|
||||
|
||||
func extractEmbedding(params map[string]any, sourceID string) []float32 {
|
||||
if params == nil {
|
||||
return nil
|
||||
}
|
||||
embMap, ok := params["embedding"].(map[string][]float32)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return embMap[sourceID]
|
||||
}
|
||||
|
||||
// insertVec writes a row's vector through db. The vec0 table for dim must
|
||||
// already exist (ensureVecTable), since db may be a transaction. Failures are
|
||||
// returned so the caller's transaction rolls back instead of committing a
|
||||
// chunk row whose vector row was dropped.
|
||||
func (r *sqliteRepository) insertVec(db *gorm.DB, rowID uint, dim int, emb []float32) error {
|
||||
if rowID == 0 {
|
||||
return errors.New("[SQLite] cannot insert a vector row without a row id")
|
||||
}
|
||||
blob, err := sqlite_vec.SerializeFloat32(emb)
|
||||
if err != nil {
|
||||
return fmt.Errorf("[SQLite] failed to serialize embedding of row %d: %w", rowID, err)
|
||||
}
|
||||
tbl := vecTableName(dim)
|
||||
if err := db.Exec(
|
||||
fmt.Sprintf("INSERT INTO %s(rowid, embedding) VALUES (?, ?)", tbl), rowID, blob,
|
||||
).Error; err != nil {
|
||||
return fmt.Errorf("[SQLite] failed to insert vector row %d into %s: %w", rowID, tbl, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// deleteRowsAndVecs removes the vec0 and FTS copies of the given rows. Every
|
||||
// failure is returned: deleting only the lite_embeddings rows would leave the
|
||||
// retrieval indexes holding rows that no longer exist.
|
||||
func (r *sqliteRepository) deleteRowsAndVecs(db *gorm.DB, rows []sqliteEmbedding) error {
|
||||
dimIDs := make(map[int][]uint)
|
||||
for _, row := range rows {
|
||||
if row.Dimension > 0 {
|
||||
dimIDs[row.Dimension] = append(dimIDs[row.Dimension], row.ID)
|
||||
}
|
||||
}
|
||||
for dim, ids := range dimIDs {
|
||||
if !r.hasVecTable(dim) {
|
||||
continue
|
||||
}
|
||||
tbl := vecTableName(dim)
|
||||
for _, id := range ids {
|
||||
if err := db.Exec(fmt.Sprintf("DELETE FROM %s WHERE rowid = ?", tbl), id).Error; err != nil {
|
||||
return fmt.Errorf("[SQLite] failed to delete vector row %d from %s: %w", id, tbl, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if r.ftsUnavailable {
|
||||
return nil
|
||||
}
|
||||
for _, row := range rows {
|
||||
if err := db.Exec("DELETE FROM lite_embeddings_fts WHERE rowid = ?", row.ID).Error; err != nil {
|
||||
return fmt.Errorf("[SQLite] failed to delete keyword index row %d: %w", row.ID, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// copyVec duplicates a vector row for a copied chunk. It reports an error when
|
||||
// the destination table cannot be prepared or the source row has no vector
|
||||
// row, so a clone cannot silently end up without vectors.
|
||||
func (r *sqliteRepository) copyVec(ctx context.Context, srcID, dstID uint, dim int) error {
|
||||
if err := r.ensureVecTable(dim); err != nil {
|
||||
return err
|
||||
}
|
||||
tbl := vecTableName(dim)
|
||||
result := r.db.WithContext(ctx).Exec(fmt.Sprintf(
|
||||
"INSERT INTO %s(rowid, embedding) SELECT ?, embedding FROM %s WHERE rowid = ?",
|
||||
tbl, tbl,
|
||||
), dstID, srcID)
|
||||
if result.Error != nil {
|
||||
r.unmarkVecTable(dim)
|
||||
return fmt.Errorf("[SQLite] failed to copy vector row %d -> %d in %s: %w",
|
||||
srcID, dstID, tbl, result.Error)
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
return fmt.Errorf("[SQLite] source row %d has no vector row in %s", srcID, tbl)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// syncFTS5Insert mirrors a lite_embeddings row into the keyword index. The
|
||||
// error is returned so the caller's transaction rolls back instead of leaving
|
||||
// the chunk unfindable by both retrieval paths.
|
||||
func (r *sqliteRepository) syncFTS5Insert(db *gorm.DB, row *sqliteEmbedding) error {
|
||||
if r.ftsUnavailable {
|
||||
return nil
|
||||
}
|
||||
if row.ID == 0 {
|
||||
return fmt.Errorf("[SQLite] cannot index chunk %s: row has no id", row.SourceID)
|
||||
}
|
||||
if err := db.Exec(fts5InsertSQL, row.ID, tokenizeCJKBigram(row.Content), row.SourceID, row.ChunkID,
|
||||
row.KnowledgeID, row.KnowledgeBaseID).Error; err != nil {
|
||||
return fmt.Errorf("[SQLite] failed to insert keyword index row for %s: %w", row.SourceID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type whereClause struct {
|
||||
clause string
|
||||
args []interface{}
|
||||
}
|
||||
|
||||
func buildFilterWhere(params types.RetrieveParams, tableAlias string) []whereClause {
|
||||
var parts []whereClause
|
||||
if len(params.KnowledgeBaseIDs) > 0 {
|
||||
parts = append(parts, whereClause{
|
||||
clause: tableAlias + ".knowledge_base_id IN (" + placeholders(len(params.KnowledgeBaseIDs)) + ")",
|
||||
args: toInterfaceSlice(params.KnowledgeBaseIDs),
|
||||
})
|
||||
}
|
||||
if len(params.KnowledgeIDs) > 0 {
|
||||
parts = append(parts, whereClause{
|
||||
clause: tableAlias + ".knowledge_id IN (" + placeholders(len(params.KnowledgeIDs)) + ")",
|
||||
args: toInterfaceSlice(params.KnowledgeIDs),
|
||||
})
|
||||
}
|
||||
if len(params.TagIDs) > 0 {
|
||||
parts = append(parts, whereClause{
|
||||
clause: tableAlias + ".tag_id IN (" + placeholders(len(params.TagIDs)) + ")",
|
||||
args: toInterfaceSlice(params.TagIDs),
|
||||
})
|
||||
}
|
||||
return parts
|
||||
}
|
||||
|
||||
func placeholders(n int) string {
|
||||
p := make([]string, n)
|
||||
for i := range p {
|
||||
p[i] = "?"
|
||||
}
|
||||
return strings.Join(p, ",")
|
||||
}
|
||||
|
||||
func toInterfaceSlice(ss []string) []interface{} {
|
||||
out := make([]interface{}, len(ss))
|
||||
for i, s := range ss {
|
||||
out[i] = s
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// tokenizeCJKBigram splits continuous CJK character sequences into overlapping bigrams.
|
||||
// Non-CJK words are kept intact. This approach maximizes recall for CJK search.
|
||||
func tokenizeCJKBigram(text string) string {
|
||||
var parts []string
|
||||
var currentCJK []rune
|
||||
var currentNonCJK strings.Builder
|
||||
|
||||
flushCJK := func() {
|
||||
if len(currentCJK) == 0 {
|
||||
return
|
||||
}
|
||||
if len(currentCJK) == 1 {
|
||||
parts = append(parts, string(currentCJK[0]))
|
||||
} else {
|
||||
for i := 0; i < len(currentCJK)-1; i++ {
|
||||
parts = append(parts, string(currentCJK[i])+string(currentCJK[i+1]))
|
||||
}
|
||||
}
|
||||
currentCJK = currentCJK[:0]
|
||||
}
|
||||
|
||||
flushNonCJK := func() {
|
||||
if currentNonCJK.Len() > 0 {
|
||||
parts = append(parts, currentNonCJK.String())
|
||||
currentNonCJK.Reset()
|
||||
}
|
||||
}
|
||||
|
||||
for _, r := range text {
|
||||
// unicode.Han covers Chinese characters
|
||||
if unicode.Is(unicode.Han, r) {
|
||||
flushNonCJK()
|
||||
currentCJK = append(currentCJK, r)
|
||||
} else if unicode.IsSpace(r) || unicode.IsPunct(r) || unicode.IsSymbol(r) {
|
||||
// Delimiters
|
||||
flushCJK()
|
||||
flushNonCJK()
|
||||
} else {
|
||||
// Alphanumeric or other languages
|
||||
flushCJK()
|
||||
currentNonCJK.WriteRune(r)
|
||||
}
|
||||
}
|
||||
flushCJK()
|
||||
flushNonCJK()
|
||||
|
||||
return strings.Join(parts, " ")
|
||||
}
|
||||
|
||||
// sanitizeFTS5Query builds an FTS5 query from user input by applying bigram tokenization.
|
||||
func sanitizeFTS5Query(q string) string {
|
||||
q = strings.TrimSpace(q)
|
||||
if q == "" {
|
||||
return q
|
||||
}
|
||||
|
||||
// Tokenize input query with bigrams (same as during indexing)
|
||||
tokenized := tokenizeCJKBigram(q)
|
||||
fields := strings.Fields(tokenized)
|
||||
|
||||
var parts []string
|
||||
for _, f := range fields {
|
||||
if f == "" {
|
||||
continue
|
||||
}
|
||||
term := `"` + strings.ReplaceAll(f, `"`, `""`) + `"`
|
||||
// The index holds CJK text as bigrams, so a lone Han character
|
||||
// (the 股 of "A股") was never a token; match bigrams starting with it.
|
||||
if runes := []rune(f); len(runes) == 1 && unicode.Is(unicode.Han, runes[0]) {
|
||||
term += "*"
|
||||
}
|
||||
parts = append(parts, term)
|
||||
}
|
||||
|
||||
if len(parts) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Use OR because we want fuzzy match across multiple bigrams/words.
|
||||
// Only the content column is searched: the FTS table also indexes
|
||||
// source, chunk, knowledge and KB IDs, so a query for "2023" could match
|
||||
// a UUID fragment.
|
||||
return "content : (" + strings.Join(parts, " OR ") + ")"
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package sqlite
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
sqlite_vec "github.com/asg017/sqlite-vec-go-bindings/cgo"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
gormsqlite "gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var registerSQLiteVec sync.Once
|
||||
|
||||
func newSQLiteRetrieverTestRepository(t *testing.T) *sqliteRepository {
|
||||
t.Helper()
|
||||
registerSQLiteVec.Do(sqlite_vec.Auto)
|
||||
|
||||
dbName := strings.NewReplacer("/", "_", " ", "_").Replace(t.Name())
|
||||
db, err := gorm.Open(gormsqlite.Open(fmt.Sprintf("file:%s?mode=memory&cache=shared", dbName)), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
|
||||
sqlDB, err := db.DB()
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() {
|
||||
require.NoError(t, sqlDB.Close())
|
||||
})
|
||||
|
||||
repository, ok := NewSQLiteRetrieveEngineRepository(db).(*sqliteRepository)
|
||||
require.True(t, ok)
|
||||
return repository
|
||||
}
|
||||
|
||||
func saveSQLiteTestVector(t *testing.T, repository *sqliteRepository, info *types.IndexInfo, embedding []float32) {
|
||||
t.Helper()
|
||||
require.NoError(t, repository.Save(context.Background(), info, map[string]any{
|
||||
"embedding": map[string][]float32{info.SourceID: embedding},
|
||||
}))
|
||||
}
|
||||
|
||||
func sqliteTestIndex(chunkID, knowledgeBaseID, knowledgeID, tagID string, enabled bool) *types.IndexInfo {
|
||||
return &types.IndexInfo{
|
||||
Content: chunkID,
|
||||
SourceID: "source-" + chunkID,
|
||||
SourceType: types.ChunkSourceType,
|
||||
ChunkID: chunkID,
|
||||
KnowledgeID: knowledgeID,
|
||||
KnowledgeBaseID: knowledgeBaseID,
|
||||
TagID: tagID,
|
||||
IsEnabled: enabled,
|
||||
}
|
||||
}
|
||||
|
||||
func TestVectorRetrieveFiltersBeforeTopK(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
blocker *types.IndexInfo
|
||||
configure func(*types.RetrieveParams)
|
||||
}{
|
||||
{
|
||||
name: "knowledge base",
|
||||
blocker: sqliteTestIndex("blocker", "kb-other", "knowledge-target", "tag-target", true),
|
||||
configure: func(params *types.RetrieveParams) {
|
||||
params.KnowledgeBaseIDs = []string{"kb-target"}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "knowledge",
|
||||
blocker: sqliteTestIndex("blocker", "kb-target", "knowledge-other", "tag-target", true),
|
||||
configure: func(params *types.RetrieveParams) {
|
||||
params.KnowledgeIDs = []string{"knowledge-target"}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "tag",
|
||||
blocker: sqliteTestIndex("blocker", "kb-target", "knowledge-target", "tag-other", true),
|
||||
configure: func(params *types.RetrieveParams) {
|
||||
params.TagIDs = []string{"tag-target"}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "enabled status",
|
||||
blocker: sqliteTestIndex("blocker", "kb-target", "knowledge-target", "tag-target", false),
|
||||
configure: func(_ *types.RetrieveParams) {},
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
repository := newSQLiteRetrieverTestRepository(t)
|
||||
saveSQLiteTestVector(t, repository, testCase.blocker, []float32{1, 0})
|
||||
saveSQLiteTestVector(t, repository,
|
||||
sqliteTestIndex("target", "kb-target", "knowledge-target", "tag-target", true),
|
||||
[]float32{0.8, 0.6},
|
||||
)
|
||||
|
||||
params := types.RetrieveParams{
|
||||
Embedding: []float32{1, 0},
|
||||
TopK: 1,
|
||||
RetrieverType: types.VectorRetrieverType,
|
||||
}
|
||||
testCase.configure(¶ms)
|
||||
|
||||
results, err := repository.vectorRetrieve(context.Background(), params)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, results, 1)
|
||||
require.Len(t, results[0].Results, 1)
|
||||
assert.Equal(t, "target", results[0].Results[0].ChunkID)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestVectorRetrieveZeroThresholdDoesNotFilter(t *testing.T) {
|
||||
repository := newSQLiteRetrieverTestRepository(t)
|
||||
saveSQLiteTestVector(t, repository,
|
||||
sqliteTestIndex("anti-correlated", "kb-target", "knowledge-target", "tag-target", true),
|
||||
[]float32{-1, 0},
|
||||
)
|
||||
|
||||
results, err := repository.vectorRetrieve(context.Background(), types.RetrieveParams{
|
||||
Embedding: []float32{1, 0},
|
||||
KnowledgeBaseIDs: []string{"kb-target"},
|
||||
TopK: 1,
|
||||
Threshold: 0,
|
||||
RetrieverType: types.VectorRetrieverType,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, results, 1)
|
||||
require.Len(t, results[0].Results, 1)
|
||||
assert.Equal(t, "anti-correlated", results[0].Results[0].ChunkID)
|
||||
assert.Less(t, results[0].Results[0].Score, 0.0)
|
||||
}
|
||||
|
||||
func TestVectorRetrieveAppliesSimilarityThreshold(t *testing.T) {
|
||||
repository := newSQLiteRetrieverTestRepository(t)
|
||||
saveSQLiteTestVector(t, repository,
|
||||
sqliteTestIndex("below-threshold", "kb-target", "knowledge-target", "tag-target", true),
|
||||
[]float32{0.5, 0.8660254},
|
||||
)
|
||||
|
||||
results, err := repository.vectorRetrieve(context.Background(), types.RetrieveParams{
|
||||
Embedding: []float32{1, 0},
|
||||
KnowledgeBaseIDs: []string{"kb-target"},
|
||||
TopK: 1,
|
||||
Threshold: 0.75,
|
||||
RetrieverType: types.VectorRetrieverType,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, results, 1)
|
||||
assert.Empty(t, results[0].Results)
|
||||
}
|
||||
|
||||
func TestRetrieveReturnsVectorQueryError(t *testing.T) {
|
||||
repository := newSQLiteRetrieverTestRepository(t)
|
||||
saveSQLiteTestVector(t, repository,
|
||||
sqliteTestIndex("chunk", "kb-target", "knowledge-target", "tag-target", true),
|
||||
[]float32{1, 0},
|
||||
)
|
||||
require.NoError(t, repository.db.Exec("DROP TABLE "+vecTableName(2)).Error)
|
||||
|
||||
results, err := repository.Retrieve(context.Background(), types.RetrieveParams{
|
||||
Embedding: []float32{1, 0},
|
||||
TopK: 1,
|
||||
RetrieverType: types.VectorRetrieverType,
|
||||
})
|
||||
require.Error(t, err)
|
||||
assert.Nil(t, results)
|
||||
assert.Contains(t, err.Error(), "sqlite-vec query failed")
|
||||
}
|
||||
|
||||
func TestRetrieveReturnsKeywordQueryError(t *testing.T) {
|
||||
repository := newSQLiteRetrieverTestRepository(t)
|
||||
require.NoError(t, repository.db.Exec("DROP TABLE IF EXISTS lite_embeddings_fts").Error)
|
||||
|
||||
results, err := repository.Retrieve(context.Background(), types.RetrieveParams{
|
||||
Query: "missing fts table",
|
||||
TopK: 1,
|
||||
RetrieverType: types.KeywordsRetrieverType,
|
||||
})
|
||||
require.Error(t, err)
|
||||
assert.Nil(t, results)
|
||||
assert.Contains(t, err.Error(), "FTS5 query failed")
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
package sqlite
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func vectorSearch(t *testing.T, repository *sqliteRepository, embedding []float32) []*types.IndexWithScore {
|
||||
t.Helper()
|
||||
results, err := repository.vectorRetrieve(context.Background(), types.RetrieveParams{
|
||||
Embedding: embedding,
|
||||
TopK: 10,
|
||||
RetrieverType: types.VectorRetrieverType,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, results, 1)
|
||||
return results[0].Results
|
||||
}
|
||||
|
||||
func keywordSearch(t *testing.T, repository *sqliteRepository, query string) []*types.IndexWithScore {
|
||||
t.Helper()
|
||||
results, err := repository.keywordsRetrieve(context.Background(), types.RetrieveParams{
|
||||
Query: query,
|
||||
TopK: 10,
|
||||
RetrieverType: types.KeywordsRetrieverType,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, results, 1)
|
||||
return results[0].Results
|
||||
}
|
||||
|
||||
func TestBatchSaveReplacesExistingSource(t *testing.T) {
|
||||
repository := newSQLiteRetrieverTestRepository(t)
|
||||
info := sqliteTestIndex("faq", "kb", "knowledge", "", true)
|
||||
info.Content = "oldanswer"
|
||||
saveSQLiteTestVector(t, repository, info, []float32{1, 0})
|
||||
|
||||
edited := *info
|
||||
edited.Content = "newanswer"
|
||||
saveSQLiteTestVector(t, repository, &edited, []float32{0, 1})
|
||||
|
||||
var count int64
|
||||
require.NoError(t, repository.db.Model(&sqliteEmbedding{}).Count(&count).Error)
|
||||
assert.Equal(t, int64(1), count, "re-indexing a source must replace its row")
|
||||
|
||||
hits := vectorSearch(t, repository, []float32{0, 1})
|
||||
require.Len(t, hits, 1)
|
||||
assert.Equal(t, "newanswer", hits[0].Content)
|
||||
assert.InDelta(t, 1.0, hits[0].Score, 1e-3, "the vector must be the re-indexed one")
|
||||
|
||||
if !repository.db.Migrator().HasTable("lite_embeddings_fts") {
|
||||
t.Log("FTS5 unavailable (build without sqlite_fts5); skipping keyword checks")
|
||||
return
|
||||
}
|
||||
assert.Empty(t, keywordSearch(t, repository, "oldanswer"), "stale FTS entry must be gone")
|
||||
require.Len(t, keywordSearch(t, repository, "newanswer"), 1)
|
||||
}
|
||||
|
||||
func TestBatchSaveKeepsVectorsAlignedWhenSomeSourcesExist(t *testing.T) {
|
||||
repository := newSQLiteRetrieverTestRepository(t)
|
||||
existing := sqliteTestIndex("existing", "kb", "knowledge", "", true)
|
||||
saveSQLiteTestVector(t, repository, existing, []float32{1, 0})
|
||||
|
||||
fresh := sqliteTestIndex("fresh", "kb", "knowledge", "", true)
|
||||
require.NoError(t, repository.BatchSave(context.Background(), []*types.IndexInfo{existing, fresh}, map[string]any{
|
||||
"embedding": map[string][]float32{
|
||||
existing.SourceID: {1, 0},
|
||||
fresh.SourceID: {0, 1},
|
||||
},
|
||||
}))
|
||||
|
||||
hits := vectorSearch(t, repository, []float32{0, 1})
|
||||
require.Len(t, hits, 2)
|
||||
assert.Equal(t, "fresh", hits[0].ChunkID, "the fresh row must carry its own vector")
|
||||
assert.InDelta(t, 1.0, hits[0].Score, 1e-3)
|
||||
}
|
||||
|
||||
func TestBatchSaveKeepsLastDuplicateInBatch(t *testing.T) {
|
||||
repository := newSQLiteRetrieverTestRepository(t)
|
||||
first := sqliteTestIndex("chunk", "kb", "knowledge", "", true)
|
||||
first.Content = "firstversion"
|
||||
second := *first
|
||||
second.Content = "secondversion"
|
||||
require.NoError(t, repository.BatchSave(context.Background(), []*types.IndexInfo{first, &second}, map[string]any{
|
||||
"embedding": map[string][]float32{first.SourceID: {1, 0}},
|
||||
}))
|
||||
|
||||
hits := vectorSearch(t, repository, []float32{1, 0})
|
||||
require.Len(t, hits, 1)
|
||||
assert.Equal(t, "secondversion", hits[0].Content)
|
||||
}
|
||||
|
||||
func TestConcurrentBatchSaveNewDimensions(t *testing.T) {
|
||||
repository := newSQLiteRetrieverTestRepository(t)
|
||||
sqlDB, err := repository.db.DB()
|
||||
require.NoError(t, err)
|
||||
// Production runs SQLite on a single connection.
|
||||
sqlDB.SetMaxOpenConns(1)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
errs := make(chan error, 16)
|
||||
for i := range 16 {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
dim := 2 + i%4
|
||||
info := sqliteTestIndex(fmt.Sprintf("chunk-%d", i), "kb", "knowledge", "", true)
|
||||
embedding := make([]float32, dim)
|
||||
embedding[0] = 1
|
||||
errs <- repository.BatchSave(context.Background(), []*types.IndexInfo{info}, map[string]any{
|
||||
"embedding": map[string][]float32{info.SourceID: embedding},
|
||||
})
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
for err := range errs {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
for dim := 2; dim < 6; dim++ {
|
||||
assert.True(t, repository.hasVecTable(dim))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCopyIndicesCopiesEveryRowOfAChunk(t *testing.T) {
|
||||
repository := newSQLiteRetrieverTestRepository(t)
|
||||
chunk := sqliteTestIndex("src-chunk", "kb-src", "knowledge-src", "", true)
|
||||
chunk.SourceID = "src-chunk"
|
||||
question := sqliteTestIndex("src-chunk", "kb-src", "knowledge-src", "", false)
|
||||
question.SourceID = "src-chunk-q1"
|
||||
question.Content = "generated question"
|
||||
require.NoError(t, repository.BatchSave(context.Background(), []*types.IndexInfo{chunk, question}, map[string]any{
|
||||
"embedding": map[string][]float32{
|
||||
chunk.SourceID: {1, 0},
|
||||
question.SourceID: {0, 1},
|
||||
},
|
||||
}))
|
||||
|
||||
require.NoError(t, repository.CopyIndices(context.Background(), "kb-src",
|
||||
map[string]string{"knowledge-src": "knowledge-dst"},
|
||||
map[string]string{"src-chunk": "dst-chunk"},
|
||||
"kb-dst", 2, string(types.KnowledgeTypeManual),
|
||||
))
|
||||
|
||||
var copied []sqliteEmbedding
|
||||
require.NoError(t, repository.db.Where("knowledge_base_id = ?", "kb-dst").Order("source_id").Find(&copied).Error)
|
||||
require.Len(t, copied, 2)
|
||||
assert.Equal(t, "dst-chunk", copied[0].SourceID)
|
||||
assert.True(t, *copied[0].IsEnabled)
|
||||
assert.Equal(t, "dst-chunk-q1", copied[1].SourceID)
|
||||
assert.False(t, *copied[1].IsEnabled, "enabled state must be copied")
|
||||
for _, row := range copied {
|
||||
assert.Equal(t, "dst-chunk", row.ChunkID)
|
||||
assert.Equal(t, "knowledge-dst", row.KnowledgeID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnableImageChunkIndexesRepairsOnlyEnabledImageChunks(t *testing.T) {
|
||||
repository := newSQLiteRetrieverTestRepository(t)
|
||||
require.NoError(t, repository.db.Exec(
|
||||
`CREATE TABLE chunks (id TEXT PRIMARY KEY, chunk_type TEXT, is_enabled BOOLEAN)`).Error)
|
||||
require.NoError(t, repository.db.Exec(`INSERT INTO chunks (id, chunk_type, is_enabled) VALUES
|
||||
('ocr', 'image_ocr', 1), ('caption', 'image_caption', 1),
|
||||
('ocr-off', 'image_ocr', 0), ('text-off', 'text', 1)`).Error)
|
||||
for _, id := range []string{"ocr", "caption", "ocr-off", "text-off"} {
|
||||
saveSQLiteTestVector(t, repository, sqliteTestIndex(id, "kb", "knowledge", "", false), []float32{1, 0})
|
||||
}
|
||||
|
||||
enableImageChunkIndexes(repository.db)
|
||||
|
||||
enabled := map[string]bool{}
|
||||
var rows []sqliteEmbedding
|
||||
require.NoError(t, repository.db.Find(&rows).Error)
|
||||
for _, row := range rows {
|
||||
enabled[row.ChunkID] = *row.IsEnabled
|
||||
}
|
||||
assert.Equal(t, map[string]bool{
|
||||
"ocr": true, "caption": true, "ocr-off": false, "text-off": false,
|
||||
}, enabled)
|
||||
}
|
||||
|
||||
// Replacing a source is atomic: when the insert fails, the old row stays.
|
||||
func TestBatchSaveKeepsOldRowWhenInsertFails(t *testing.T) {
|
||||
repository := newSQLiteRetrieverTestRepository(t)
|
||||
info := sqliteTestIndex("faq", "kb", "knowledge", "", true)
|
||||
info.Content = "old answer"
|
||||
saveSQLiteTestVector(t, repository, info, []float32{1, 0})
|
||||
|
||||
require.NoError(t, repository.db.Exec(`CREATE TRIGGER reject_boom BEFORE INSERT ON lite_embeddings
|
||||
WHEN NEW.content = 'boom' BEGIN SELECT RAISE(ABORT, 'rejected'); END`).Error)
|
||||
edited := *info
|
||||
edited.Content = "boom"
|
||||
require.Error(t, repository.BatchSave(context.Background(), []*types.IndexInfo{&edited}, map[string]any{
|
||||
"embedding": map[string][]float32{edited.SourceID: {0, 1}},
|
||||
}))
|
||||
|
||||
var rows []sqliteEmbedding
|
||||
require.NoError(t, repository.db.Find(&rows).Error)
|
||||
require.Len(t, rows, 1)
|
||||
assert.Equal(t, "old answer", rows[0].Content)
|
||||
hits := vectorSearch(t, repository, []float32{1, 0})
|
||||
require.Len(t, hits, 1, "the old vector must survive the failed replace")
|
||||
}
|
||||
Reference in new issue
Block a user