From 507ee69b242fa2c349ea5a39e4d63343e2886247 Mon Sep 17 00:00:00 2001 From: Dominik Schmidt Date: Fri, 27 Nov 2026 13:06:13 +0100 Subject: [PATCH] fix(graph): list tags through a terms aggregation The tag listing searched for every tagged resource with an unlimited page and collected the tags from the matches. OpenSearch answers an unlimited page with the first 1000 matches of a space, so tags that only resources beyond those carry were missing from the list. Bleve returned every match with all stored fields to read one of them. The listing now asks for a terms aggregation on the tags, ordered by key, without matches. The search counts every tagged resource on both engines and cuts the list at the 100 listed tags after merging the spaces, in the same byte order as before. AGG-47 pins that a tag is found whichever match carries it. --- services/graph/pkg/service/v0/tags.go | 59 ++++++---------- services/graph/pkg/service/v0/tags_test.go | 69 +++++-------------- services/search/pkg/parity/README.md | 1 + .../search/pkg/parity/aggregations_test.go | 11 ++- 4 files changed, 48 insertions(+), 92 deletions(-) diff --git a/services/graph/pkg/service/v0/tags.go b/services/graph/pkg/service/v0/tags.go index e4958f6061..f76fe13843 100644 --- a/services/graph/pkg/service/v0/tags.go +++ b/services/graph/pkg/service/v0/tags.go @@ -1,68 +1,43 @@ package svc import ( - "maps" "net/http" - "slices" "strings" rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" "github.com/go-chi/render" + libregraph "github.com/opencloud-eu/libre-graph-api-go" "github.com/opencloud-eu/opencloud/pkg/conversions" - searchmsg "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/messages/search/v0" searchsvc "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/services/search/v0" "github.com/opencloud-eu/opencloud/services/graph/pkg/errorcode" revaCtx "github.com/opencloud-eu/reva/v3/pkg/ctx" "github.com/opencloud-eu/reva/v3/pkg/events" "github.com/opencloud-eu/reva/v3/pkg/storagespace" "github.com/opencloud-eu/reva/v3/pkg/tags" - libregraph "github.com/opencloud-eu/libre-graph-api-go" "go-micro.dev/v4/metadata" ) // maxListedTags is the maximum number of tags that GetTags returns. It keeps -// the response small when many distinct tags are in use. Since the tags are -// sorted before the list is cut, the same tags are always the ones returned. +// the response small when many distinct tags are in use. const maxListedTags = 100 -// listedTags returns the distinct tags of the given search matches, sorted in -// byte order, and cut at maxListedTags. -// -// Byte order means that upper case comes before lower case ("Banana" before -// "apple"). It is used on purpose instead of a case-insensitive order, which -// would be nicer to read, because it is the order in which search engines sort -// keyword values, e.g. an OpenSearch terms aggregation ordered by key. With the -// same order here, the search can return just the first maxListedTags tags of -// every space, and merging those lists still gives exactly the first -// maxListedTags tags overall. With a case-insensitive order, that only works by -// aggregating on a lowercased copy of the field, which needs a mapping change -// and a reindex, and loses the original casing of the tags. Clients that want -// another order for display can sort the list themselves. -func listedTags(matches []*searchmsg.Match) []string { - distinct := make(map[string]struct{}) - for _, match := range matches { - for _, tag := range match.GetEntity().GetTags() { - if tag != "" { - distinct[tag] = struct{}{} - } - } - } - - // never nil: an empty list is rendered as "value": [], not left out - list := slices.AppendSeq(make([]string, 0, len(distinct)), maps.Keys(distinct)) - slices.Sort(list) - return list[:min(len(list), maxListedTags)] -} - -// GetTags returns the tags in use, see listedTags +// GetTags returns the tags in use: the first maxListedTags in byte order, +// upper case before lower case ("Banana" before "apple"). That is the order +// of the keys of a terms aggregation, so the search can cut the list. Clients +// that want another order for display can sort the list themselves. func (g Graph) GetTags(w http.ResponseWriter, r *http.Request) { th := r.Header.Get(revaCtx.TokenHeader) ctx := revaCtx.ContextSetToken(r.Context(), th) ctx = metadata.Set(ctx, revaCtx.TokenHeader, th) sr, err := g.searchService.Search(ctx, &searchsvc.SearchRequest{ Query: "Tags:*", - PageSize: conversions.ToPointer(int32(-1)), + PageSize: conversions.ToPointer(int32(0)), + Aggregations: []*searchsvc.AggregationOption{{ + Field: "Tags", + Size: maxListedTags, + BucketDefinition: &searchsvc.BucketDefinition{SortBy: searchsvc.BucketSortBy_BUCKET_SORT_BY_KEY_AS_STRING}, + }}, }) if err != nil { g.logger.Error().Err(err).Msg("Could not search for tags") @@ -70,8 +45,16 @@ func (g Graph) GetTags(w http.ResponseWriter, r *http.Request) { return } + // never nil: an empty list is rendered as "value": [], not left out + list := []string{} + if aggs := sr.GetAggregations(); len(aggs) > 0 { + for _, bucket := range aggs[0].GetBuckets() { + list = append(list, bucket.GetKey()) + } + } + tagCollection := libregraph.NewCollectionOfTags() - tagCollection.Value = listedTags(sr.GetMatches()) + tagCollection.Value = list render.Status(r, http.StatusOK) render.JSON(w, r, tagCollection) diff --git a/services/graph/pkg/service/v0/tags_test.go b/services/graph/pkg/service/v0/tags_test.go index 4cd191f172..2ae041d279 100644 --- a/services/graph/pkg/service/v0/tags_test.go +++ b/services/graph/pkg/service/v0/tags_test.go @@ -3,7 +3,6 @@ package svc_test import ( "encoding/json" "errors" - "fmt" "net/http" "net/http/httptest" @@ -15,7 +14,6 @@ import ( "github.com/opencloud-eu/opencloud/pkg/log" "github.com/opencloud-eu/opencloud/pkg/shared" - searchmsg "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/messages/search/v0" searchsvc "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/services/search/v0" searchmocks "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/services/search/v0/mocks" "github.com/opencloud-eu/opencloud/services/graph/pkg/config/defaults" @@ -32,13 +30,13 @@ var _ = Describe("GetTags", func() { tape *httptest.ResponseRecorder ) - // matchesWithTags returns one search match per argument, with the given tags - matchesWithTags := func(tagsPerMatch ...[]string) []*searchmsg.Match { - matches := make([]*searchmsg.Match, 0, len(tagsPerMatch)) - for _, tags := range tagsPerMatch { - matches = append(matches, &searchmsg.Match{Entity: &searchmsg.Entity{Tags: tags}}) + // tagBuckets answers like the search does: one bucket per tag + tagBuckets := func(tags ...string) *searchsvc.SearchResponse { + buckets := make([]*searchsvc.Bucket, 0, len(tags)) + for _, tag := range tags { + buckets = append(buckets, &searchsvc.Bucket{Key: tag, Count: 1}) } - return matches + return &searchsvc.SearchResponse{Aggregations: []*searchsvc.AggregationResult{{Field: "Tags", Buckets: buckets}}} } getTags := func() []string { @@ -72,68 +70,33 @@ var _ = Describe("GetTags", func() { Expect(err).ToNot(HaveOccurred()) }) - It("asks the search for all tagged resources", func() { + It("asks the search for the first tags in byte order, without matches", func() { searchService.EXPECT().Search(mock.Anything, mock.MatchedBy(func(req *searchsvc.SearchRequest) bool { - return req.GetQuery() == "Tags:*" && req.GetPageSize() == -1 + aggs := req.GetAggregations() + return req.GetQuery() == "Tags:*" && req.PageSize != nil && req.GetPageSize() == 0 && + len(aggs) == 1 && aggs[0].GetField() == "Tags" && + aggs[0].GetSize() == int32(service.MaxListedTagsForTest) && + aggs[0].GetBucketDefinition().GetSortBy() == searchsvc.BucketSortBy_BUCKET_SORT_BY_KEY_AS_STRING && + !aggs[0].GetBucketDefinition().GetIsDescending() })).Return(&searchsvc.SearchResponse{}, nil) Expect(getTags()).To(BeEmpty()) }) It("renders an empty list when no tags are in use", func() { - searchService.EXPECT().Search(mock.Anything, mock.Anything).Return(&searchsvc.SearchResponse{}, nil) + searchService.EXPECT().Search(mock.Anything, mock.Anything).Return(tagBuckets(), nil) svc.GetTags(tape, httptest.NewRequest(http.MethodGet, "/graph/v1.0/extensions/org.libregraph/tags", nil)) Expect(tape.Code).To(Equal(http.StatusOK)) Expect(tape.Body.String()).To(MatchJSON(`{"value": []}`)) }) - It("lists every tag once", func() { - searchService.EXPECT().Search(mock.Anything, mock.Anything).Return(&searchsvc.SearchResponse{ - Matches: matchesWithTags([]string{"work", "draft"}, []string{"draft", ""}, nil, []string{"work"}), - }, nil) - - Expect(getTags()).To(Equal([]string{"draft", "work"})) - }) - - It("sorts the tags in byte order, upper case before lower case", func() { - searchService.EXPECT().Search(mock.Anything, mock.Anything).Return(&searchsvc.SearchResponse{ - Matches: matchesWithTags([]string{"apple", "cherry"}, []string{"Apple", "Banana"}), - }, nil) + It("lists the tags as the search orders them", func() { + searchService.EXPECT().Search(mock.Anything, mock.Anything).Return(tagBuckets("Apple", "Banana", "apple", "cherry"), nil) Expect(getTags()).To(Equal([]string{"Apple", "Banana", "apple", "cherry"})) }) - It("returns the same list for the same tags, whatever the order of the search results", func() { - first := matchesWithTags([]string{"c", "a"}, []string{"b"}) - reversed := matchesWithTags([]string{"b"}, []string{"a", "c"}) - - searchService.EXPECT().Search(mock.Anything, mock.Anything).Return(&searchsvc.SearchResponse{Matches: first}, nil).Once() - firstResult := getTags() - - tape = httptest.NewRecorder() - searchService.EXPECT().Search(mock.Anything, mock.Anything).Return(&searchsvc.SearchResponse{Matches: reversed}, nil).Once() - Expect(getTags()).To(Equal(firstResult)) - }) - - It("returns only the first tags in sort order when more tags are in use than it lists", func() { - limit := service.MaxListedTagsForTest - // one more tag than listed, spread over several matches, in descending order - all := make([]string, 0, limit+1) - for i := limit; i >= 0; i-- { - all = append(all, fmt.Sprintf("tag%03d", i)) - } - searchService.EXPECT().Search(mock.Anything, mock.Anything).Return(&searchsvc.SearchResponse{ - Matches: matchesWithTags(all[:limit/2], all[limit/2:]), - }, nil) - - listed := getTags() - Expect(listed).To(HaveLen(limit)) - Expect(listed[0]).To(Equal("tag000")) - Expect(listed[limit-1]).To(Equal(fmt.Sprintf("tag%03d", limit-1))) - Expect(listed).ToNot(ContainElement(fmt.Sprintf("tag%03d", limit))) - }) - It("fails when the search fails", func() { searchService.EXPECT().Search(mock.Anything, mock.Anything).Return(nil, errors.New("search is down")) diff --git a/services/search/pkg/parity/README.md b/services/search/pkg/parity/README.md index a676790629..3f2716e935 100644 --- a/services/search/pkg/parity/README.md +++ b/services/search/pkg/parity/README.md @@ -919,6 +919,7 @@ Fixtures: | Case | Query | expected | bleve | OpenSearch | same? | |---|---|---|---|---|---| +| AGG-47 | `Tags:*` reads `one bucket per tag, whichever match carries it` | 150 items | Tags tag-000=53, Tags tag-001=53, Tags tag-002=53, Tags tag-003=53, Tags tag-004=53, Tags tag-005=53, Tags tag-006=53, Tags tag-007=53, … +142 more | Tags tag-000=53, Tags tag-001=53, Tags tag-002=53, Tags tag-003=53, Tags tag-004=53, Tags tag-005=53, Tags tag-006=53, Tags tag-007=53, … +142 more | ✅ | | AGG-17 | `mediatype:audio` reads `one bucket per artist, cardinality above the page size` | 10050 items | audio.arti...-00000=1, audio.arti...-00001=1, audio.arti...-00002=1, audio.arti...-00003=1, audio.arti...-00004=1, audio.arti...-00005=1, audio.arti...-00006=1, audio.arti...-00007=1, … +10042 more | audio.arti...-00000=1, audio.arti...-00001=1, audio.arti...-00002=1, audio.arti...-00003=1, audio.arti...-00004=1, audio.arti...-00005=1, audio.arti...-00006=1, audio.arti...-00007=1, … +10042 more | ✅ | | AGG-42 | `mediatype:audio` reads `the total counts every match` | 1 of 10050 matches | 1 of 10050 matches | 1 of 10050 matches | ✅ | | AGG-43 | `mediatype:audio` reads `a page reaching beyond the first 10000 matches` | 10001 of 10050 matches | 10001 of 10050 matches | bad request | ❌ known | diff --git a/services/search/pkg/parity/aggregations_test.go b/services/search/pkg/parity/aggregations_test.go index 2d32854eef..cf53603eff 100644 --- a/services/search/pkg/parity/aggregations_test.go +++ b/services/search/pkg/parity/aggregations_test.go @@ -390,7 +390,12 @@ func renderAggregation(prefix string, a *searchService.AggregationResult) []stri func cardinalityFixtures() []search.Resource { docs := make([]search.Resource, 0, 10050) for i := 0; i < 10050; i++ { - docs = append(docs, song(fmt.Sprintf("card-%05d.mp3", i), fmt.Sprintf("artist-%05d", i), "Singles", int32(1950+i%50))) + // tags only beyond the first 1000 songs, the page OpenSearch returns for "all matches" + var tagged []fixtureOption + if i >= 2000 { + tagged = append(tagged, withTags(fmt.Sprintf("tag-%03d", i%150))) + } + docs = append(docs, song(fmt.Sprintf("card-%05d.mp3", i), fmt.Sprintf("artist-%05d", i), "Singles", int32(1950+i%50), tagged...)) } return docs } @@ -406,7 +411,11 @@ func nested(fields ...string) *searchService.AggregationOption { func cardinalityCases() []aggCase { count := 10050 + tags := 150 return []aggCase{ + {id: 47, query: "Tags:*", reads: "one bucket per tag, whichever match carries it", + aggs: []*searchService.AggregationOption{{Field: "Tags"}}, + wantCount: &tags}, {id: 17, query: "mediatype:audio", reads: "one bucket per artist, cardinality above the page size", aggs: []*searchService.AggregationOption{{Field: "audio.artist"}}, wantCount: &count},