fix(embedding): two wire-level bugs in the remote embedders (#3484)

* fix(embedding): stop four embedders from returning (nil, nil) on a dead upstream

doRequestWithRetry keeps resp and err in the enclosing scope and returns
(nil, err) once the retries run out. Writing `req, err := ...` inside the
loop introduces a loop-local err, so `resp, err = client.Do(req)` updates
that copy and the enclosing err stays nil. Every retry failing therefore
returned (nil, nil): BatchEmbed's `if err != nil` did not fire and the next
line dereferenced resp.Body, a nil-pointer panic that took the process down
instead of surfacing "connection refused". Stopping the embedding upstream
and asking any RAG question reproduced it.

The bug was found, documented and fixed in openai.go, then re-fixed in
zhipu.go and again, differently, in azure_openai.go; jina.go, nvidia.go,
aliyun.go and volcengine.go kept the original spelling because the retry
loop exists in eight near-identical copies and a fix to one reaches none of
the others.

TestEmbeddersReportUnreachableUpstream now drives all eight against a
refused port with the retry budget zeroed, so the next copy of this loop is
covered the moment it appears.

* fix(embedding): read the documented index field of DashScope multimodal vectors

The multimodal embedding response carries each vector's position in `index`:

  {"output": {"embeddings": [{"index": 0, "embedding": [...], "type": "text"},
                             {"index": 1, "embedding": [...], "type": "image"}]}}

The decoder read `text_index`, which is the field name of DashScope's *text*
embedding API one page over. A missing field decodes as 0, so every vector in
a batch was written to slot 0 and the rest of the slice stayed empty: with the
default BATCH_EMBED_SIZE of 5, four of every five chunks were indexed with an
empty vector. Only models routed to this client are affected — an Aliyun
embedding model whose name contains "vision" or "multimodal"; the text-only
models go through the OpenAI-compatible path.

An index outside the batch, or a response that covers fewer inputs than were
sent, is now an error. Handing back an empty vector stores it and poisons
retrieval without anything failing.

The regression test replays the response example from the reference page, so
the decoder is pinned against the vendor's own document rather than against
our structs.

https://help.aliyun.com/zh/model-studio/multimodal-embedding-api-reference
main
lyingbug 2026-09-20 21:12:33 +08:00 committed by GitHub
parent d4b9fd0c72
commit 50bbf9ad5f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
6 changed files with 243 additions and 11 deletions

View File

@ -66,12 +66,19 @@ type AliyunContent struct {
Text string `json:"text,omitempty"`
}
// AliyunEmbedResponse represents an Aliyun DashScope embedding response
// AliyunEmbedResponse represents an Aliyun DashScope embedding response.
//
// The position field is `index`, not the `text_index` of DashScope's
// text-embedding API (/services/embeddings/text-embedding/text-embedding).
// The two interfaces are neighbours in the docs and the wrong name was
// carried over: a missing field decodes as 0, so every vector in a batch
// landed in slot 0 and the rest stayed empty.
// https://help.aliyun.com/zh/model-studio/multimodal-embedding-api-reference
type AliyunEmbedResponse struct {
Output struct {
Embeddings []struct {
Embedding []float32 `json:"embedding"`
TextIndex int `json:"text_index"`
Index int `json:"index"`
} `json:"embeddings"`
} `json:"output"`
Usage struct {
@ -165,7 +172,12 @@ func (e *AliyunEmbedder) doRequestWithRetry(ctx context.Context, jsonData []byte
}
}
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(jsonData))
// Declare req separately: with `req, err := ...` the `:=` introduces a
// loop-local err, so the `resp, err = client.Do(req)` below writes to
// that copy and the outer err stays nil. Every retry failing then
// returns (nil, nil) and the caller dereferences resp.Body → SIGSEGV.
var req *http.Request
req, err = http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(jsonData))
if err != nil {
logger.GetLogger(ctx).Errorf("AliyunEmbedder failed to create request: %v", err)
continue
@ -242,11 +254,20 @@ func (e *AliyunEmbedder) BatchEmbed(ctx context.Context, texts []string) ([][]fl
return nil, fmt.Errorf("unmarshal response: %w", err)
}
// Extract embedding vectors, preserving order by text_index
// Extract embedding vectors, restoring input order from `index`.
embeddings := make([][]float32, len(texts))
for _, emb := range response.Output.Embeddings {
if emb.TextIndex >= 0 && emb.TextIndex < len(embeddings) {
embeddings[emb.TextIndex] = emb.Embedding
if emb.Index < 0 || emb.Index >= len(embeddings) {
return nil, fmt.Errorf("embedding index %d out of range for %d inputs", emb.Index, len(texts))
}
embeddings[emb.Index] = emb.Embedding
}
// An unfilled slot means the response did not cover every input. Returning
// it would store an empty vector and silently poison retrieval, so fail
// instead: the caller can retry or surface the error.
for i, embedding := range embeddings {
if len(embedding) == 0 {
return nil, fmt.Errorf("no embedding returned for input %d of %d", i, len(texts))
}
}

View File

@ -0,0 +1,84 @@
package embedding
import (
"context"
"net/http"
"net/http/httptest"
"testing"
)
// documentedMultimodalResponse is the response body of DashScope's multimodal
// embedding API, copied from the reference page so the decoder is pinned
// against the vendor's own example rather than against our structs:
// https://help.aliyun.com/zh/model-studio/multimodal-embedding-api-reference
//
// The position field is `index`. DashScope's *text* embedding API, one page
// over, calls it `text_index`; decoding that name here silently yields 0 for
// every element, which used to collapse a whole batch onto slot 0.
const documentedMultimodalResponse = `{
"output": {
"embeddings": [
{"index": 0, "embedding": [0.1, 0.11], "type": "text"},
{"index": 1, "embedding": [0.2, 0.22], "type": "text"},
{"index": 2, "embedding": [0.3, 0.33], "type": "text"}
]
},
"usage": {"input_tokens": 3, "output_tokens": 0, "total_tokens": 3},
"request_id": "1fff9502-a6c5-9472-9ee1-73930fdd04c5"
}`
func TestAliyunEmbedderRestoresBatchOrder(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(documentedMultimodalResponse))
}))
defer server.Close()
embedder, err := NewAliyunEmbedder("key", server.URL, "tongyi-embedding-vision-plus", 0, 0, "model-id", nil)
if err != nil {
t.Fatalf("NewAliyunEmbedder: %v", err)
}
got, err := embedder.BatchEmbed(context.Background(), []string{"a", "b", "c"})
if err != nil {
t.Fatalf("BatchEmbed: %v", err)
}
want := [][]float32{{0.1, 0.11}, {0.2, 0.22}, {0.3, 0.33}}
if len(got) != len(want) {
t.Fatalf("got %d embeddings, want %d", len(got), len(want))
}
for i := range want {
if len(got[i]) != len(want[i]) {
t.Fatalf("embedding %d: got %v, want %v", i, got[i], want[i])
}
for j := range want[i] {
if got[i][j] != want[i][j] {
t.Fatalf("embedding %d: got %v, want %v", i, got[i], want[i])
}
}
}
}
// A response that skips an input must fail rather than hand back an empty
// vector: an empty vector is stored and poisons retrieval silently.
func TestAliyunEmbedderFailsOnMissingEmbedding(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"output":{"embeddings":[{"index":0,"embedding":[0.1],"type":"text"}]}}`))
}))
defer server.Close()
embedder, err := NewAliyunEmbedder("key", server.URL, "tongyi-embedding-vision-plus", 0, 0, "model-id", nil)
if err != nil {
t.Fatalf("NewAliyunEmbedder: %v", err)
}
if _, err := embedder.BatchEmbed(context.Background(), []string{"a", "b"}); err == nil {
t.Fatal("expected an error when the response covers fewer inputs than requested")
}
}

View File

@ -121,8 +121,13 @@ func (e *JinaEmbedder) doRequestWithRetry(ctx context.Context, jsonData []byte)
}
}
// Rebuild request each time to ensure Body is valid
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(jsonData))
// Rebuild request each time to ensure Body is valid.
// Declare req separately: with `req, err := ...` the `:=` introduces a
// loop-local err, so the `resp, err = client.Do(req)` below writes to
// that copy and the outer err stays nil. Every retry failing then
// returns (nil, nil) and the caller dereferences resp.Body → SIGSEGV.
var req *http.Request
req, err = http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(jsonData))
if err != nil {
logger.GetLogger(ctx).Errorf("JinaEmbedder failed to create request: %v", err)
continue

View File

@ -122,8 +122,13 @@ func (e *NvidiaEmbedder) doRequestWithRetry(ctx context.Context, jsonData []byte
}
}
// Rebuild request each time to ensure Body is valid
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(jsonData))
// Rebuild request each time to ensure Body is valid.
// Declare req separately: with `req, err := ...` the `:=` introduces a
// loop-local err, so the `resp, err = client.Do(req)` below writes to
// that copy and the outer err stays nil. Every retry failing then
// returns (nil, nil) and the caller dereferences resp.Body → SIGSEGV.
var req *http.Request
req, err = http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(jsonData))
if err != nil {
logger.GetLogger(ctx).Errorf("NvidiaEmbedder failed to create request: %v", err)
continue

View File

@ -0,0 +1,112 @@
package embedding
import (
"context"
"net/http"
"net/http/httptest"
"testing"
)
// TestEmbeddersReportUnreachableUpstream guards a crash that every
// OpenAI-style embedder here is one keystroke away from.
//
// Each doRequestWithRetry keeps `resp` and `err` in the enclosing scope and
// returns `(nil, err)` once the retries run out. Writing
// `req, err := http.NewRequestWithContext(...)` inside the loop introduces a
// loop-local `err`, so `resp, err = client.Do(req)` updates that copy only and
// the enclosing `err` stays nil. The function then returns `(nil, nil)`,
// BatchEmbed's `if err != nil` does not fire, and the next line dereferences
// `resp.Body` — a nil-pointer panic that takes the process down instead of
// surfacing "connection refused". It was found, documented and fixed in
// openai.go, then re-fixed in zhipu.go and azure_openai.go, while jina.go,
// nvidia.go, aliyun.go and volcengine.go kept the original spelling.
//
// The retry budget is zeroed so the table runs without the backoff sleeps.
func TestEmbeddersReportUnreachableUpstream(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
// A server that is started and immediately closed gives a reachable-looking
// URL whose port refuses connections.
server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
url := server.URL
server.Close()
cases := []struct {
name string
make func() (Embedder, error)
}{
{"openai", func() (Embedder, error) {
e, err := NewOpenAIEmbedder("k", url, "m", 0, 0, "id", nil)
if e != nil {
e.maxRetries = 0
}
return e, err
}},
{"zhipu", func() (Embedder, error) {
e, err := NewZhipuEmbedder("k", url, "m", 0, 0, "id", nil)
if e != nil {
e.maxRetries = 0
}
return e, err
}},
{"jina", func() (Embedder, error) {
e, err := NewJinaEmbedder("k", url, "m", 0, 0, "id", nil)
if e != nil {
e.maxRetries = 0
}
return e, err
}},
{"nvidia", func() (Embedder, error) {
e, err := NewNvidiaEmbedder("k", url, "m", 0, "id", nil)
if e != nil {
e.maxRetries = 0
}
return e, err
}},
{"gemini", func() (Embedder, error) {
e, err := NewGeminiEmbedder("k", url, "m", 0, 0, "id", nil)
if e != nil {
e.maxRetries = 0
}
return e, err
}},
{"aliyun", func() (Embedder, error) {
e, err := NewAliyunEmbedder("k", url, "m", 0, 0, "id", nil)
if e != nil {
e.maxRetries = 0
}
return e, err
}},
{"volcengine", func() (Embedder, error) {
e, err := NewVolcengineEmbedder("k", url, "m", 0, 0, "id", nil)
if e != nil {
e.maxRetries = 0
}
return e, err
}},
{"azure_openai", func() (Embedder, error) {
e, err := NewAzureOpenAIEmbedder("k", url, "m", 0, 0, "id", "", nil)
if e != nil {
e.maxRetries = 0
}
return e, err
}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
embedder, err := tc.make()
if err != nil {
t.Fatalf("constructor: %v", err)
}
defer func() {
if r := recover(); r != nil {
t.Fatalf("BatchEmbed panicked instead of returning an error: %v", r)
}
}()
if _, err := embedder.BatchEmbed(context.Background(), []string{"a"}); err == nil {
t.Fatal("expected an error when the upstream refuses connections")
}
})
}
}

View File

@ -171,7 +171,12 @@ func (e *VolcengineEmbedder) doRequestWithRetry(ctx context.Context, jsonData []
}
}
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(jsonData))
// Declare req separately: with `req, err := ...` the `:=` introduces a
// loop-local err, so the `resp, err = client.Do(req)` below writes to
// that copy and the outer err stays nil. Every retry failing then
// returns (nil, nil) and the caller dereferences resp.Body → SIGSEGV.
var req *http.Request
req, err = http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(jsonData))
if err != nil {
logger.GetLogger(ctx).Errorf("VolcengineEmbedder failed to create request: %v", err)
continue