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,503 @@
|
||||
package weaviate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"maps"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
sdk "github.com/weaviate/weaviate-go-client/v5/weaviate"
|
||||
)
|
||||
|
||||
const copyTestCollection = "Copy_64"
|
||||
|
||||
// cursorConflictMessage is what weaviate v1.37.3 answers when a Get combines a
|
||||
// filter with the cursor API (entities/filters/cursor_validator.go).
|
||||
const cursorConflictMessage = "where cannot be set with after and limit parameters"
|
||||
|
||||
var (
|
||||
afterArgPattern = regexp.MustCompile(`after:\s*"([^"]*)"`)
|
||||
limitArgPattern = regexp.MustCompile(`limit:\s*(\d+)`)
|
||||
chunkArgPattern = regexp.MustCompile(`path: \["chunk_id"\] valueText: \[([^\]]*)\]`)
|
||||
quotedPattern = regexp.MustCompile(`"([^"]*)"`)
|
||||
)
|
||||
|
||||
// copySourceRow is one source vector, in the shape a GraphQL Get answers with.
|
||||
func copySourceRow(id, chunkID, sourceID string) map[string]any {
|
||||
return map[string]any{
|
||||
fieldContent: "content of " + sourceID,
|
||||
fieldSourceID: sourceID,
|
||||
fieldSourceType: 1,
|
||||
fieldChunkID: chunkID,
|
||||
fieldKnowledgeID: "know-1",
|
||||
fieldKnowledgeBaseID: "kb-src",
|
||||
fieldTagID: "",
|
||||
"_additional": map[string]any{"id": id, "vector": []any{0.5, 0.25}},
|
||||
}
|
||||
}
|
||||
|
||||
// copyWrittenObject is one object the copy sent to the batch endpoint.
|
||||
type copyWrittenObject struct {
|
||||
sourceID string
|
||||
targetChunkID string
|
||||
}
|
||||
|
||||
// copyPageServer stands in for a Weaviate data node holding the source
|
||||
// vectors. It answers Get the way the real one does - with the rows whose
|
||||
// chunk_id is in the ContainsAny list the query asked for, cut off at the
|
||||
// query's limit - and it validates the cursor API the way the real one does,
|
||||
// so a query that combines `where` with `after` fails here exactly as it fails
|
||||
// in production.
|
||||
type copyPageServer struct {
|
||||
mu sync.Mutex
|
||||
// rows holds each chunk's vectors: one for the chunk content plus one per
|
||||
// generated question, all sharing the chunk_id.
|
||||
rows map[string][]map[string]any
|
||||
order []string
|
||||
|
||||
// queryLimit is the server's QUERY_MAXIMUM_RESULTS; 0 means no refusal.
|
||||
queryLimit int
|
||||
// ignoreChunkFilter answers every query with the same page, the way a
|
||||
// source whose pages repeat themselves behaves.
|
||||
ignoreChunkFilter bool
|
||||
// queryError, when set, is the GraphQL error every Get is answered with.
|
||||
queryError string
|
||||
// omitData answers every Get with a data object that carries no Get key.
|
||||
omitData bool
|
||||
// omitCollection answers with a Get object that carries no key for the
|
||||
// queried collection.
|
||||
omitCollection bool
|
||||
|
||||
queries int
|
||||
limits []int
|
||||
requested [][]string
|
||||
rejected []string
|
||||
batches int
|
||||
written []copyWrittenObject
|
||||
unexpected []string
|
||||
}
|
||||
|
||||
// copyTestStore builds a source whose chunks hold the given vectors. Each
|
||||
// entry maps a chunk ID to its source IDs: the chunk's own content vector
|
||||
// first, then one per generated question.
|
||||
func copyTestStore(vectors map[string][]string) *copyPageServer {
|
||||
s := ©PageServer{rows: make(map[string][]map[string]any)}
|
||||
next := 0
|
||||
for _, chunkID := range slices.Sorted(maps.Keys(vectors)) {
|
||||
for _, sourceID := range vectors[chunkID] {
|
||||
s.rows[chunkID] = append(s.rows[chunkID], copySourceRow(copyTestUUID(next), chunkID, sourceID))
|
||||
next++
|
||||
}
|
||||
s.order = append(s.order, chunkID)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func copyTestUUID(i int) string {
|
||||
return fmt.Sprintf("00000000-0000-0000-0000-%012d", i)
|
||||
}
|
||||
|
||||
// copyTestChunkMap maps size chunks onto target chunks.
|
||||
func copyTestChunkMap(size int) map[string]string {
|
||||
m := make(map[string]string, size)
|
||||
for i := range size {
|
||||
m[fmt.Sprintf("chunk-%d", i)] = fmt.Sprintf("target-chunk-%d", i)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// copyTestSingleVectorChunks builds a source with one vector per named chunk.
|
||||
func copyTestSingleVectorChunks(chunkIDs ...string) *copyPageServer {
|
||||
vectors := make(map[string][]string, len(chunkIDs))
|
||||
for _, chunkID := range chunkIDs {
|
||||
vectors[chunkID] = []string{chunkID}
|
||||
}
|
||||
return copyTestStore(vectors)
|
||||
}
|
||||
|
||||
// serve starts an httptest server for s and returns a repository pointed at
|
||||
// it. The copy's own query limit is left at its default; tests that need the
|
||||
// truncation path lower it on the returned repository.
|
||||
func (s *copyPageServer) serve(t *testing.T) *weaviateRepository {
|
||||
t.Helper()
|
||||
server := httptest.NewServer(http.HandlerFunc(s.handle))
|
||||
t.Cleanup(server.Close)
|
||||
client, err := sdk.NewClient(sdk.Config{Scheme: "http", Host: strings.TrimPrefix(server.URL, "http://")})
|
||||
require.NoError(t, err)
|
||||
return &weaviateRepository{client: client, collectionBaseName: "Copy"}
|
||||
}
|
||||
|
||||
func (s *copyPageServer) handle(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch {
|
||||
case r.Method == http.MethodPost && r.URL.Path == "/v1/graphql":
|
||||
var body struct {
|
||||
Query string `json:"query"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(s.resolve(body.Query))
|
||||
case r.Method == http.MethodPost && r.URL.Path == "/v1/batch/objects":
|
||||
var body struct {
|
||||
Objects []struct {
|
||||
Properties map[string]any `json:"properties"`
|
||||
} `json:"objects"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.batches++
|
||||
for _, obj := range body.Objects {
|
||||
s.written = append(s.written, copyWrittenObject{
|
||||
sourceID: fmt.Sprint(obj.Properties[fieldSourceID]),
|
||||
targetChunkID: fmt.Sprint(obj.Properties[fieldChunkID]),
|
||||
})
|
||||
}
|
||||
s.mu.Unlock()
|
||||
_, _ = w.Write([]byte(`[]`))
|
||||
case r.Method == http.MethodGet && r.URL.Path == "/v1/meta":
|
||||
_, _ = w.Write([]byte(`{"version":"1.37.3"}`))
|
||||
default:
|
||||
s.mu.Lock()
|
||||
s.unexpected = append(s.unexpected, r.Method+" "+r.URL.Path)
|
||||
s.mu.Unlock()
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}
|
||||
|
||||
// resolve answers one GraphQL Get the way Weaviate does. A query it refused
|
||||
// comes back as a successful call carrying an errors array, which is what the
|
||||
// copy has to read as a failure.
|
||||
func (s *copyPageServer) resolve(query string) map[string]any {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.queries++
|
||||
|
||||
limit := 0
|
||||
if match := limitArgPattern.FindStringSubmatch(query); match != nil {
|
||||
limit, _ = strconv.Atoi(match[1])
|
||||
}
|
||||
s.limits = append(s.limits, limit)
|
||||
|
||||
// The cursor API refuses a filtered query: a Get that asks for rows after a
|
||||
// cursor cannot also carry where and limit.
|
||||
if strings.Contains(query, "where:") {
|
||||
if afterArgPattern.MatchString(query) {
|
||||
s.rejected = append(s.rejected, query)
|
||||
return graphQLError("cursor api: invalid 'after' parameter: " + cursorConflictMessage)
|
||||
}
|
||||
}
|
||||
|
||||
switch {
|
||||
case s.queryError != "":
|
||||
return graphQLError(s.queryError)
|
||||
case s.omitData:
|
||||
return map[string]any{"data": map[string]any{}}
|
||||
case s.omitCollection:
|
||||
return map[string]any{"data": map[string]any{"Get": map[string]any{}}}
|
||||
}
|
||||
|
||||
if s.queryLimit > 0 && limit > s.queryLimit {
|
||||
return graphQLError(fmt.Sprintf(
|
||||
"query maximum results exceeded: the total limit calculated from the provided offset '0' "+
|
||||
"and limit '%d' exceeds the configured value for QUERY_MAXIMUM_RESULTS '%d'. "+
|
||||
"If you've supplied a negative offset or limit, this may be an underflow error",
|
||||
limit, s.queryLimit))
|
||||
}
|
||||
|
||||
chunkIDs := copyRequestedChunkIDs(query)
|
||||
s.requested = append(s.requested, chunkIDs)
|
||||
|
||||
order := chunkIDs
|
||||
if s.ignoreChunkFilter {
|
||||
order = s.order
|
||||
}
|
||||
rows := make([]any, 0, len(s.rows))
|
||||
for _, chunkID := range order {
|
||||
for _, row := range s.rows[chunkID] {
|
||||
rows = append(rows, row)
|
||||
}
|
||||
}
|
||||
if limit > 0 && len(rows) > limit {
|
||||
rows = rows[:limit]
|
||||
}
|
||||
return map[string]any{"data": map[string]any{"Get": map[string]any{copyTestCollection: rows}}}
|
||||
}
|
||||
|
||||
func graphQLError(message string) map[string]any {
|
||||
return map[string]any{"errors": []any{map[string]any{"message": message}}}
|
||||
}
|
||||
|
||||
// copyRequestedChunkIDs pulls the chunk_id ContainsAny values out of a query.
|
||||
func copyRequestedChunkIDs(query string) []string {
|
||||
match := chunkArgPattern.FindStringSubmatch(query)
|
||||
if match == nil {
|
||||
return nil
|
||||
}
|
||||
var ids []string
|
||||
for _, quoted := range quotedPattern.FindAllStringSubmatch(match[1], -1) {
|
||||
ids = append(ids, quoted[1])
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
func (s *copyPageServer) queryCount() int {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.queries
|
||||
}
|
||||
|
||||
func (s *copyPageServer) queryLimits() []int {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return slices.Clone(s.limits)
|
||||
}
|
||||
|
||||
func (s *copyPageServer) requestedBatches() [][]string {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
batches := make([][]string, 0, len(s.requested))
|
||||
for _, batch := range s.requested {
|
||||
batches = append(batches, slices.Clone(batch))
|
||||
}
|
||||
return batches
|
||||
}
|
||||
|
||||
func (s *copyPageServer) writtenObjects() []copyWrittenObject {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return slices.Clone(s.written)
|
||||
}
|
||||
|
||||
func (s *copyPageServer) summary() string {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return fmt.Sprintf("queries=%d limits=%v batches-requested=%v objects-written=%d refused-cursor-combos=%d",
|
||||
s.queries, s.limits, s.requested, len(s.written), len(s.rejected))
|
||||
}
|
||||
|
||||
// check states the invariants every copy test depends on: no Get ever combined
|
||||
// where with after, and every Get named the chunk IDs it wanted.
|
||||
func (s *copyPageServer) check(t *testing.T) {
|
||||
t.Helper()
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
assert.Empty(t, s.rejected, "a source query combined where with after; weaviate refuses that")
|
||||
assert.Empty(t, s.unexpected, "the copy called an endpoint it should not have")
|
||||
for i, batch := range s.requested {
|
||||
assert.NotEmpty(t, batch, "query %d did not name the chunks it wanted", i)
|
||||
}
|
||||
}
|
||||
|
||||
// copyTestRun copies mapping from the fake source and logs what the source saw.
|
||||
func copyTestRun(t *testing.T, source *copyPageServer, repo *weaviateRepository, mapping map[string]string) error {
|
||||
t.Helper()
|
||||
defer func() { t.Log("copy walk: " + source.summary()) }()
|
||||
defer source.check(t)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
return repo.CopyIndices(ctx, "kb-src", map[string]string{"know-1": "know-2"}, mapping, "kb-dst", 64, "doc")
|
||||
}
|
||||
|
||||
// CopyIndices has to read the source by the chunk IDs the mapping names. A
|
||||
// filtered Get that carries `after` is refused by Weaviate ("where cannot be
|
||||
// set with after and limit parameters"), which the cursor walk this replaces
|
||||
// provoked on its very first page, and the fake server refuses it the same way.
|
||||
func TestCopyIndicesQueriesByChunkIDWithoutACursor(t *testing.T) {
|
||||
const chunks = 130 // 64 + 64 + 2: more than one batch, one short batch
|
||||
source := copyTestSingleVectorChunks(keysOf(copyTestChunkMap(chunks))...)
|
||||
repo := source.serve(t)
|
||||
|
||||
require.NoError(t, copyTestRun(t, source, repo, copyTestChunkMap(chunks)))
|
||||
|
||||
assert.Equal(t, 3, source.queryCount(), "130 mapped chunks are read as three batches")
|
||||
assert.Equal(t, 130, len(source.writtenObjects()), "every mapped chunk must be copied")
|
||||
assert.ElementsMatch(t, []int{64, 64, 2}, batchSizes(source.requestedBatches()),
|
||||
"each read asks for one batch of the mapping")
|
||||
|
||||
var read []string
|
||||
for _, batch := range source.requestedBatches() {
|
||||
assert.True(t, slices.IsSorted(batch), "a batch is read in mapping order")
|
||||
read = append(read, batch...)
|
||||
}
|
||||
assert.ElementsMatch(t, keysOf(copyTestChunkMap(chunks)), read,
|
||||
"the reads cover the mapping exactly, each chunk once")
|
||||
}
|
||||
|
||||
// A source that answers every request with the same page must not have that
|
||||
// page replayed into the target. Reads are bounded by the mapping, so the copy
|
||||
// asks for each batch once and cannot walk in circles.
|
||||
func TestCopyIndicesDoesNotReplayARepeatedPage(t *testing.T) {
|
||||
const pageSize = 64
|
||||
source := copyTestSingleVectorChunks(keysOf(copyTestChunkMap(pageSize))...)
|
||||
source.ignoreChunkFilter = true
|
||||
repo := source.serve(t)
|
||||
|
||||
require.NoError(t, copyTestRun(t, source, repo, copyTestChunkMap(pageSize)))
|
||||
|
||||
assert.Equal(t, 1, source.queryCount(), "the mapping is read once, not walked page by page")
|
||||
assert.Equal(t, pageSize, len(source.writtenObjects()), "the page must not be written twice")
|
||||
}
|
||||
|
||||
// A chunk holds one vector for its content plus one per generated question,
|
||||
// all sharing the chunk_id. Every one of them has to reach the target: a query
|
||||
// that names one chunk ID must not be mistaken for a query that returns one
|
||||
// row.
|
||||
func TestCopyIndicesCopiesEveryVectorOfAChunk(t *testing.T) {
|
||||
source := copyTestStore(map[string][]string{
|
||||
"chunk-0": {"chunk-0", "chunk-0-q1", "chunk-0-q2", "chunk-0-q3"},
|
||||
})
|
||||
repo := source.serve(t)
|
||||
|
||||
require.NoError(t, copyTestRun(t, source, repo, map[string]string{"chunk-0": "target-chunk-0"}))
|
||||
|
||||
written := source.writtenObjects()
|
||||
assert.Equal(t, 4, len(written), "the chunk's content vector and all three question vectors")
|
||||
assert.ElementsMatch(t,
|
||||
[]string{"target-chunk-0", "target-chunk-0-q1", "target-chunk-0-q2", "target-chunk-0-q3"},
|
||||
sourceIDsOf(written))
|
||||
for _, obj := range written {
|
||||
assert.Equal(t, "target-chunk-0", obj.targetChunkID)
|
||||
}
|
||||
}
|
||||
|
||||
// A batch that comes back with exactly as many rows as it asked for may have
|
||||
// been cut off, so it has to be split and re-read. Here four chunk IDs produce
|
||||
// five vectors: the first read is full, the two halves are not, and all five
|
||||
// vectors still have to be copied.
|
||||
func TestCopyIndicesSplitsABatchThatFillsTheLimit(t *testing.T) {
|
||||
source := copyTestStore(map[string][]string{
|
||||
"chunk-0": {"chunk-0", "chunk-0-q1"},
|
||||
"chunk-1": {"chunk-1"},
|
||||
"chunk-2": {"chunk-2"},
|
||||
"chunk-3": {"chunk-3"},
|
||||
})
|
||||
repo := source.serve(t)
|
||||
repo.copyQueryLimit = 4
|
||||
|
||||
mapping := map[string]string{
|
||||
"chunk-0": "target-chunk-0",
|
||||
"chunk-1": "target-chunk-1",
|
||||
"chunk-2": "target-chunk-2",
|
||||
"chunk-3": "target-chunk-3",
|
||||
}
|
||||
require.NoError(t, copyTestRun(t, source, repo, mapping))
|
||||
|
||||
assert.Equal(t, 5, len(source.writtenObjects()), "every vector of the batch must be copied")
|
||||
assert.Equal(t, 3, source.queryCount(), "a full read is followed by two half reads")
|
||||
assert.ElementsMatch(t, []int{4, 2, 2}, batchSizes(source.requestedBatches()))
|
||||
}
|
||||
|
||||
// When one chunk on its own fills the query limit it cannot be read
|
||||
// completely, and the copy has to say so rather than report success on an
|
||||
// index that is missing vectors.
|
||||
func TestCopyIndicesStopsOnAChunkThatFillsTheLimit(t *testing.T) {
|
||||
source := copyTestStore(map[string][]string{
|
||||
"chunk-0": {"chunk-0", "chunk-0-q1", "chunk-0-q2", "chunk-0-q3", "chunk-0-q4"},
|
||||
})
|
||||
repo := source.serve(t)
|
||||
repo.copyQueryLimit = 3
|
||||
|
||||
err := copyTestRun(t, source, repo, map[string]string{"chunk-0": "target-chunk-0"})
|
||||
|
||||
require.ErrorContains(t, err, "chunk-0", "the error must name the chunk that cannot be read")
|
||||
require.ErrorContains(t, err, "QUERY_MAXIMUM_RESULTS",
|
||||
"the error must say the chunk's vector count reaches the server's query limit")
|
||||
assert.Zero(t, len(source.writtenObjects()), "an unreadable chunk must not be reported as copied")
|
||||
}
|
||||
|
||||
// The server's QUERY_MAXIMUM_RESULTS is not exposed over the client API, so the
|
||||
// copy asks for the documented default first and, refused for it, retries at
|
||||
// the limit the server names.
|
||||
func TestCopyIndicesLowersTheQueryLimitWhenTheServerRefuses(t *testing.T) {
|
||||
source := copyTestSingleVectorChunks("chunk-0", "chunk-1", "chunk-2")
|
||||
source.queryLimit = 4
|
||||
repo := source.serve(t)
|
||||
|
||||
require.NoError(t, copyTestRun(t, source, repo, copyTestChunkMap(3)))
|
||||
|
||||
assert.Equal(t, []int{10000, 4}, source.queryLimits(),
|
||||
"the refused default is retried at the server's own limit")
|
||||
assert.Equal(t, 3, len(source.writtenObjects()))
|
||||
assert.Equal(t, 2, source.queryCount(), "only the first read pays for the refusal")
|
||||
}
|
||||
|
||||
// A query Weaviate could not run comes back as HTTP 200 with an errors array and
|
||||
// no data, so the SDK reports no Go error. Reading that as "the source has no
|
||||
// more objects" turns a failed query into a successful, silently truncated copy
|
||||
// - and the response type check used to panic before it could even get there.
|
||||
func TestCopyIndicesReportsAQueryError(t *testing.T) {
|
||||
const failure = "class Academy_embeddings_64 does not exist"
|
||||
source := copyTestSingleVectorChunks("chunk-0")
|
||||
source.queryError = failure
|
||||
repo := source.serve(t)
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
t.Fatalf("CopyIndices panicked on a query that could not run: %v", r)
|
||||
}
|
||||
}()
|
||||
|
||||
require.ErrorContains(t, copyTestRun(t, source, repo, copyTestChunkMap(1)), failure)
|
||||
assert.Equal(t, 1, source.queryCount(), "the walk must stop on the failed query")
|
||||
assert.Zero(t, len(source.writtenObjects()), "a failed query must not be reported as a finished copy")
|
||||
}
|
||||
|
||||
// A response the walk cannot read must be reported, not turned into a panic by
|
||||
// an unchecked assertion on the response shape.
|
||||
func TestCopyIndicesRejectsAResponseWithoutData(t *testing.T) {
|
||||
brokenResponses := map[string]func(*copyPageServer){
|
||||
"no data object": func(s *copyPageServer) { s.omitData = true },
|
||||
"no collection in Get": func(s *copyPageServer) { s.omitCollection = true },
|
||||
}
|
||||
for name, breakResponse := range brokenResponses {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
source := copyTestSingleVectorChunks("chunk-0")
|
||||
breakResponse(source)
|
||||
repo := source.serve(t)
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
t.Fatalf("CopyIndices panicked on a response without data: %v", r)
|
||||
}
|
||||
}()
|
||||
|
||||
require.ErrorContains(t, copyTestRun(t, source, repo, copyTestChunkMap(1)), "invalid response")
|
||||
assert.Equal(t, 1, source.queryCount(), "the walk must stop on the unreadable response")
|
||||
assert.Zero(t, len(source.writtenObjects()), "nothing may be reported as copied")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func keysOf[V any](m map[string]V) []string {
|
||||
return slices.Sorted(maps.Keys(m))
|
||||
}
|
||||
|
||||
func batchSizes(batches [][]string) []int {
|
||||
sizes := make([]int, 0, len(batches))
|
||||
for _, batch := range batches {
|
||||
sizes = append(sizes, len(batch))
|
||||
}
|
||||
return sizes
|
||||
}
|
||||
|
||||
func sourceIDsOf(objects []copyWrittenObject) []string {
|
||||
ids := make([]string, 0, len(objects))
|
||||
for _, obj := range objects {
|
||||
ids = append(ids, obj.sourceID)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// Package weaviate implements retrieval and metadata updates in Weaviate.
|
||||
package weaviate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/weaviate/weaviate-go-client/v5/weaviate/filters"
|
||||
"github.com/weaviate/weaviate-go-client/v5/weaviate/graphql"
|
||||
)
|
||||
|
||||
func (w *weaviateRepository) MoveKnowledgeIndices(
|
||||
ctx context.Context,
|
||||
sourceKB, targetKB, knowledgeID string,
|
||||
_ []string,
|
||||
dimension int,
|
||||
_ string,
|
||||
) error {
|
||||
collection := w.getCollectionName(dimension)
|
||||
where := filters.Where().WithOperator(filters.And).WithOperands([]*filters.WhereBuilder{
|
||||
filters.Where().WithPath([]string{fieldKnowledgeBaseID}).WithOperator(filters.Equal).WithValueString(sourceKB),
|
||||
filters.Where().WithPath([]string{fieldKnowledgeID}).WithOperator(filters.Equal).WithValueString(knowledgeID),
|
||||
})
|
||||
seen := make(map[string]bool)
|
||||
for {
|
||||
result, err := w.client.GraphQL().Get().WithClassName(collection).WithWhere(where).WithLimit(100).
|
||||
WithFields(graphql.Field{Name: "_additional", Fields: []graphql.Field{{Name: "id"}}}).
|
||||
Do(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if result == nil || len(result.Errors) != 0 {
|
||||
return fmt.Errorf("failed to list move indices")
|
||||
}
|
||||
get, ok := result.Data["Get"].(map[string]interface{})
|
||||
if !ok {
|
||||
return fmt.Errorf("invalid move index response")
|
||||
}
|
||||
rows, ok := get[collection].([]interface{})
|
||||
if !ok {
|
||||
return fmt.Errorf("invalid move index collection")
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return nil
|
||||
}
|
||||
var ids []string
|
||||
for _, row := range rows {
|
||||
data, ok := row.(map[string]interface{})
|
||||
if !ok {
|
||||
return fmt.Errorf("invalid move index row")
|
||||
}
|
||||
additional, ok := data["_additional"].(map[string]interface{})
|
||||
if !ok {
|
||||
return fmt.Errorf("missing move index ID")
|
||||
}
|
||||
id, ok := additional["id"].(string)
|
||||
if !ok || id == "" {
|
||||
return fmt.Errorf("invalid move index ID")
|
||||
}
|
||||
if seen[id] {
|
||||
return fmt.Errorf("move indices made no progress for %s", id)
|
||||
}
|
||||
seen[id] = true
|
||||
ids = append(ids, id)
|
||||
}
|
||||
// Drain the first filtered page; after+where is unsupported by Weaviate.
|
||||
// Successful updates remove these IDs from the predicate. Only an empty
|
||||
// follow-up query proves completion, including after partial-page updates.
|
||||
for _, id := range ids {
|
||||
if err := w.client.Data().Updater().WithClassName(collection).WithID(id).WithMerge().
|
||||
WithProperties(map[string]interface{}{fieldKnowledgeBaseID: targetKB, fieldTagID: ""}).
|
||||
Do(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package weaviate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
sdk "github.com/weaviate/weaviate-go-client/v5/weaviate"
|
||||
)
|
||||
|
||||
func TestMoveKnowledgeIndicesDrainsBeyondOffsetLimitAndRetries(t *testing.T) {
|
||||
const count = 10005
|
||||
var mu sync.Mutex
|
||||
remaining := make(map[string]bool, count)
|
||||
for i := range count {
|
||||
remaining[fmt.Sprintf("00000000-0000-0000-0000-%012d", i)] = true
|
||||
}
|
||||
failed := false
|
||||
patches, queries := 0, 0
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch {
|
||||
case r.URL.Path == "/v1/graphql":
|
||||
queries++
|
||||
var body struct {
|
||||
Query string `json:"query"`
|
||||
}
|
||||
if !assert.NoError(t, json.NewDecoder(r.Body).Decode(&body)) {
|
||||
w.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
assert.Contains(t, body.Query, "knowledge_base_id")
|
||||
assert.Contains(t, body.Query, "knowledge_id")
|
||||
assert.Contains(t, body.Query, "source")
|
||||
assert.Contains(t, body.Query, "doc")
|
||||
if strings.Contains(body.Query, "offset") || strings.Contains(body.Query, "after") {
|
||||
_ = json.NewEncoder(w).
|
||||
Encode(map[string]any{"errors": []any{map[string]any{"message": "pagination unsupported"}}})
|
||||
return
|
||||
}
|
||||
rows := make([]any, 0, 100)
|
||||
for id := range remaining {
|
||||
rows = append(rows, map[string]any{"_additional": map[string]any{"id": id}})
|
||||
if len(rows) == 100 {
|
||||
break
|
||||
}
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"Get": map[string]any{"Move_3": rows}}})
|
||||
case r.Method == http.MethodPatch:
|
||||
id := path.Base(r.URL.Path)
|
||||
assert.True(t, remaining[id], "only source-filtered IDs should be moved")
|
||||
var body struct {
|
||||
Properties map[string]any `json:"properties"`
|
||||
Vector []float32 `json:"vector"`
|
||||
}
|
||||
if !assert.NoError(t, json.NewDecoder(r.Body).Decode(&body)) {
|
||||
w.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
assert.Equal(t, map[string]any{fieldKnowledgeBaseID: "target", fieldTagID: ""}, body.Properties)
|
||||
assert.Empty(t, body.Vector, "metadata merge must preserve existing vectors")
|
||||
if patches == 137 && !failed {
|
||||
failed = true
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
patches++
|
||||
delete(remaining, id)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
default:
|
||||
// SDK probes the server version before object writes.
|
||||
if r.URL.Path == "/v1/meta" {
|
||||
_, _ = w.Write([]byte(`{"version":"1.30.0"}`))
|
||||
return
|
||||
}
|
||||
t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
client, err := sdk.NewClient(sdk.Config{Scheme: "http", Host: strings.TrimPrefix(server.URL, "http://")})
|
||||
require.NoError(t, err)
|
||||
repo := &weaviateRepository{client: client, collectionBaseName: "Move"}
|
||||
require.Error(t, repo.MoveKnowledgeIndices(context.Background(), "source", "target", "doc", nil, 3, ""))
|
||||
mu.Lock()
|
||||
left := len(remaining)
|
||||
mu.Unlock()
|
||||
require.Equal(t, count-137, left)
|
||||
require.NoError(t, repo.MoveKnowledgeIndices(context.Background(), "source", "target", "doc", nil, 3, ""))
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
require.Empty(t, remaining)
|
||||
require.Equal(t, count, patches)
|
||||
require.Greater(t, queries, 100)
|
||||
}
|
||||
|
||||
func TestMoveKnowledgeIndicesRejectsNoProgress(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch r.URL.Path {
|
||||
case "/v1/graphql":
|
||||
_, _ = w.Write(
|
||||
[]byte(`{"data":{"Get":{"Move_3":[{"_additional":{"id":"00000000-0000-0000-0000-000000000001"}}]}}}`),
|
||||
)
|
||||
case "/v1/meta":
|
||||
_, _ = w.Write([]byte(`{"version":"1.30.0"}`))
|
||||
default:
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
client, err := sdk.NewClient(sdk.Config{Scheme: "http", Host: strings.TrimPrefix(server.URL, "http://")})
|
||||
require.NoError(t, err)
|
||||
repo := &weaviateRepository{client: client, collectionBaseName: "Move"}
|
||||
require.ErrorContains(
|
||||
t,
|
||||
repo.MoveKnowledgeIndices(context.Background(), "source", "target", "doc", nil, 3, ""),
|
||||
"no progress",
|
||||
)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,164 @@
|
||||
package weaviate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
sdk "github.com/weaviate/weaviate-go-client/v5/weaviate"
|
||||
)
|
||||
|
||||
// weaviateErrorBody is how Weaviate words a refused schema request.
|
||||
func weaviateErrorBody(message string) string {
|
||||
body, _ := json.Marshal(map[string]any{"error": []any{map[string]any{"message": message}}})
|
||||
return string(body)
|
||||
}
|
||||
|
||||
// schemaTestServer stands in for Weaviate's schema API. A class exists once a
|
||||
// create has been answered with 200; probe runs before every existence check.
|
||||
type schemaTestServer struct {
|
||||
mu sync.Mutex
|
||||
exists bool
|
||||
probes int
|
||||
creates int
|
||||
probe func()
|
||||
create func(attempt int) (int, string)
|
||||
}
|
||||
|
||||
func (s *schemaTestServer) repository(t *testing.T) *weaviateRepository {
|
||||
t.Helper()
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch {
|
||||
case r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/v1/schema/"):
|
||||
// Answer from the state the worker found on arrival, before the
|
||||
// barrier releases the race. Sampling after it instead lets the
|
||||
// winner's create turn into an "already exists" answer for whoever
|
||||
// the scheduler runs last, so that worker skips the create
|
||||
// entirely and fewer than `workers` creates ever reach the server.
|
||||
s.mu.Lock()
|
||||
s.probes++
|
||||
exists := s.exists
|
||||
s.mu.Unlock()
|
||||
if s.probe != nil {
|
||||
s.probe()
|
||||
}
|
||||
if !exists {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"class":"Academy_embeddings_1024"}`))
|
||||
case r.Method == http.MethodPost && r.URL.Path == "/v1/schema":
|
||||
s.mu.Lock()
|
||||
s.creates++
|
||||
code, body := s.create(s.creates)
|
||||
if code == http.StatusOK {
|
||||
s.exists = true
|
||||
}
|
||||
s.mu.Unlock()
|
||||
w.WriteHeader(code)
|
||||
_, _ = w.Write([]byte(body))
|
||||
case r.URL.Path == "/v1/meta":
|
||||
_, _ = w.Write([]byte(`{"version":"1.37.3"}`))
|
||||
default:
|
||||
t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
client, err := sdk.NewClient(sdk.Config{Scheme: "http", Host: strings.TrimPrefix(server.URL, "http://")})
|
||||
require.NoError(t, err)
|
||||
return &weaviateRepository{client: client, collectionBaseName: "Academy_embeddings"}
|
||||
}
|
||||
|
||||
// The first batches written at a new dimension are saved by several workers at
|
||||
// once, and each may find the class missing before any has created it. Only
|
||||
// one create wins. Weaviate refuses the others with 422, in one of two wordings
|
||||
// depending on whether they lose before or inside the Raft apply; neither may
|
||||
// fail their writes. The barrier makes every worker see the class as missing,
|
||||
// so the race happens every run.
|
||||
func TestEnsureCollectionToleratesConcurrentCreation(t *testing.T) {
|
||||
const workers = 8
|
||||
var arrived atomic.Int32
|
||||
allProbed := make(chan struct{})
|
||||
server := &schemaTestServer{
|
||||
probe: func() {
|
||||
n := arrived.Add(1)
|
||||
if n == workers {
|
||||
close(allProbed)
|
||||
}
|
||||
if n > workers {
|
||||
return // a loser looking again after its 422
|
||||
}
|
||||
select {
|
||||
case <-allProbed:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Error("not every worker probed the class")
|
||||
}
|
||||
},
|
||||
create: func(attempt int) (int, string) {
|
||||
switch {
|
||||
case attempt == 1:
|
||||
return http.StatusOK, `{"class":"Academy_embeddings_1024"}`
|
||||
case attempt%2 == 0:
|
||||
return http.StatusUnprocessableEntity,
|
||||
weaviateErrorBody("updating schema: TYPE_ADD_CLASS: class already exists")
|
||||
default:
|
||||
return http.StatusUnprocessableEntity,
|
||||
weaviateErrorBody("class name Academy_embeddings_1024 already exists")
|
||||
}
|
||||
},
|
||||
}
|
||||
repo := server.repository(t)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
errs := make(chan error, workers)
|
||||
for range workers {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
errs <- repo.ensureCollection(context.Background(), 1024)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
for err := range errs {
|
||||
assert.NoError(t, err, "a worker lost the creation race")
|
||||
}
|
||||
assert.Equal(t, workers, server.creates, "every worker should have attempted the create")
|
||||
_, ok := repo.initializedCollections.Load(1024)
|
||||
assert.True(t, ok, "dimension 1024 should be marked initialized")
|
||||
}
|
||||
|
||||
// A 422 for any other reason leaves the class missing, so the write must fail
|
||||
// rather than be recorded as initialized.
|
||||
func TestEnsureCollectionFailsWhenTheCreateIsRejected(t *testing.T) {
|
||||
server := &schemaTestServer{create: func(int) (int, string) {
|
||||
return http.StatusUnprocessableEntity, weaviateErrorBody("invalid property: data type not supported")
|
||||
}}
|
||||
repo := server.repository(t)
|
||||
|
||||
require.ErrorContains(t, repo.ensureCollection(context.Background(), 1024), "failed to create collection")
|
||||
assert.Equal(t, 2, server.probes, "the class should be looked up again after the 422")
|
||||
_, ok := repo.initializedCollections.Load(1024)
|
||||
assert.False(t, ok)
|
||||
}
|
||||
|
||||
// Only a 422 means the create was refused; anything else is reported as it is.
|
||||
func TestEnsureCollectionDoesNotRecheckOtherFailures(t *testing.T) {
|
||||
server := &schemaTestServer{create: func(int) (int, string) {
|
||||
return http.StatusInternalServerError, weaviateErrorBody("disk full")
|
||||
}}
|
||||
repo := server.repository(t)
|
||||
|
||||
require.Error(t, repo.ensureCollection(context.Background(), 1024))
|
||||
assert.Equal(t, 1, server.probes)
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package weaviate
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// Weaviate certainty is (1 + cos) / 2; vector hits leave the driver as
|
||||
// cosine similarity.
|
||||
func TestParseGraphQLResponseReportsCosine(t *testing.T) {
|
||||
t.Parallel()
|
||||
items := []interface{}{
|
||||
map[string]interface{}{
|
||||
"_additional": map[string]interface{}{"id": "p1", "certainty": 0.9},
|
||||
"chunk_id": "c1",
|
||||
},
|
||||
}
|
||||
got := parseGraphQLResponse(items, "Coll", types.MatchTypeEmbedding)
|
||||
if len(got) != 1 || got[0].Score < 0.8-1e-9 || got[0].Score > 0.8+1e-9 {
|
||||
t.Fatalf("scores = %+v, want cosine 0.8", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package weaviate
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/weaviate/weaviate-go-client/v5/weaviate"
|
||||
)
|
||||
|
||||
type weaviateRepository struct {
|
||||
client *weaviate.Client
|
||||
collectionBaseName string
|
||||
replicationFactor int // 0 = use Weaviate server default
|
||||
desiredShardCount int // 0 = use Weaviate server default
|
||||
// copyQueryLimit caps the rows one CopyIndices source query may return.
|
||||
// 0 = defaultCopyQueryLimit. Tests lower it to drive the truncation and
|
||||
// batch-splitting paths with small fixtures.
|
||||
copyQueryLimit int
|
||||
// Cache for initialized collections (dimension -> true)
|
||||
initializedCollections sync.Map
|
||||
}
|
||||
|
||||
type WeaviateVectorEmbedding struct {
|
||||
Content string `json:"content"`
|
||||
SourceID string `json:"source_id"`
|
||||
SourceType int `json:"source_type"`
|
||||
ChunkID string `json:"chunk_id"`
|
||||
KnowledgeID string `json:"knowledge_id"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||
TagID string `json:"tag_id"`
|
||||
Embedding []float32 `json:"embedding"`
|
||||
IsEnabled bool `json:"is_enabled"`
|
||||
}
|
||||
|
||||
type WeaviateVectorEmbeddingWithScore struct {
|
||||
WeaviateVectorEmbedding
|
||||
Score float64
|
||||
}
|
||||
Reference in new issue
Block a user