Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix(ima): 三条游标分页循环补重复游标防护与跳数上限 (#3889)

linus-liu-weba6c6c35ad292
diff --git a/internal/datasource/connector/ima/connector.go b/internal/datasource/connector/ima/connector.go
index dc07cd4eb..bf5e12cb2 100644
--- a/internal/datasource/connector/ima/connector.go
+++ b/internal/datasource/connector/ima/connector.go
@@ -50,6 +50,32 @@ func (c *Connector) ResolveResourceAncestors(
return []string{}, nil
}
+// maxPaginationHops bounds every cursor-paginated loop in this file. A vendor
+// that keeps handing back a fresh cursor would otherwise keep the connector
+// (and the sync task holding it) spinning until the task deadline; the value
+// mirrors the guard Confluence and DingTalk already carry.
+const maxPaginationHops = 10000
+
+// nextPageCursor validates the progress of a cursor-paginated loop after page
+// `page` (1-based) has been fetched: a cursor handed back twice means the
+// vendor is repeating a page, and page >= maxPaginationHops means the listing
+// is unbounded. Both are reported instead of being retried forever, and the
+// hop cap is also logged because it is the one failure that looks like a
+// healthy, still-running sync from the outside.
+func nextPageCursor(
+ ctx context.Context, seen map[string]struct{}, cursor string, page int,
+) (string, error) {
+ if page >= maxPaginationHops {
+ logger.Warnf(ctx, "[IMA] pagination exceeded %d pages; aborting", maxPaginationHops)
+ return "", fmt.Errorf("pagination exceeded %d pages", maxPaginationHops)
+ }
+ if _, exists := seen[cursor]; exists {
+ return "", fmt.Errorf("pagination repeated next_cursor %q", cursor)
+ }
+ seen[cursor] = struct{}{}
+ return cursor, nil
+}
+
// ListResources returns the flat list of knowledge bases the token can read.
// parentID is honoured only for the "no children" contract — see the note on
// Connector.ListResources in internal/datasource/connector.go.
@@ -80,7 +106,8 @@ func (c *Connector) ListResources(
var bases []kbLite
cursor := ""
- for {
+ seenCursors := make(map[string]struct{})
+ for page := 1; ; page++ {
resp, err := cli.GetAddableKnowledgeBaseList(ctx, cursor, defaultPageSize)
if err != nil {
return nil, fmt.Errorf("get_addable_knowledge_base_list: %w", err)
@@ -91,13 +118,18 @@ func (c *Connector) ListResources(
if resp.IsEnd || resp.NextCursor == "" {
break
}
- cursor = resp.NextCursor
+ next, err := nextPageCursor(ctx, seenCursors, resp.NextCursor, page)
+ if err != nil {
+ return nil, fmt.Errorf("get_addable_knowledge_base_list: %w", err)
+ }
+ cursor = next
}
logger.Infof(ctx, "[IMA] get_addable_knowledge_base_list returned %d knowledge bases", len(bases))
if len(bases) == 0 {
cursor = ""
- for {
+ seenCursors = make(map[string]struct{})
+ for page := 1; ; page++ {
resp, err := cli.SearchKnowledgeBase(ctx, "", cursor, searchPageSize)
if err != nil {
return nil, fmt.Errorf("search_knowledge_base fallback: %w", err)
@@ -108,7 +140,11 @@ func (c *Connector) ListResources(
if resp.IsEnd || resp.NextCursor == "" {
break
}
- cursor = resp.NextCursor
+ next, err := nextPageCursor(ctx, seenCursors, resp.NextCursor, page)
+ if err != nil {
+ return nil, fmt.Errorf("search_knowledge_base fallback: %w", err)
+ }
+ cursor = next
}
logger.Infof(ctx, "[IMA] search_knowledge_base fallback returned %d knowledge bases", len(bases))
}
@@ -356,7 +392,8 @@ func listAllKBFiles(
stack = stack[:len(stack)-1]
cursor := ""
- for {
+ seenCursors := make(map[string]struct{})
+ for page := 1; ; page++ {
resp, err := cli.GetKnowledgeList(ctx, kbID, cur.folderID, cursor, defaultPageSize)
if err != nil {
return nil, nil, err
@@ -387,7 +424,11 @@ func listAllKBFiles(
if resp.IsEnd || resp.NextCursor == "" {
break
}
- cursor = resp.NextCursor
+ next, err := nextPageCursor(ctx, seenCursors, resp.NextCursor, page)
+ if err != nil {
+ return nil, nil, fmt.Errorf("get_knowledge_list: %w", err)
+ }
+ cursor = next
}
}
return out, folderPath, nil
diff --git a/internal/datasource/connector/ima/fake_ima_test.go b/internal/datasource/connector/ima/fake_ima_test.go
index 368945513..d4c3b974d 100644
--- a/internal/datasource/connector/ima/fake_ima_test.go
+++ b/internal/datasource/connector/ima/fake_ima_test.go
@@ -78,16 +78,39 @@ type fakeIMA struct {
// calls counts requests per action, plus "download:<media_id>".
calls map[string]int
+ // paging overrides an action's paging envelope; see fakePaging.
+ paging map[string]fakePaging
// downloadHeaders records the headers seen by the last download of a media.
downloadHeaders map[string]http.Header
}
+// fakePaging forces the paging envelope of one action so a test can reproduce
+// a vendor that never stops paging. maxRequests bounds the fake: once the
+// action has been called more times than that it answers 400, so a run without
+// the connector's guard fails instead of spinning forever.
+type fakePaging struct {
+ // nextCursor is answered as next_cursor; with advanceCursor the request
+ // number is appended so every page hands back a cursor never seen before.
+ nextCursor string
+ advanceCursor bool
+ isEnd bool
+ // stopAfter ends the listing (is_end=true, empty cursor) once the action
+ // has been called this many times, so a test can model a finite listing.
+ stopAfter int
+ // filesByCall replaces get_knowledge_list's payload for one request
+ // number (1-based), so a test can prove several pages are merged.
+ filesByCall map[int][]fakeFile
+ // maxRequests answers 400 once the action has been called more than this.
+ maxRequests int
+}
+
func newFakeIMA(t *testing.T) *fakeIMA {
t.Helper()
f := &fakeIMA{
files: map[string]map[string][]fakeFile{},
folders: map[string]map[string][]fakeFolder{},
calls: map[string]int{},
+ paging: map[string]fakePaging{},
downloadHeaders: map[string]http.Header{},
}
mux := http.NewServeMux()
@@ -136,6 +159,47 @@ func (f *fakeIMA) record(key string) {
f.calls[key]++
}
+// pagingFields answers the is_end/next_cursor pair for an action, applying the
+// test's paging override when one is installed.
+func (f *fakeIMA) pagingFields(action string) (isEnd bool, nextCursor string) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ override, ok := f.paging[action]
+ if !ok {
+ return true, ""
+ }
+ if override.stopAfter > 0 && f.calls[action] >= override.stopAfter {
+ return true, ""
+ }
+ if override.advanceCursor {
+ return override.isEnd, fmt.Sprintf("%s-%d", override.nextCursor, f.calls[action])
+ }
+ return override.isEnd, override.nextCursor
+}
+
+// pagingFiles answers the file payload for one get_knowledge_list request,
+// falling back to the knowledge base's own listing.
+func (f *fakeIMA) pagingFiles(kbID, folderID string, call int) []fakeFile {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if override, ok := f.paging["get_knowledge_list"]; ok {
+ if files, ok := override.filesByCall[call]; ok {
+ return files
+ }
+ }
+ return f.files[kbID][folderID]
+}
+
+// requestBudgetExceeded reports whether the action has used up the request
+// budget a test installed, so the fake can answer 400 instead of letting an
+// unguarded connector spin.
+func (f *fakeIMA) requestBudgetExceeded(action string) bool {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ limit := f.paging[action].maxRequests
+ return limit > 0 && f.calls[action] > limit
+}
+
// findFile locates a file by media_id across every knowledge base.
func (f *fakeIMA) findFile(mediaID string) (fakeFile, bool) {
f.mu.Lock()
@@ -155,6 +219,10 @@ func (f *fakeIMA) findFile(mediaID string) (fakeFile, bool) {
func (f *fakeIMA) handleAPI(w http.ResponseWriter, r *http.Request) {
action := strings.TrimPrefix(r.URL.Path, apiBasePath+"/")
f.record(action)
+ if f.requestBudgetExceeded(action) {
+ w.WriteHeader(http.StatusBadRequest)
+ return
+ }
var req map[string]interface{}
_ = json.NewDecoder(r.Body).Decode(&req)
@@ -167,14 +235,20 @@ func (f *fakeIMA) handleAPI(w http.ResponseWriter, r *http.Request) {
switch action {
case "get_addable_knowledge_base_list":
+ isEnd, nextCursor := f.pagingFields(action)
f.mu.Lock()
- resp := getAddableKnowledgeBaseListResp{AddableKnowledgeBaseList: f.bases, IsEnd: true}
+ resp := getAddableKnowledgeBaseListResp{
+ AddableKnowledgeBaseList: f.bases,
+ IsEnd: isEnd,
+ NextCursor: nextCursor,
+ }
f.mu.Unlock()
writeEnvelope(w, 0, "", resp)
case "search_knowledge_base":
+ isEnd, nextCursor := f.pagingFields(action)
f.mu.Lock()
- resp := searchKnowledgeBaseResp{InfoList: f.searchBases, IsEnd: true}
+ resp := searchKnowledgeBaseResp{InfoList: f.searchBases, IsEnd: isEnd, NextCursor: nextCursor}
f.mu.Unlock()
writeEnvelope(w, 0, "", resp)
@@ -191,8 +265,9 @@ func (f *fakeIMA) handleAPI(w http.ResponseWriter, r *http.Request) {
case "get_knowledge_list":
kbID, folderID := str("knowledge_base_id"), str("folder_id")
f.record("get_knowledge_list:" + folderID)
+ isEnd, nextCursor := f.pagingFields("get_knowledge_list")
+ files := f.pagingFiles(kbID, folderID, f.callCount("get_knowledge_list"))
f.mu.Lock()
- files := f.files[kbID][folderID]
folders := f.folders[kbID][folderID]
f.mu.Unlock()
@@ -216,7 +291,7 @@ func (f *fakeIMA) handleAPI(w http.ResponseWriter, r *http.Request) {
})
list = append(list, b)
}
- writeEnvelope(w, 0, "", getKnowledgeListResp{KnowledgeList: list, IsEnd: true})
+ writeEnvelope(w, 0, "", getKnowledgeListResp{KnowledgeList: list, IsEnd: isEnd, NextCursor: nextCursor})
case "get_media_info":
mediaID := str("media_id")
diff --git a/internal/datasource/connector/ima/pagination_guard_test.go b/internal/datasource/connector/ima/pagination_guard_test.go
new file mode 100644
index 000000000..3dec09583
--- /dev/null
+++ b/internal/datasource/connector/ima/pagination_guard_test.go
@@ -0,0 +1,137 @@
+package ima
+
+import (
+ "bytes"
+ "context"
+ "os"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/Tencent/WeKnora/internal/logger"
+)
+
+// paginationHopCap mirrors maxPaginationHops in connector.go. It is spelled as
+// a literal so this file also compiles — and then fails on behaviour — against
+// a tree that has no guard at all.
+const paginationHopCap = 10000
+
+// fakeLoopBudget bounds an unguarded run a little above the guard's own cap:
+// the fake answers 400 once the budget is gone, so a regression fails with the
+// wrong error instead of spinning forever.
+const fakeLoopBudget = paginationHopCap + 5
+
+func imaTestClient(t *testing.T, fake *fakeIMA) *client {
+ t.Helper()
+ cfg, err := parseIMAConfig(fake.config("kb-1"))
+ require.NoError(t, err)
+ return newClient(cfg)
+}
+
+// A vendor that keeps answering is_end=false with the same next_cursor used to
+// make all three loops request the same page until the task deadline. Each
+// loop must now stop as soon as a cursor repeats.
+func TestListResourcesRejectsRepeatedCursor(t *testing.T) {
+ fake := newFakeIMA(t)
+ fake.setKB("kb-1", nil)
+ fake.paging["get_addable_knowledge_base_list"] = fakePaging{
+ nextCursor: "same-cursor",
+ maxRequests: fakeLoopBudget,
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ _, err := NewConnector().ListResources(ctx, fake.config("kb-1"), "")
+ require.Error(t, err)
+ require.Equal(t, 2, fake.callCount("get_addable_knowledge_base_list"),
+ "the guard must reject the repeated cursor on the second page; err=%v", err)
+ require.Contains(t, err.Error(), `repeated next_cursor "same-cursor"`)
+}
+
+func TestListResourcesSearchFallbackRejectsRepeatedCursor(t *testing.T) {
+ fake := newFakeIMA(t)
+ // No addable knowledge bases: ListResources falls back to search.
+ fake.paging["search_knowledge_base"] = fakePaging{
+ nextCursor: "same-cursor",
+ maxRequests: fakeLoopBudget,
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ _, err := NewConnector().ListResources(ctx, fake.config(), "")
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "search_knowledge_base fallback")
+ require.Equal(t, 2, fake.callCount("search_knowledge_base"),
+ "the guard must reject the repeated cursor on the second page; err=%v", err)
+ require.Contains(t, err.Error(), `repeated next_cursor "same-cursor"`)
+}
+
+func TestListAllKBFilesRejectsRepeatedCursor(t *testing.T) {
+ fake := newFakeIMA(t)
+ fake.paging["get_knowledge_list"] = fakePaging{
+ nextCursor: "same-cursor",
+ maxRequests: fakeLoopBudget,
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ _, _, err := listAllKBFiles(ctx, imaTestClient(t, fake), "kb-1")
+ require.Error(t, err)
+ require.Equal(t, 2, fake.callCount("get_knowledge_list"),
+ "the guard must reject the repeated cursor on the second page; err=%v", err)
+ require.Contains(t, err.Error(), `repeated next_cursor "same-cursor"`)
+}
+
+// A vendor that hands back a brand new cursor on every page never repeats one,
+// so the repeat guard cannot stop it: the hop cap must, and it must say so in
+// the log instead of vanishing into a task deadline.
+func TestListResourcesSearchFallbackStopsAtPaginationCap(t *testing.T) {
+ fake := newFakeIMA(t)
+ fake.paging["search_knowledge_base"] = fakePaging{
+ nextCursor: "cursor",
+ advanceCursor: true,
+ maxRequests: fakeLoopBudget,
+ }
+
+ var logs bytes.Buffer
+ logger.SetOutput(&logs)
+ defer logger.SetOutput(os.Stdout)
+
+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
+ defer cancel()
+
+ _, err := NewConnector().ListResources(ctx, fake.config(), "")
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "pagination exceeded 10000 pages")
+ require.Equal(t, paginationHopCap, fake.callCount("search_knowledge_base"))
+ require.Contains(t, logs.String(), "pagination exceeded 10000 pages",
+ "hitting the hop cap must be visible in the log")
+}
+
+// The guard must not truncate a listing that genuinely spans several pages.
+func TestListAllKBFilesMergesRealPages(t *testing.T) {
+ fake := newFakeIMA(t)
+ fake.paging["get_knowledge_list"] = fakePaging{
+ nextCursor: "page",
+ advanceCursor: true,
+ stopAfter: 2, // page 2 ends the listing
+ filesByCall: map[int][]fakeFile{
+ 1: {{MediaID: "media-1", Title: "a.txt", MediaType: mediaTypeMarkdown}},
+ 2: {{MediaID: "media-2", Title: "b.txt", MediaType: mediaTypeMarkdown}},
+ },
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ files, _, err := listAllKBFiles(ctx, imaTestClient(t, fake), "kb-1")
+ require.NoError(t, err)
+ require.Len(t, files, 2)
+ require.Equal(t, 2, fake.callCount("get_knowledge_list"))
+ require.True(t, strings.HasSuffix(files[0].Title, "a.txt") || strings.HasSuffix(files[1].Title, "a.txt"))
+}