From 4e3d952c13ad8ed8cef5f828f64a0dbbb1fe5dd7 Mon Sep 17 00:00:00 2001 From: Florian Schade Date: Tue, 24 Nov 2026 13:45:03 +0100 Subject: [PATCH 1/6] fix(search): keep tika out of tag updates and retry incomplete extractions --- services/search/pkg/bleve/backend.go | 28 +++++- services/search/pkg/bleve/backend_test.go | 52 ++++++++++ .../pkg/bleve/testdata/mapping.golden.json | 13 +++ services/search/pkg/content/tika.go | 3 +- services/search/pkg/content/tika_test.go | 11 +++ services/search/pkg/opensearch/backend.go | 58 ++++++++++++ .../search/pkg/opensearch/backend_test.go | 66 +++++++++++++ .../opensearch/testdata/resource.golden.json | 3 + services/search/pkg/search/mocks/engine.go | 63 +++++++++++++ services/search/pkg/search/mocks/searcher.go | 40 ++++++++ services/search/pkg/search/search.go | 13 +++ services/search/pkg/search/service.go | 43 ++++++++- services/search/pkg/search/service_test.go | 94 ++++++++++++++++++- services/search/pkg/service/event/service.go | 8 +- .../search/pkg/service/event/service_test.go | 8 +- 15 files changed, 486 insertions(+), 17 deletions(-) diff --git a/services/search/pkg/bleve/backend.go b/services/search/pkg/bleve/backend.go index 17474bed50..fa17ce5fef 100644 --- a/services/search/pkg/bleve/backend.go +++ b/services/search/pkg/bleve/backend.go @@ -16,6 +16,7 @@ import ( "github.com/opencloud-eu/opencloud/pkg/kql" "github.com/opencloud-eu/opencloud/pkg/log" + "github.com/opencloud-eu/opencloud/services/search/pkg/mapping" "github.com/opencloud-eu/opencloud/services/search/pkg/search" searchMessage "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/messages/search/v0" @@ -28,7 +29,7 @@ const defaultBatchSize = 50 var _ search.Engine = (*Backend)(nil) // ensure Backend implements Engine type Backend struct { - index bleve.Index + index *serialIndex queryCreator searchQuery.Creator[query.Query] log log.Logger } @@ -178,6 +179,31 @@ func (b *Backend) Get(_ context.Context, id string) (*search.Resource, error) { return searchResourceByID(id, b.index) } +// Update holds the batch lock from the read to the write, so a batch pushed in +// between cannot be overwritten with the document as it was before +func (b *Backend) Update(_ context.Context, id string, u search.MetadataUpdate) error { + b.index.batchMu.Lock() + defer b.index.batchMu.Unlock() + + r, err := searchResourceByID(id, b.index) + if err != nil { + return err + } + r.Tags = u.Tags + r.Favorites = u.Favorites + + doc, err := mapping.PrepareForIndex(r, r.SearchFieldOverrides()) + if err != nil { + return err + } + batch := b.index.NewBatch() + err = batch.Index(id, doc) + if err != nil { + return err + } + return b.index.bleveIndex.Batch(batch) +} + func (b *Backend) DocCount() (uint64, error) { return b.index.DocCount() } diff --git a/services/search/pkg/bleve/backend_test.go b/services/search/pkg/bleve/backend_test.go index 270c821183..db84988590 100644 --- a/services/search/pkg/bleve/backend_test.go +++ b/services/search/pkg/bleve/backend_test.go @@ -11,6 +11,7 @@ import ( . "github.com/onsi/gomega" "github.com/opencloud-eu/opencloud/pkg/log" + searchService "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/services/search/v0" "github.com/opencloud-eu/opencloud/services/search/pkg/bleve" "github.com/opencloud-eu/opencloud/services/search/pkg/content" bleveQuery "github.com/opencloud-eu/opencloud/services/search/pkg/query/bleve" @@ -138,6 +139,57 @@ var _ = Describe("Bleve", func() { }) }) + Describe("Update", func() { + tagHits := func(tag string) []string { + res, err := eng.Search(context.Background(), &searchService.SearchIndexRequest{Query: `tag:("` + tag + `")`}) + Expect(err).ToNot(HaveOccurred()) + var ids []string + for _, match := range res.GetMatches() { + ids = append(ids, match.GetEntity().GetId().GetOpaqueId()) + } + return ids + } + + It("rewrites tags and favorites and keeps the extracted fields", func() { + childResource.Content = "quarterly report" + childResource.Tags = []string{"alpha"} + childResource.Extracted = true + Expect(eng.Upsert(childResource.ID, childResource)).To(Succeed()) + + Expect(eng.Update(context.Background(), childResource.ID, search.MetadataUpdate{ + Tags: []string{"Beta"}, + Favorites: []string{"user-1"}, + })).To(Succeed()) + + r, err := eng.Get(context.Background(), childResource.ID) + Expect(err).ToNot(HaveOccurred()) + Expect(r.Tags).To(Equal([]string{"Beta"})) + Expect(r.Favorites).To(Equal([]string{"user-1"})) + Expect(r.Content).To(Equal("quarterly report")) + Expect(r.Extracted).To(BeTrue()) + + Expect(tagHits("beta")).To(ConsistOf("4"), "the lowercase sibling follows the new tag") + Expect(tagHits("alpha")).To(BeEmpty()) + }) + + It("clears the tags", func() { + childResource.Tags = []string{"alpha"} + Expect(eng.Upsert(childResource.ID, childResource)).To(Succeed()) + + Expect(eng.Update(context.Background(), childResource.ID, search.MetadataUpdate{})).To(Succeed()) + + r, err := eng.Get(context.Background(), childResource.ID) + Expect(err).ToNot(HaveOccurred()) + Expect(r.Tags).To(BeEmpty()) + Expect(tagHits("alpha")).To(BeEmpty()) + }) + + It("fails with ErrResourceNotFound for an unknown id", func() { + err := eng.Update(context.Background(), "1$2!unknown", search.MetadataUpdate{Tags: []string{"alpha"}}) + Expect(err).To(MatchError(search.ErrResourceNotFound)) + }) + }) + Describe("New", func() { It("returns a new index instance", func() { b := bleve.NewBackend(idx, bleveQuery.DefaultCreator, log.Logger{}) diff --git a/services/search/pkg/bleve/testdata/mapping.golden.json b/services/search/pkg/bleve/testdata/mapping.golden.json index 73f6baa748..88ad94cbc2 100644 --- a/services/search/pkg/bleve/testdata/mapping.golden.json +++ b/services/search/pkg/bleve/testdata/mapping.golden.json @@ -30,6 +30,19 @@ } ] }, + "Extracted": { + "enabled": true, + "dynamic": true, + "fields": [ + { + "type": "boolean", + "store": true, + "index": true, + "include_in_all": true, + "docvalues": true + } + ] + }, "Favorites": { "enabled": true, "dynamic": true, diff --git a/services/search/pkg/content/tika.go b/services/search/pkg/content/tika.go index 767f8a0d98..035d4b9fa4 100644 --- a/services/search/pkg/content/tika.go +++ b/services/search/pkg/content/tika.go @@ -82,8 +82,9 @@ func (t Tika) Extract(ctx context.Context, ri *provider.ResourceInfo) (Document, if err != nil { return doc, err } + // a file with content always yields metadata, none means tika failed on it if len(metas) == 0 { - return doc, nil + return doc, fmt.Errorf("tika returned no metadata for %q", ri.GetName()) } for _, meta := range metas { diff --git a/services/search/pkg/content/tika_test.go b/services/search/pkg/content/tika_test.go index f0b1850879..62c5f248b1 100644 --- a/services/search/pkg/content/tika_test.go +++ b/services/search/pkg/content/tika_test.go @@ -99,6 +99,17 @@ var _ = Describe("Tika", func() { Expect(doc.Content).To(Equal(body)) }) + It("fails when tika returns no metadata for a file with content", func() { + fullResponse = "[]" + + _, err := tika.Extract(context.TODO(), &provider.ResourceInfo{ + Type: provider.ResourceType_RESOURCE_TYPE_FILE, + Name: "report.pdf", + Size: 1, + }) + Expect(err).To(MatchError(ContainSubstring("report.pdf"))) + }) + It("adds the title", func() { fullResponse = `[{"dc:title": "quarterly report", "X-TIKA:content": "some data"}]` diff --git a/services/search/pkg/opensearch/backend.go b/services/search/pkg/opensearch/backend.go index d56fd6d731..d5610a4483 100644 --- a/services/search/pkg/opensearch/backend.go +++ b/services/search/pkg/opensearch/backend.go @@ -1,11 +1,16 @@ package opensearch import ( + "bytes" "context" + "encoding/json" + "errors" "fmt" + "reflect" "time" storageProvider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" + opensearchgo "github.com/opensearch-project/opensearch-go/v4" opensearchgoAPI "github.com/opensearch-project/opensearch-go/v4/opensearchapi" "github.com/opencloud-eu/reva/v3/pkg/errtypes" @@ -17,6 +22,7 @@ import ( "github.com/opencloud-eu/opencloud/pkg/log" searchMessage "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/messages/search/v0" searchService "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/services/search/v0" + "github.com/opencloud-eu/opencloud/services/search/pkg/mapping" "github.com/opencloud-eu/opencloud/services/search/pkg/opensearch/internal/convert" "github.com/opencloud-eu/opencloud/services/search/pkg/opensearch/internal/osu" "github.com/opencloud-eu/opencloud/services/search/pkg/search" @@ -24,6 +30,10 @@ import ( const defaultBatchSize = 50 +// updateRetries lets OpenSearch merge a partial update again onto a document +// another write changed between its read and its write +const updateRetries = 3 + var ( ErrUnhealthyCluster = fmt.Errorf("cluster is not healthy") ) @@ -178,6 +188,54 @@ func (b *Backend) Get(ctx context.Context, id string) (*search.Resource, error) return &resource, nil } +// Update sends a partial document, OpenSearch merges it into the stored one, so +// the extracted fields are never read and written back +func (b *Backend) Update(ctx context.Context, id string, u search.MetadataUpdate) error { + r := search.Resource{} + r.Tags = u.Tags + r.Favorites = u.Favorites + full, err := mapping.PrepareForIndex(r, r.SearchFieldOverrides()) + if err != nil { + return fmt.Errorf("failed to prepare the update: %w", err) + } + + // a field the update empties has no sibling in full, the explicit null clears the stale one + siblings := mapping.SearchSiblings(reflect.TypeFor[search.Resource](), r.SearchFieldOverrides()) + partial := map[string]any{} + for _, field := range []string{"Tags", "Favorites"} { + partial[field] = full[field] + if siblings[field].Lowercase { + partial[field+mapping.LowercaseSuffix] = full[field+mapping.LowercaseSuffix] + } + if siblings[field].Words { + partial[field+mapping.WordsSuffix] = full[field+mapping.WordsSuffix] + } + } + + body, err := json.Marshal(map[string]any{"doc": partial}) + if err != nil { + return fmt.Errorf("failed to marshal the update: %w", err) + } + + _, err = b.client.Update(ctx, opensearchgoAPI.UpdateReq{ + Index: b.index, + DocumentID: id, + Body: bytes.NewReader(body), + Params: opensearchgoAPI.UpdateParams{ + Refresh: "wait_for", + RetryOnConflict: new(updateRetries), + }, + }) + var structErr *opensearchgo.StructError + switch { + case errors.As(err, &structErr) && structErr.Err.Type == "document_missing_exception": + return fmt.Errorf("document with id %s: %w", id, search.ErrResourceNotFound) + case err != nil: + return fmt.Errorf("failed to update the document: %w", err) + } + return nil +} + func (b *Backend) DocCount() (uint64, error) { req, err := osu.BuildIndicesCountReq( &opensearchgoAPI.IndicesCountReq{ diff --git a/services/search/pkg/opensearch/backend_test.go b/services/search/pkg/opensearch/backend_test.go index 2fa0c0b2c6..ae7b1aaeba 100644 --- a/services/search/pkg/opensearch/backend_test.go +++ b/services/search/pkg/opensearch/backend_test.go @@ -11,6 +11,7 @@ import ( opensearchgoAPI "github.com/opensearch-project/opensearch-go/v4/opensearchapi" "github.com/opencloud-eu/opencloud/pkg/log" + searchService "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/services/search/v0" "github.com/opencloud-eu/opencloud/services/search/internal/opensearchtest" "github.com/opencloud-eu/opencloud/services/search/pkg/opensearch" "github.com/opencloud-eu/opencloud/services/search/pkg/search" @@ -127,4 +128,69 @@ var _ = Describe("Backend", func() { Expect(err).To(MatchError(search.ErrResourceNotFound)) }) }) + + Describe("Update", func() { + const indexName = "opencloud-test-engine-update" + + var backend *opensearch.Backend + + BeforeEach(func() { + physical := opensearch.VersionedIndexName(indexName) + + tc := opensearchtest.NewDefaultTestClient(GinkgoTB(), defaultConfig.Engine.OpenSearch.Client) + tc.Require.IndicesReset([]string{physical}) + deleteIndexOnCleanup(tc, physical) + + var err error + backend, err = opensearch.NewBackend(context.Background(), indexName, tc.Client(), log.NopLogger()) + Expect(err).ToNot(HaveOccurred()) + }) + + tagHits := func(tag string) int { + res, err := backend.Search(context.Background(), &searchService.SearchIndexRequest{Query: `tag:("` + tag + `")`}) + Expect(err).ToNot(HaveOccurred()) + return len(res.GetMatches()) + } + + It("rewrites tags and favorites and keeps the extracted fields", func() { + document := opensearchtest.Testdata.Resources.File + document.Content = "quarterly report" + document.Tags = []string{"alpha"} + document.Extracted = true + Expect(backend.Upsert(document.ID, document)).To(Succeed()) + + Expect(backend.Update(context.Background(), document.ID, search.MetadataUpdate{ + Tags: []string{"Beta"}, + Favorites: []string{"user-1"}, + })).To(Succeed()) + + r, err := backend.Get(context.Background(), document.ID) + Expect(err).ToNot(HaveOccurred()) + Expect(r.Tags).To(Equal([]string{"Beta"})) + Expect(r.Favorites).To(Equal([]string{"user-1"})) + Expect(r.Content).To(Equal("quarterly report")) + Expect(r.Extracted).To(BeTrue()) + + Expect(tagHits("beta")).To(Equal(1), "the lowercase sibling follows the new tag") + Expect(tagHits("alpha")).To(BeZero()) + }) + + It("clears the tags and their lowercase sibling", func() { + document := opensearchtest.Testdata.Resources.File + document.Tags = []string{"alpha"} + Expect(backend.Upsert(document.ID, document)).To(Succeed()) + + Expect(backend.Update(context.Background(), document.ID, search.MetadataUpdate{})).To(Succeed()) + + r, err := backend.Get(context.Background(), document.ID) + Expect(err).ToNot(HaveOccurred()) + Expect(r.Tags).To(BeEmpty()) + Expect(tagHits("ALPHA")).To(BeZero()) + }) + + It("fails with ErrResourceNotFound for an unknown id", func() { + err := backend.Update(context.Background(), "1$2!unknown", search.MetadataUpdate{Tags: []string{"alpha"}}) + Expect(err).To(MatchError(search.ErrResourceNotFound)) + }) + }) }) diff --git a/services/search/pkg/opensearch/testdata/resource.golden.json b/services/search/pkg/opensearch/testdata/resource.golden.json index ab343eef11..6512c2c1b7 100644 --- a/services/search/pkg/opensearch/testdata/resource.golden.json +++ b/services/search/pkg/opensearch/testdata/resource.golden.json @@ -9,6 +9,9 @@ "Deleted": { "type": "boolean" }, + "Extracted": { + "type": "boolean" + }, "Favorites": { "type": "keyword" }, diff --git a/services/search/pkg/search/mocks/engine.go b/services/search/pkg/search/mocks/engine.go index 9fdee306ef..6797500fc3 100644 --- a/services/search/pkg/search/mocks/engine.go +++ b/services/search/pkg/search/mocks/engine.go @@ -563,6 +563,69 @@ func (_c *Engine_Search_Call) RunAndReturn(run func(ctx context.Context, req *v0 return _c } +// Update provides a mock function for the type Engine +func (_mock *Engine) Update(ctx context.Context, id string, u search.MetadataUpdate) error { + ret := _mock.Called(ctx, id, u) + + if len(ret) == 0 { + panic("no return value specified for Update") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(context.Context, string, search.MetadataUpdate) error); ok { + r0 = returnFunc(ctx, id, u) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// Engine_Update_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Update' +type Engine_Update_Call struct { + *mock.Call +} + +// Update is a helper method to define mock.On call +// - ctx context.Context +// - id string +// - u search.MetadataUpdate +func (_e *Engine_Expecter) Update(ctx any, id any, u any) *Engine_Update_Call { + return &Engine_Update_Call{Call: _e.mock.On("Update", ctx, id, u)} +} + +func (_c *Engine_Update_Call) Run(run func(ctx context.Context, id string, u search.MetadataUpdate)) *Engine_Update_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 search.MetadataUpdate + if args[2] != nil { + arg2 = args[2].(search.MetadataUpdate) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Engine_Update_Call) Return(err error) *Engine_Update_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Engine_Update_Call) RunAndReturn(run func(ctx context.Context, id string, u search.MetadataUpdate) error) *Engine_Update_Call { + _c.Call.Return(run) + return _c +} + // Upsert provides a mock function for the type Engine func (_mock *Engine) Upsert(id string, r search.Resource) error { ret := _mock.Called(id, r) diff --git a/services/search/pkg/search/mocks/searcher.go b/services/search/pkg/search/mocks/searcher.go index 563cdfede6..dcd8c08a9f 100644 --- a/services/search/pkg/search/mocks/searcher.go +++ b/services/search/pkg/search/mocks/searcher.go @@ -426,6 +426,46 @@ func (_c *Searcher_TrashItem_Call) RunAndReturn(run func(resourceID *providerv1b return _c } +// UpdateMetadata provides a mock function for the type Searcher +func (_mock *Searcher) UpdateMetadata(ref *providerv1beta1.Reference) { + _mock.Called(ref) + return +} + +// Searcher_UpdateMetadata_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateMetadata' +type Searcher_UpdateMetadata_Call struct { + *mock.Call +} + +// UpdateMetadata is a helper method to define mock.On call +// - ref *providerv1beta1.Reference +func (_e *Searcher_Expecter) UpdateMetadata(ref any) *Searcher_UpdateMetadata_Call { + return &Searcher_UpdateMetadata_Call{Call: _e.mock.On("UpdateMetadata", ref)} +} + +func (_c *Searcher_UpdateMetadata_Call) Run(run func(ref *providerv1beta1.Reference)) *Searcher_UpdateMetadata_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *providerv1beta1.Reference + if args[0] != nil { + arg0 = args[0].(*providerv1beta1.Reference) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Searcher_UpdateMetadata_Call) Return() *Searcher_UpdateMetadata_Call { + _c.Call.Return() + return _c +} + +func (_c *Searcher_UpdateMetadata_Call) RunAndReturn(run func(ref *providerv1beta1.Reference)) *Searcher_UpdateMetadata_Call { + _c.Run(run) + return _c +} + // UpsertItem provides a mock function for the type Searcher func (_mock *Searcher) UpsertItem(ref *providerv1beta1.Reference) { _mock.Called(ref) diff --git a/services/search/pkg/search/search.go b/services/search/pkg/search/search.go index a046cc88d8..fba76509fc 100644 --- a/services/search/pkg/search/search.go +++ b/services/search/pkg/search/search.go @@ -50,10 +50,20 @@ type Engine interface { Purge(id string, onlyDeleted bool) error PurgeSpace(rootID string) error Get(ctx context.Context, id string) (*Resource, error) + // Update rewrites the fields u carries on the indexed document and keeps the + // rest, ErrResourceNotFound if the index holds no document with that id + Update(ctx context.Context, id string, u MetadataUpdate) error NewBatch(batchSize int) (BatchOperator, error) } +// MetadataUpdate holds the fields a tag or label change rewrites. Both come from +// the stat, so the extracted content stays and tika is not asked again. +type MetadataUpdate struct { + Tags []string + Favorites []string +} + type BatchOperator interface { Upsert(id string, r Resource) error Move(id string, parentID string, targetPath string) error @@ -75,6 +85,9 @@ type Resource struct { Type uint64 `json:"Type"` Deleted bool `json:"Deleted"` Hidden bool `json:"Hidden"` + // Extracted is set once the content extraction succeeded, a document + // without it is extracted again on the next reindex + Extracted bool `json:"Extracted"` } // resourceFieldOverrides is built once (it never changes) and reused on hot diff --git a/services/search/pkg/search/service.go b/services/search/pkg/search/service.go index 9333398cdb..564fe08db3 100644 --- a/services/search/pkg/search/service.go +++ b/services/search/pkg/search/service.go @@ -64,6 +64,7 @@ type Searcher interface { TrashItem(resourceID *provider.ResourceId) PurgeItem(ref *provider.Reference) UpsertItem(ref *provider.Reference) + UpdateMetadata(ref *provider.Reference) RestoreItem(ref *provider.Reference) MoveItem(ref *provider.Reference) } @@ -680,6 +681,43 @@ func (s *Service) UpsertItem(ref *provider.Reference) { s.doUpsertItem(ctx, ref, nil) } +// UpdateMetadata rewrites the tags and favorites of an indexed resource without +// extracting its content again, a resource not indexed yet is upserted in full. +func (s *Service) UpdateMetadata(ref *provider.Reference) { + ctx, err := getAuthContext(s.serviceAccountID, s.gatewaySelector, s.serviceAccountSecret, s.logger) + if err != nil { + s.logger.Error().Err(err).Msg("failed to get auth context") + return + } + + stat, _ := s.resInfo(ctx, ref) + if stat == nil { + return + } + + basic, err := content.NewBasicExtractor(s.logger) + if err != nil { + s.logger.Error().Err(err).Msg("failed to create the basic extractor") + return + } + doc, err := basic.Extract(ctx, stat.GetInfo()) + if err != nil { + s.logger.Error().Err(err).Msg("failed to read the resource metadata") + return + } + + err = s.engine.Update(ctx, storagespace.FormatResourceID(stat.GetInfo().GetId()), MetadataUpdate{ + Tags: doc.Tags, + Favorites: doc.Favorites, + }) + switch { + case errors.Is(err, ErrResourceNotFound): + s.doUpsertItem(ctx, ref, nil) + case err != nil: + s.logger.Error().Err(err).Interface("id", stat.GetInfo().GetId()).Msg("failed to update the resource metadata in the index") + } +} + // doUpsertItem indexes or stores Resource data fields. func (s *Service) doUpsertItem(ctx context.Context, ref *provider.Reference, batch BatchOperator) { stat, path := s.resInfo(ctx, ref) @@ -710,6 +748,7 @@ func (s *Service) doUpsertItem(ctx context.Context, ref *provider.Reference, bat Document: doc, } r.Hidden = IsHidden(r.Path) + r.Extracted = true if parentID := stat.GetInfo().GetParentId(); parentID != nil { r.ParentID = storagespace.FormatResourceID(parentID) @@ -895,7 +934,7 @@ func (s *Service) MoveItem(ref *provider.Reference) { } } -// isIndexed reports whether the index holds a live document for info that is at least as new +// isIndexed reports whether the index holds a live, fully extracted document for info that is at least as new func (s *Service) isIndexed(ctx context.Context, info *provider.ResourceInfo) bool { r, err := s.engine.Get(ctx, storagespace.FormatResourceID(info.GetId())) switch { @@ -905,7 +944,7 @@ func (s *Service) isIndexed(ctx context.Context, info *provider.ResourceInfo) bo s.logger.Error().Err(err).Interface("id", info.GetId()).Msg("failed to look up the indexed resource, indexing it again") return false } - return !r.Deleted && r.Mtime != nil && !r.Mtime.Before(utils.TSToTime(info.GetMtime())) + return !r.Deleted && r.Extracted && r.Mtime != nil && !r.Mtime.Before(utils.TSToTime(info.GetMtime())) } func (s *Service) resInfo(ctx context.Context, ref *provider.Reference) (*provider.StatResponse, string) { diff --git a/services/search/pkg/search/service_test.go b/services/search/pkg/search/service_test.go index 5ebef078e7..3b1cf06ae9 100644 --- a/services/search/pkg/search/service_test.go +++ b/services/search/pkg/search/service_test.go @@ -2,6 +2,7 @@ package search_test import ( "context" + "errors" "time" gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" @@ -157,12 +158,14 @@ var _ = Describe("Searchprovider", func() { info("outdated", sprovider.ResourceType_RESOURCE_TYPE_FILE, 5000), info("missing", sprovider.ResourceType_RESOURCE_TYPE_FILE, 4000), info("trashed", sprovider.ResourceType_RESOURCE_TYPE_FILE, 4000), + info("unextracted", sprovider.ResourceType_RESOURCE_TYPE_FILE, 4000), } indexed := map[string]*search.Resource{ - "storageid$spaceid!spaceid": {Document: content.Document{Mtime: &indexedAt}}, - "storageid$spaceid!current": {Document: content.Document{Mtime: &indexedAt}}, - "storageid$spaceid!outdated": {Document: content.Document{Mtime: &indexedAt}}, - "storageid$spaceid!trashed": {Document: content.Document{Mtime: &indexedAt}, Deleted: true}, + "storageid$spaceid!spaceid": {Document: content.Document{Mtime: &indexedAt}, Extracted: true}, + "storageid$spaceid!current": {Document: content.Document{Mtime: &indexedAt}, Extracted: true}, + "storageid$spaceid!outdated": {Document: content.Document{Mtime: &indexedAt}, Extracted: true}, + "storageid$spaceid!trashed": {Document: content.Document{Mtime: &indexedAt}, Extracted: true, Deleted: true}, + "storageid$spaceid!unextracted": {Document: content.Document{Mtime: &indexedAt}}, } gatewayClient.On("GetUserByClaim", mock.Anything, mock.Anything).Return(&userv1beta1.GetUserByClaimResponse{ @@ -201,7 +204,7 @@ var _ = Describe("Searchprovider", func() { err := s.IndexSpace(&sprovider.StorageSpaceId{OpaqueId: "storageid$spaceid!spaceid"}, false) Expect(err).ShouldNot(HaveOccurred()) - Expect(upserted).To(ConsistOf("storageid$spaceid!outdated", "storageid$spaceid!missing", "storageid$spaceid!trashed")) + Expect(upserted).To(ConsistOf("storageid$spaceid!outdated", "storageid$spaceid!missing", "storageid$spaceid!trashed", "storageid$spaceid!unextracted")) }) }) @@ -243,6 +246,22 @@ var _ = Describe("Searchprovider", func() { Entry("/", "/", false), ) + It("marks the resource as extracted", func() { + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(&sprovider.StatResponse{ + Status: status.NewOK(context.Background()), + Info: ri, + }, nil) + extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, nil) + + var indexed search.Resource + indexClient.On("Upsert", mock.Anything, mock.Anything).Run(func(args mock.Arguments) { + indexed = args.Get(1).(search.Resource) + }).Return(nil) + + s.UpsertItem(&sprovider.Reference{ResourceId: ri.GetId()}) + Expect(indexed.Extracted).To(BeTrue()) + }) + Context("with facets stored on the resource", func() { var ( info *sprovider.ResourceInfo @@ -384,6 +403,71 @@ var _ = Describe("Searchprovider", func() { Entry("a traversal out of a dot folder", "./.git/../notes.txt", false), ) + Describe("UpdateMetadata", func() { + var info *sprovider.ResourceInfo + + BeforeEach(func() { + info = &sprovider.ResourceInfo{ + Id: &sprovider.ResourceId{StorageId: "storageid", SpaceId: "spaceid", OpaqueId: "tagged-opaqueid"}, + ParentId: &sprovider.ResourceId{StorageId: "storageid", OpaqueId: "parentopaqueid"}, + Path: "./report.pdf", + Size: 12345, + ArbitraryMetadata: &sprovider.ArbitraryMetadata{ + Metadata: map[string]string{"tags": "alpha,beta"}, + }, + Opaque: &typesv1beta1.Opaque{ + Map: map[string]*typesv1beta1.OpaqueEntry{ + "favorites": {Decoder: "json", Value: []byte(`["user-1"]`)}, + }, + }, + } + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(&sprovider.StatResponse{ + Status: status.NewOK(context.Background()), + Info: info, + }, nil) + gatewayClient.On("GetPath", mock.Anything, mock.MatchedBy(func(req *sprovider.GetPathRequest) bool { + return req.GetResourceId().GetOpaqueId() == info.GetId().GetOpaqueId() + })).Return(&sprovider.GetPathResponse{ + Status: status.NewOK(context.Background()), + Path: info.GetPath(), + }, nil) + }) + + It("rewrites the tags and favorites without extracting the content", func() { + indexClient.On("Update", mock.Anything, "storageid$spaceid!tagged-opaqueid", search.MetadataUpdate{ + Tags: []string{"alpha", "beta"}, + Favorites: []string{"user-1"}, + }).Return(nil) + + s.UpdateMetadata(&sprovider.Reference{ResourceId: info.GetId()}) + indexClient.AssertNumberOfCalls(GinkgoT(), "Update", 1) + extractor.AssertNotCalled(GinkgoT(), "Extract", mock.Anything, mock.Anything) + indexClient.AssertNotCalled(GinkgoT(), "Upsert", mock.Anything, mock.Anything) + }) + + It("indexes the resource in full when the index does not hold it yet", func() { + indexClient.On("Update", mock.Anything, mock.Anything, mock.Anything).Return(search.ErrResourceNotFound) + extractor.On("Extract", mock.Anything, mock.Anything).Return(content.Document{Tags: []string{"alpha", "beta"}}, nil) + + var indexed search.Resource + indexClient.On("Upsert", mock.Anything, mock.Anything).Run(func(args mock.Arguments) { + indexed = args.Get(1).(search.Resource) + }).Return(nil) + + s.UpdateMetadata(&sprovider.Reference{ResourceId: info.GetId()}) + Expect(indexed.ID).To(Equal("storageid$spaceid!tagged-opaqueid")) + Expect(indexed.Extracted).To(BeTrue()) + }) + + It("does not extract the content when the update fails for another reason", func() { + indexClient.On("Update", mock.Anything, mock.Anything, mock.Anything).Return(errors.New("cluster unavailable")) + + s.UpdateMetadata(&sprovider.Reference{ResourceId: info.GetId()}) + extractor.AssertNotCalled(GinkgoT(), "Extract", mock.Anything, mock.Anything) + indexClient.AssertNotCalled(GinkgoT(), "Upsert", mock.Anything, mock.Anything) + }) + }) + Describe("Search", func() { It("fails when an empty query is given", func() { res, err := s.Search(ctx, &searchsvc.SearchRequest{ diff --git a/services/search/pkg/service/event/service.go b/services/search/pkg/service/event/service.go index f3becfe0d3..86c277b423 100644 --- a/services/search/pkg/service/event/service.go +++ b/services/search/pkg/service/event/service.go @@ -205,10 +205,10 @@ func (s Service) processEvent(e raw.Event) error { case events.FileVersionRestored: debounce(getSpaceID(ev.Ref), false) case events.TagsAdded: - s.index.UpsertItem(ev.Ref) + s.index.UpdateMetadata(ev.Ref) debounce(getSpaceID(ev.Ref), false) case events.TagsRemoved: - s.index.UpsertItem(ev.Ref) + s.index.UpdateMetadata(ev.Ref) debounce(getSpaceID(ev.Ref), false) case events.FileUploaded: debounce(getSpaceID(ev.Ref), false) @@ -240,9 +240,9 @@ func (s Service) processEvent(e raw.Event) error { s.log.Error().Err(err).Interface("spaceID", ev.ID).Msg("failed to remove space from the skipped spaces bucket") } case events.LabelAdded: - s.index.UpsertItem(ev.Ref) + s.index.UpdateMetadata(ev.Ref) case events.LabelRemoved: - s.index.UpsertItem(ev.Ref) + s.index.UpdateMetadata(ev.Ref) default: s.log.Error().Interface("event", e).Msg("unhandled event type, acknowledged without indexing") } diff --git a/services/search/pkg/service/event/service_test.go b/services/search/pkg/service/event/service_test.go index 4c81f412d0..b54fc76113 100644 --- a/services/search/pkg/service/event/service_test.go +++ b/services/search/pkg/service/event/service_test.go @@ -57,16 +57,16 @@ var _ = DescribeTable("event", Entry("SpaceDeleted", []string{"PurgeSpace"}, events.SpaceDeleted{}, false), Entry("ItemPurged", []string{"PurgeItem"}, events.ItemPurged{}, false), Entry("TrashbinPurged", []string{"PurgeDeleted"}, events.TrashbinPurged{}, false), - Entry("LabelAdded", []string{"UpsertItem"}, events.LabelAdded{}, false), - Entry("LabelRemoved", []string{"UpsertItem"}, events.LabelRemoved{}, false), + Entry("LabelAdded", []string{"UpdateMetadata"}, events.LabelAdded{}, false), + Entry("LabelRemoved", []string{"UpdateMetadata"}, events.LabelRemoved{}, false), Entry("ItemTrashed", []string{"TrashItem", "IndexSpace"}, events.ItemTrashed{}, false), Entry("ItemMoved", []string{"MoveItem", "IndexSpace"}, events.ItemMoved{}, false), Entry("ItemRestored", []string{"RestoreItem", "IndexSpace"}, events.ItemRestored{}, false), Entry("ContainerCreated", []string{"IndexSpace"}, events.ContainerCreated{}, false), Entry("FileTouched", []string{"IndexSpace"}, events.FileTouched{}, false), Entry("FileVersionRestored", []string{"IndexSpace"}, events.FileVersionRestored{}, false), - Entry("TagsAdded", []string{"UpsertItem", "IndexSpace"}, events.TagsAdded{}, false), - Entry("TagsRemoved", []string{"UpsertItem", "IndexSpace"}, events.TagsRemoved{}, false), + Entry("TagsAdded", []string{"UpdateMetadata", "IndexSpace"}, events.TagsAdded{}, false), + Entry("TagsRemoved", []string{"UpdateMetadata", "IndexSpace"}, events.TagsRemoved{}, false), Entry("FileUploaded", []string{"IndexSpace"}, events.FileUploaded{}, false), Entry("UploadReady", []string{"IndexSpace"}, events.UploadReady{ExecutingUser: &userv1beta1.User{}}, true), ) From 6cfc198663b72ba1efb4ef4fbe5d0ea13ed7f3e2 Mon Sep 17 00:00:00 2001 From: Florian Schade Date: Tue, 24 Nov 2026 16:20:57 +0100 Subject: [PATCH 2/6] fix(search): keep existing index entries out of the upgrade reindex --- services/search/pkg/bleve/backend_test.go | 2 -- .../pkg/bleve/testdata/mapping.golden.json | 13 --------- .../search/pkg/opensearch/backend_test.go | 2 -- .../opensearch/testdata/resource.golden.json | 3 -- services/search/pkg/search/search.go | 3 -- services/search/pkg/search/service.go | 5 ++-- services/search/pkg/search/service_test.go | 29 ++++--------------- 7 files changed, 7 insertions(+), 50 deletions(-) diff --git a/services/search/pkg/bleve/backend_test.go b/services/search/pkg/bleve/backend_test.go index db84988590..8cff372e2c 100644 --- a/services/search/pkg/bleve/backend_test.go +++ b/services/search/pkg/bleve/backend_test.go @@ -153,7 +153,6 @@ var _ = Describe("Bleve", func() { It("rewrites tags and favorites and keeps the extracted fields", func() { childResource.Content = "quarterly report" childResource.Tags = []string{"alpha"} - childResource.Extracted = true Expect(eng.Upsert(childResource.ID, childResource)).To(Succeed()) Expect(eng.Update(context.Background(), childResource.ID, search.MetadataUpdate{ @@ -166,7 +165,6 @@ var _ = Describe("Bleve", func() { Expect(r.Tags).To(Equal([]string{"Beta"})) Expect(r.Favorites).To(Equal([]string{"user-1"})) Expect(r.Content).To(Equal("quarterly report")) - Expect(r.Extracted).To(BeTrue()) Expect(tagHits("beta")).To(ConsistOf("4"), "the lowercase sibling follows the new tag") Expect(tagHits("alpha")).To(BeEmpty()) diff --git a/services/search/pkg/bleve/testdata/mapping.golden.json b/services/search/pkg/bleve/testdata/mapping.golden.json index 88ad94cbc2..73f6baa748 100644 --- a/services/search/pkg/bleve/testdata/mapping.golden.json +++ b/services/search/pkg/bleve/testdata/mapping.golden.json @@ -30,19 +30,6 @@ } ] }, - "Extracted": { - "enabled": true, - "dynamic": true, - "fields": [ - { - "type": "boolean", - "store": true, - "index": true, - "include_in_all": true, - "docvalues": true - } - ] - }, "Favorites": { "enabled": true, "dynamic": true, diff --git a/services/search/pkg/opensearch/backend_test.go b/services/search/pkg/opensearch/backend_test.go index ae7b1aaeba..abd74fd1e5 100644 --- a/services/search/pkg/opensearch/backend_test.go +++ b/services/search/pkg/opensearch/backend_test.go @@ -156,7 +156,6 @@ var _ = Describe("Backend", func() { document := opensearchtest.Testdata.Resources.File document.Content = "quarterly report" document.Tags = []string{"alpha"} - document.Extracted = true Expect(backend.Upsert(document.ID, document)).To(Succeed()) Expect(backend.Update(context.Background(), document.ID, search.MetadataUpdate{ @@ -169,7 +168,6 @@ var _ = Describe("Backend", func() { Expect(r.Tags).To(Equal([]string{"Beta"})) Expect(r.Favorites).To(Equal([]string{"user-1"})) Expect(r.Content).To(Equal("quarterly report")) - Expect(r.Extracted).To(BeTrue()) Expect(tagHits("beta")).To(Equal(1), "the lowercase sibling follows the new tag") Expect(tagHits("alpha")).To(BeZero()) diff --git a/services/search/pkg/opensearch/testdata/resource.golden.json b/services/search/pkg/opensearch/testdata/resource.golden.json index 6512c2c1b7..ab343eef11 100644 --- a/services/search/pkg/opensearch/testdata/resource.golden.json +++ b/services/search/pkg/opensearch/testdata/resource.golden.json @@ -9,9 +9,6 @@ "Deleted": { "type": "boolean" }, - "Extracted": { - "type": "boolean" - }, "Favorites": { "type": "keyword" }, diff --git a/services/search/pkg/search/search.go b/services/search/pkg/search/search.go index fba76509fc..463b6936e3 100644 --- a/services/search/pkg/search/search.go +++ b/services/search/pkg/search/search.go @@ -85,9 +85,6 @@ type Resource struct { Type uint64 `json:"Type"` Deleted bool `json:"Deleted"` Hidden bool `json:"Hidden"` - // Extracted is set once the content extraction succeeded, a document - // without it is extracted again on the next reindex - Extracted bool `json:"Extracted"` } // resourceFieldOverrides is built once (it never changes) and reused on hot diff --git a/services/search/pkg/search/service.go b/services/search/pkg/search/service.go index 564fe08db3..64acfbb57c 100644 --- a/services/search/pkg/search/service.go +++ b/services/search/pkg/search/service.go @@ -748,7 +748,6 @@ func (s *Service) doUpsertItem(ctx context.Context, ref *provider.Reference, bat Document: doc, } r.Hidden = IsHidden(r.Path) - r.Extracted = true if parentID := stat.GetInfo().GetParentId(); parentID != nil { r.ParentID = storagespace.FormatResourceID(parentID) @@ -934,7 +933,7 @@ func (s *Service) MoveItem(ref *provider.Reference) { } } -// isIndexed reports whether the index holds a live, fully extracted document for info that is at least as new +// isIndexed reports whether the index holds a live document for info that is at least as new func (s *Service) isIndexed(ctx context.Context, info *provider.ResourceInfo) bool { r, err := s.engine.Get(ctx, storagespace.FormatResourceID(info.GetId())) switch { @@ -944,7 +943,7 @@ func (s *Service) isIndexed(ctx context.Context, info *provider.ResourceInfo) bo s.logger.Error().Err(err).Interface("id", info.GetId()).Msg("failed to look up the indexed resource, indexing it again") return false } - return !r.Deleted && r.Extracted && r.Mtime != nil && !r.Mtime.Before(utils.TSToTime(info.GetMtime())) + return !r.Deleted && r.Mtime != nil && !r.Mtime.Before(utils.TSToTime(info.GetMtime())) } func (s *Service) resInfo(ctx context.Context, ref *provider.Reference) (*provider.StatResponse, string) { diff --git a/services/search/pkg/search/service_test.go b/services/search/pkg/search/service_test.go index 3b1cf06ae9..6b0ba1210b 100644 --- a/services/search/pkg/search/service_test.go +++ b/services/search/pkg/search/service_test.go @@ -158,14 +158,12 @@ var _ = Describe("Searchprovider", func() { info("outdated", sprovider.ResourceType_RESOURCE_TYPE_FILE, 5000), info("missing", sprovider.ResourceType_RESOURCE_TYPE_FILE, 4000), info("trashed", sprovider.ResourceType_RESOURCE_TYPE_FILE, 4000), - info("unextracted", sprovider.ResourceType_RESOURCE_TYPE_FILE, 4000), } indexed := map[string]*search.Resource{ - "storageid$spaceid!spaceid": {Document: content.Document{Mtime: &indexedAt}, Extracted: true}, - "storageid$spaceid!current": {Document: content.Document{Mtime: &indexedAt}, Extracted: true}, - "storageid$spaceid!outdated": {Document: content.Document{Mtime: &indexedAt}, Extracted: true}, - "storageid$spaceid!trashed": {Document: content.Document{Mtime: &indexedAt}, Extracted: true, Deleted: true}, - "storageid$spaceid!unextracted": {Document: content.Document{Mtime: &indexedAt}}, + "storageid$spaceid!spaceid": {Document: content.Document{Mtime: &indexedAt}}, + "storageid$spaceid!current": {Document: content.Document{Mtime: &indexedAt}}, + "storageid$spaceid!outdated": {Document: content.Document{Mtime: &indexedAt}}, + "storageid$spaceid!trashed": {Document: content.Document{Mtime: &indexedAt}, Deleted: true}, } gatewayClient.On("GetUserByClaim", mock.Anything, mock.Anything).Return(&userv1beta1.GetUserByClaimResponse{ @@ -204,7 +202,7 @@ var _ = Describe("Searchprovider", func() { err := s.IndexSpace(&sprovider.StorageSpaceId{OpaqueId: "storageid$spaceid!spaceid"}, false) Expect(err).ShouldNot(HaveOccurred()) - Expect(upserted).To(ConsistOf("storageid$spaceid!outdated", "storageid$spaceid!missing", "storageid$spaceid!trashed", "storageid$spaceid!unextracted")) + Expect(upserted).To(ConsistOf("storageid$spaceid!outdated", "storageid$spaceid!missing", "storageid$spaceid!trashed")) }) }) @@ -246,22 +244,6 @@ var _ = Describe("Searchprovider", func() { Entry("/", "/", false), ) - It("marks the resource as extracted", func() { - gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(&sprovider.StatResponse{ - Status: status.NewOK(context.Background()), - Info: ri, - }, nil) - extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, nil) - - var indexed search.Resource - indexClient.On("Upsert", mock.Anything, mock.Anything).Run(func(args mock.Arguments) { - indexed = args.Get(1).(search.Resource) - }).Return(nil) - - s.UpsertItem(&sprovider.Reference{ResourceId: ri.GetId()}) - Expect(indexed.Extracted).To(BeTrue()) - }) - Context("with facets stored on the resource", func() { var ( info *sprovider.ResourceInfo @@ -456,7 +438,6 @@ var _ = Describe("Searchprovider", func() { s.UpdateMetadata(&sprovider.Reference{ResourceId: info.GetId()}) Expect(indexed.ID).To(Equal("storageid$spaceid!tagged-opaqueid")) - Expect(indexed.Extracted).To(BeTrue()) }) It("does not extract the content when the update fails for another reason", func() { From 23f890cd626463a6326128a85dcb8409fea50403 Mon Sep 17 00:00:00 2001 From: Florian Schade Date: Tue, 24 Nov 2026 14:44:03 +0100 Subject: [PATCH 3/6] fix(search): index failed extractions by name and retry them --- .../pkg/bleve/testdata/mapping.golden.json | 13 +++++++++ services/search/pkg/content/tika.go | 11 ++++++++ services/search/pkg/content/tika_test.go | 17 +++++++++++ .../opensearch/testdata/resource.golden.json | 3 ++ services/search/pkg/search/search.go | 3 ++ services/search/pkg/search/service.go | 14 ++++++++-- services/search/pkg/search/service_test.go | 28 ++++++++++++++++++- 7 files changed, 85 insertions(+), 4 deletions(-) diff --git a/services/search/pkg/bleve/testdata/mapping.golden.json b/services/search/pkg/bleve/testdata/mapping.golden.json index 73f6baa748..ba07083d29 100644 --- a/services/search/pkg/bleve/testdata/mapping.golden.json +++ b/services/search/pkg/bleve/testdata/mapping.golden.json @@ -30,6 +30,19 @@ } ] }, + "ExtractionFailed": { + "enabled": true, + "dynamic": true, + "fields": [ + { + "type": "boolean", + "store": true, + "index": true, + "include_in_all": true, + "docvalues": true + } + ] + }, "Favorites": { "enabled": true, "dynamic": true, diff --git a/services/search/pkg/content/tika.go b/services/search/pkg/content/tika.go index 035d4b9fa4..b32ec15a79 100644 --- a/services/search/pkg/content/tika.go +++ b/services/search/pkg/content/tika.go @@ -86,6 +86,17 @@ func (t Tika) Extract(ctx context.Context, ri *provider.ResourceInfo) (Document, if len(metas) == 0 { return doc, fmt.Errorf("tika returned no metadata for %q", ri.GetName()) } + // tika answers a failed parse (ocr crash, broken pdf) with 200 and empty + // content, only this key tells it apart from a file without text + cause, err := getFirstValue(metas[0], + "tk:exception:container-exception", // tika 4 + "X-TIKA:EXCEPTION:container_exception", // tika 3 legacy + ) + if err == nil { + // the value is a java stack trace, its first line names the cause + cause, _, _ = strings.Cut(cause, "\n") + return doc, fmt.Errorf("tika failed to parse %q: %s", ri.GetName(), cause) + } for _, meta := range metas { title, err := getFirstValue(meta, "dc:title") diff --git a/services/search/pkg/content/tika_test.go b/services/search/pkg/content/tika_test.go index 62c5f248b1..61940f2a84 100644 --- a/services/search/pkg/content/tika_test.go +++ b/services/search/pkg/content/tika_test.go @@ -110,6 +110,23 @@ var _ = Describe("Tika", func() { Expect(err).To(MatchError(ContainSubstring("report.pdf"))) }) + DescribeTable("fails when tika could not parse the file", + func(response string) { + fullResponse = response + + doc, err := tika.Extract(context.TODO(), &provider.ResourceInfo{ + Type: provider.ResourceType_RESOURCE_TYPE_FILE, + Name: "scan.png", + Size: 1, + }) + Expect(err).To(MatchError(And(ContainSubstring("scan.png"), ContainSubstring("bad exit value 1")))) + Expect(err.Error()).ToNot(ContainSubstring("at org.apache")) + Expect(doc.Name).To(Equal("scan.png")) + }, + Entry("tika 4", `[{"tk:content": "", "tk:exception:container-exception": "org.apache.tika.exception.TikaException: TesseractOCRParser bad exit value 1\n\tat org.apache.tika.parser.ocr.TesseractOCRParser.doOCR"}]`), + Entry("tika 3", `[{"X-TIKA:content": "", "X-TIKA:EXCEPTION:container_exception": "org.apache.tika.exception.TikaException: TesseractOCRParser bad exit value 1\n\tat org.apache.tika.parser.ocr.TesseractOCRParser.doOCR"}]`), + ) + It("adds the title", func() { fullResponse = `[{"dc:title": "quarterly report", "X-TIKA:content": "some data"}]` diff --git a/services/search/pkg/opensearch/testdata/resource.golden.json b/services/search/pkg/opensearch/testdata/resource.golden.json index ab343eef11..ff94b32f7e 100644 --- a/services/search/pkg/opensearch/testdata/resource.golden.json +++ b/services/search/pkg/opensearch/testdata/resource.golden.json @@ -9,6 +9,9 @@ "Deleted": { "type": "boolean" }, + "ExtractionFailed": { + "type": "boolean" + }, "Favorites": { "type": "keyword" }, diff --git a/services/search/pkg/search/search.go b/services/search/pkg/search/search.go index 463b6936e3..162083f177 100644 --- a/services/search/pkg/search/search.go +++ b/services/search/pkg/search/search.go @@ -85,6 +85,9 @@ type Resource struct { Type uint64 `json:"Type"` Deleted bool `json:"Deleted"` Hidden bool `json:"Hidden"` + // ExtractionFailed marks a document indexed without its content, the next + // reindex extracts it again; entries from before the field count as extracted + ExtractionFailed bool `json:"ExtractionFailed"` } // resourceFieldOverrides is built once (it never changes) and reused on hot diff --git a/services/search/pkg/search/service.go b/services/search/pkg/search/service.go index 64acfbb57c..75b1e076c7 100644 --- a/services/search/pkg/search/service.go +++ b/services/search/pkg/search/service.go @@ -730,10 +730,12 @@ func (s *Service) doUpsertItem(ctx context.Context, ref *provider.Reference, bat return } + // a failed extraction still yields the name, path and tags, the resource + // stays findable and the next space walk retries it doc, err := s.extractor.Extract(ctx, stat.Info) + extractionFailed := err != nil if err != nil { - s.logger.Error().Err(err).Msg("failed to extract resource content") - return + s.logger.Error().Err(err).Str("path", path).Msg("failed to extract resource content") } r := Resource{ @@ -748,6 +750,7 @@ func (s *Service) doUpsertItem(ctx context.Context, ref *provider.Reference, bat Document: doc, } r.Hidden = IsHidden(r.Path) + r.ExtractionFailed = extractionFailed if parentID := stat.GetInfo().GetParentId(); parentID != nil { r.ParentID = storagespace.FormatResourceID(parentID) @@ -764,6 +767,11 @@ func (s *Service) doUpsertItem(ctx context.Context, ref *provider.Reference, bat logDocCount(s.engine, s.logger) } + // without an extraction the facets are unknown, not gone + if extractionFailed { + return + } + // determine if metadata needs to be stored in storage as well metadata := map[string]string{} facetToMetadata(metadata, doc.Audio, facetKeyPrefix+"audio.") @@ -943,7 +951,7 @@ func (s *Service) isIndexed(ctx context.Context, info *provider.ResourceInfo) bo s.logger.Error().Err(err).Interface("id", info.GetId()).Msg("failed to look up the indexed resource, indexing it again") return false } - return !r.Deleted && r.Mtime != nil && !r.Mtime.Before(utils.TSToTime(info.GetMtime())) + return !r.Deleted && !r.ExtractionFailed && r.Mtime != nil && !r.Mtime.Before(utils.TSToTime(info.GetMtime())) } func (s *Service) resInfo(ctx context.Context, ref *provider.Reference) (*provider.StatResponse, string) { diff --git a/services/search/pkg/search/service_test.go b/services/search/pkg/search/service_test.go index 6b0ba1210b..9db111a2ce 100644 --- a/services/search/pkg/search/service_test.go +++ b/services/search/pkg/search/service_test.go @@ -158,12 +158,14 @@ var _ = Describe("Searchprovider", func() { info("outdated", sprovider.ResourceType_RESOURCE_TYPE_FILE, 5000), info("missing", sprovider.ResourceType_RESOURCE_TYPE_FILE, 4000), info("trashed", sprovider.ResourceType_RESOURCE_TYPE_FILE, 4000), + info("failed", sprovider.ResourceType_RESOURCE_TYPE_FILE, 4000), } indexed := map[string]*search.Resource{ "storageid$spaceid!spaceid": {Document: content.Document{Mtime: &indexedAt}}, "storageid$spaceid!current": {Document: content.Document{Mtime: &indexedAt}}, "storageid$spaceid!outdated": {Document: content.Document{Mtime: &indexedAt}}, "storageid$spaceid!trashed": {Document: content.Document{Mtime: &indexedAt}, Deleted: true}, + "storageid$spaceid!failed": {Document: content.Document{Mtime: &indexedAt}, ExtractionFailed: true}, } gatewayClient.On("GetUserByClaim", mock.Anything, mock.Anything).Return(&userv1beta1.GetUserByClaimResponse{ @@ -202,7 +204,7 @@ var _ = Describe("Searchprovider", func() { err := s.IndexSpace(&sprovider.StorageSpaceId{OpaqueId: "storageid$spaceid!spaceid"}, false) Expect(err).ShouldNot(HaveOccurred()) - Expect(upserted).To(ConsistOf("storageid$spaceid!outdated", "storageid$spaceid!missing", "storageid$spaceid!trashed")) + Expect(upserted).To(ConsistOf("storageid$spaceid!outdated", "storageid$spaceid!missing", "storageid$spaceid!trashed", "storageid$spaceid!failed")) }) }) @@ -244,6 +246,23 @@ var _ = Describe("Searchprovider", func() { Entry("/", "/", false), ) + It("indexes a resource whose extraction failed by name and marks it", func() { + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(&sprovider.StatResponse{ + Status: status.NewOK(context.Background()), + Info: ri, + }, nil) + extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{Name: "scan.png"}, errors.New("tika failed to parse")) + + var indexed search.Resource + indexClient.On("Upsert", mock.Anything, mock.Anything).Run(func(args mock.Arguments) { + indexed = args.Get(1).(search.Resource) + }).Return(nil) + + s.UpsertItem(&sprovider.Reference{ResourceId: ri.GetId()}) + Expect(indexed.Name).To(Equal("scan.png")) + Expect(indexed.ExtractionFailed).To(BeTrue()) + }) + Context("with facets stored on the resource", func() { var ( info *sprovider.ResourceInfo @@ -342,6 +361,13 @@ var _ = Describe("Searchprovider", func() { s.UpsertItem(&sprovider.Reference{ResourceId: info.GetId()}) Expect(calls).To(BeEmpty()) }) + + It("keeps the stored facets when the extraction failed", func() { + extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, errors.New("tika failed to parse")) + + s.UpsertItem(&sprovider.Reference{ResourceId: info.GetId()}) + Expect(calls).To(BeEmpty()) + }) }) }) From 8dc18b7f1d5156e2c232a18985b85e2760785615 Mon Sep 17 00:00:00 2001 From: Florian Schade Date: Tue, 24 Nov 2026 16:44:45 +0100 Subject: [PATCH 4/6] refactor(search): drop UpsertItem and reuse the stat in UpdateMetadata --- services/search/pkg/bleve/backend.go | 3 +- services/search/pkg/search/mocks/searcher.go | 40 --- services/search/pkg/search/service.go | 245 +++++++++---------- services/search/pkg/search/service_test.go | 24 +- 4 files changed, 136 insertions(+), 176 deletions(-) diff --git a/services/search/pkg/bleve/backend.go b/services/search/pkg/bleve/backend.go index fa17ce5fef..5a42cc4e1d 100644 --- a/services/search/pkg/bleve/backend.go +++ b/services/search/pkg/bleve/backend.go @@ -180,7 +180,8 @@ func (b *Backend) Get(_ context.Context, id string) (*search.Resource, error) { } // Update holds the batch lock from the read to the write, so a batch pushed in -// between cannot be overwritten with the document as it was before +// between is not overwritten; a batch built before the update and pushed after +// it still writes the tags it read func (b *Backend) Update(_ context.Context, id string, u search.MetadataUpdate) error { b.index.batchMu.Lock() defer b.index.batchMu.Unlock() diff --git a/services/search/pkg/search/mocks/searcher.go b/services/search/pkg/search/mocks/searcher.go index dcd8c08a9f..0cf6704769 100644 --- a/services/search/pkg/search/mocks/searcher.go +++ b/services/search/pkg/search/mocks/searcher.go @@ -465,43 +465,3 @@ func (_c *Searcher_UpdateMetadata_Call) RunAndReturn(run func(ref *providerv1bet _c.Run(run) return _c } - -// UpsertItem provides a mock function for the type Searcher -func (_mock *Searcher) UpsertItem(ref *providerv1beta1.Reference) { - _mock.Called(ref) - return -} - -// Searcher_UpsertItem_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpsertItem' -type Searcher_UpsertItem_Call struct { - *mock.Call -} - -// UpsertItem is a helper method to define mock.On call -// - ref *providerv1beta1.Reference -func (_e *Searcher_Expecter) UpsertItem(ref any) *Searcher_UpsertItem_Call { - return &Searcher_UpsertItem_Call{Call: _e.mock.On("UpsertItem", ref)} -} - -func (_c *Searcher_UpsertItem_Call) Run(run func(ref *providerv1beta1.Reference)) *Searcher_UpsertItem_Call { - _c.Call.Run(func(args mock.Arguments) { - var arg0 *providerv1beta1.Reference - if args[0] != nil { - arg0 = args[0].(*providerv1beta1.Reference) - } - run( - arg0, - ) - }) - return _c -} - -func (_c *Searcher_UpsertItem_Call) Return() *Searcher_UpsertItem_Call { - _c.Call.Return() - return _c -} - -func (_c *Searcher_UpsertItem_Call) RunAndReturn(run func(ref *providerv1beta1.Reference)) *Searcher_UpsertItem_Call { - _c.Run(run) - return _c -} diff --git a/services/search/pkg/search/service.go b/services/search/pkg/search/service.go index 75b1e076c7..2c3e37b8c4 100644 --- a/services/search/pkg/search/service.go +++ b/services/search/pkg/search/service.go @@ -63,7 +63,6 @@ type Searcher interface { TrashItem(resourceID *provider.ResourceId) PurgeItem(ref *provider.Reference) - UpsertItem(ref *provider.Reference) UpdateMetadata(ref *provider.Reference) RestoreItem(ref *provider.Reference) MoveItem(ref *provider.Reference) @@ -76,6 +75,7 @@ type Service struct { gatewaySelector pool.Selectable[gateway.GatewayAPIClient] engine Engine extractor content.Extractor + basic *content.Basic metrics *metrics.Metrics serviceAccountID string @@ -90,11 +90,15 @@ var errSkipSpace error // NewService creates a new Provider instance. func NewService(gatewaySelector pool.Selectable[gateway.GatewayAPIClient], eng Engine, extractor content.Extractor, metrics *metrics.Metrics, logger log.Logger, cfg *config.Config) *Service { + // NewBasicExtractor has no failure path + basic, _ := content.NewBasicExtractor(logger) + var s = &Service{ gatewaySelector: gatewaySelector, engine: eng, logger: logger, extractor: extractor, + basic: basic, metrics: metrics, serviceAccountID: cfg.ServiceAccount.ServiceAccountID, @@ -671,16 +675,6 @@ func (s *Service) PurgeDeleted(spaceID *provider.StorageSpaceId) error { return nil } -// UpsertItem indexes or stores Resource data fields. -func (s *Service) UpsertItem(ref *provider.Reference) { - ctx, err := getAuthContext(s.serviceAccountID, s.gatewaySelector, s.serviceAccountSecret, s.logger) - if err != nil { - s.logger.Error().Err(err).Msg("failed to get auth context") - return - } - s.doUpsertItem(ctx, ref, nil) -} - // UpdateMetadata rewrites the tags and favorites of an indexed resource without // extracting its content again, a resource not indexed yet is upserted in full. func (s *Service) UpdateMetadata(ref *provider.Reference) { @@ -690,17 +684,12 @@ func (s *Service) UpdateMetadata(ref *provider.Reference) { return } - stat, _ := s.resInfo(ctx, ref) - if stat == nil { + stat, path := s.resInfo(ctx, ref) + if stat == nil || path == "" { return } - basic, err := content.NewBasicExtractor(s.logger) - if err != nil { - s.logger.Error().Err(err).Msg("failed to create the basic extractor") - return - } - doc, err := basic.Extract(ctx, stat.GetInfo()) + doc, err := s.basic.Extract(ctx, stat.GetInfo()) if err != nil { s.logger.Error().Err(err).Msg("failed to read the resource metadata") return @@ -712,7 +701,7 @@ func (s *Service) UpdateMetadata(ref *provider.Reference) { }) switch { case errors.Is(err, ErrResourceNotFound): - s.doUpsertItem(ctx, ref, nil) + s.upsertResource(ctx, ref, stat, path, nil) case err != nil: s.logger.Error().Err(err).Interface("id", stat.GetInfo().GetId()).Msg("failed to update the resource metadata in the index") } @@ -724,112 +713,7 @@ func (s *Service) doUpsertItem(ctx context.Context, ref *provider.Reference, bat if stat == nil || path == "" { return } - - if utils.IsProcessing(stat.Info) { - s.logger.Debug().Str("path", path).Msg("resource is still being processed. Skipping.") - return - } - - // a failed extraction still yields the name, path and tags, the resource - // stays findable and the next space walk retries it - doc, err := s.extractor.Extract(ctx, stat.Info) - extractionFailed := err != nil - if err != nil { - s.logger.Error().Err(err).Str("path", path).Msg("failed to extract resource content") - } - - r := Resource{ - ID: storagespace.FormatResourceID(stat.Info.Id), - RootID: storagespace.FormatResourceID(&provider.ResourceId{ - StorageId: stat.Info.Id.StorageId, - OpaqueId: stat.Info.Id.SpaceId, - SpaceId: stat.Info.Id.SpaceId, - }), - Path: utils.MakeRelativePath(path), - Type: uint64(stat.Info.Type), - Document: doc, - } - r.Hidden = IsHidden(r.Path) - r.ExtractionFailed = extractionFailed - - if parentID := stat.GetInfo().GetParentId(); parentID != nil { - r.ParentID = storagespace.FormatResourceID(parentID) - } - - if batch != nil { - err = batch.Upsert(r.ID, r) - } else { - err = s.engine.Upsert(r.ID, r) - } - if err != nil { - s.logger.Error().Err(err).Msg("error adding updating the resource in the index") - } else { - logDocCount(s.engine, s.logger) - } - - // without an extraction the facets are unknown, not gone - if extractionFailed { - return - } - - // determine if metadata needs to be stored in storage as well - metadata := map[string]string{} - facetToMetadata(metadata, doc.Audio, facetKeyPrefix+"audio.") - facetToMetadata(metadata, doc.Image, facetKeyPrefix+"image.") - facetToMetadata(metadata, doc.Location, facetKeyPrefix+"location.") - facetToMetadata(metadata, doc.Photo, facetKeyPrefix+"photo.") - facetToMetadata(metadata, doc.Video, facetKeyPrefix+"video.") - facetToMetadata(metadata, doc.MotionPhoto, facetKeyPrefix+"motionPhoto.") - facetToMetadata(metadata, doc.LivePhoto, facetKeyPrefix+"livePhoto.") - - // the facet keys are ours, so the ones this extraction did not produce - // describe content the resource no longer has - var stale []string - for k, stored := range stat.GetInfo().GetArbitraryMetadata().GetMetadata() { - value, ok := metadata[k] - switch { - case ok && value == stored: - delete(metadata, k) - case !ok && strings.HasPrefix(k, facetKeyPrefix): - stale = append(stale, k) - } - } - if len(metadata) == 0 && len(stale) == 0 { - return - } - - gatewayClient, err := s.gatewaySelector.Next() - if err != nil { - s.logger.Error().Err(err).Msg("could not retrieve client to store metadata") - return - } - - if len(metadata) > 0 { - s.logger.Trace().Str("name", doc.Name).Interface("metadata", metadata).Msg("Storing metadata") - - resp, err := gatewayClient.SetArbitraryMetadata(ctx, &provider.SetArbitraryMetadataRequest{ - Ref: ref, - ArbitraryMetadata: &provider.ArbitraryMetadata{ - Metadata: metadata, - }, - }) - if err != nil || resp.GetStatus().GetCode() != rpc.Code_CODE_OK { - s.logger.Error().Err(err).Int32("status", int32(resp.GetStatus().GetCode())).Msg("error storing metadata") - return - } - } - - if len(stale) > 0 { - s.logger.Trace().Str("name", doc.Name).Strs("keys", stale).Msg("Removing stale metadata") - - resp, err := gatewayClient.UnsetArbitraryMetadata(ctx, &provider.UnsetArbitraryMetadataRequest{ - Ref: ref, - ArbitraryMetadataKeys: stale, - }) - if err != nil || resp.GetStatus().GetCode() != rpc.Code_CODE_OK { - s.logger.Error().Err(err).Int32("status", int32(resp.GetStatus().GetCode())).Msg("error removing stale metadata") - } - } + s.upsertResource(ctx, ref, stat, path, batch) } // SanitizeHighlights keeps the tags and escapes everything else. @@ -941,6 +825,115 @@ func (s *Service) MoveItem(ref *provider.Reference) { } } +// upsertResource extracts and indexes the resource stat describes +func (s *Service) upsertResource(ctx context.Context, ref *provider.Reference, stat *provider.StatResponse, path string, batch BatchOperator) { + if utils.IsProcessing(stat.GetInfo()) { + s.logger.Debug().Str("path", path).Msg("resource is still being processed. Skipping.") + return + } + + // a failed extraction still yields the name, path and tags, the resource + // stays findable and the next space walk retries it + doc, err := s.extractor.Extract(ctx, stat.GetInfo()) + extractionFailed := err != nil + if err != nil { + s.logger.Error().Err(err).Str("path", path).Msg("failed to extract resource content") + } + + r := Resource{ + ID: storagespace.FormatResourceID(stat.GetInfo().GetId()), + RootID: storagespace.FormatResourceID(&provider.ResourceId{ + StorageId: stat.GetInfo().GetId().GetStorageId(), + OpaqueId: stat.GetInfo().GetId().GetSpaceId(), + SpaceId: stat.GetInfo().GetId().GetSpaceId(), + }), + Path: utils.MakeRelativePath(path), + Type: uint64(stat.GetInfo().GetType()), //nolint:gosec // proto enum values are never negative + Document: doc, + } + r.Hidden = IsHidden(r.Path) + r.ExtractionFailed = extractionFailed + + if parentID := stat.GetInfo().GetParentId(); parentID != nil { + r.ParentID = storagespace.FormatResourceID(parentID) + } + + if batch != nil { + err = batch.Upsert(r.ID, r) + } else { + err = s.engine.Upsert(r.ID, r) + } + if err != nil { + s.logger.Error().Err(err).Msg("error adding updating the resource in the index") + } else { + logDocCount(s.engine, s.logger) + } + + // without an extraction the facets are unknown, not gone + if extractionFailed { + return + } + + // determine if metadata needs to be stored in storage as well + metadata := map[string]string{} + facetToMetadata(metadata, doc.Audio, facetKeyPrefix+"audio.") + facetToMetadata(metadata, doc.Image, facetKeyPrefix+"image.") + facetToMetadata(metadata, doc.Location, facetKeyPrefix+"location.") + facetToMetadata(metadata, doc.Photo, facetKeyPrefix+"photo.") + facetToMetadata(metadata, doc.Video, facetKeyPrefix+"video.") + facetToMetadata(metadata, doc.MotionPhoto, facetKeyPrefix+"motionPhoto.") + facetToMetadata(metadata, doc.LivePhoto, facetKeyPrefix+"livePhoto.") + + // the facet keys are ours, so the ones this extraction did not produce + // describe content the resource no longer has + var stale []string + for k, stored := range stat.GetInfo().GetArbitraryMetadata().GetMetadata() { + value, ok := metadata[k] + switch { + case ok && value == stored: + delete(metadata, k) + case !ok && strings.HasPrefix(k, facetKeyPrefix): + stale = append(stale, k) + } + } + if len(metadata) == 0 && len(stale) == 0 { + return + } + + gatewayClient, err := s.gatewaySelector.Next() + if err != nil { + s.logger.Error().Err(err).Msg("could not retrieve client to store metadata") + return + } + + if len(metadata) > 0 { + s.logger.Trace().Str("name", doc.Name).Interface("metadata", metadata).Msg("Storing metadata") + + resp, err := gatewayClient.SetArbitraryMetadata(ctx, &provider.SetArbitraryMetadataRequest{ + Ref: ref, + ArbitraryMetadata: &provider.ArbitraryMetadata{ + Metadata: metadata, + }, + }) + if err != nil || resp.GetStatus().GetCode() != rpc.Code_CODE_OK { + s.logger.Error().Err(err).Int32("status", int32(resp.GetStatus().GetCode())).Msg("error storing metadata") + return + } + } + + if len(stale) > 0 { + s.logger.Trace().Str("name", doc.Name).Strs("keys", stale).Msg("Removing stale metadata") + + resp, err := gatewayClient.UnsetArbitraryMetadata(ctx, &provider.UnsetArbitraryMetadataRequest{ + Ref: ref, + ArbitraryMetadataKeys: stale, + }) + if err != nil || resp.GetStatus().GetCode() != rpc.Code_CODE_OK { + s.logger.Error().Err(err).Int32("status", int32(resp.GetStatus().GetCode())).Msg("error removing stale metadata") + } + } +} + // isIndexed reports whether the index holds a live document for info that is at least as new func (s *Service) isIndexed(ctx context.Context, info *provider.ResourceInfo) bool { r, err := s.engine.Get(ctx, storagespace.FormatResourceID(info.GetId())) diff --git a/services/search/pkg/search/service_test.go b/services/search/pkg/search/service_test.go index 9db111a2ce..fd15999a5c 100644 --- a/services/search/pkg/search/service_test.go +++ b/services/search/pkg/search/service_test.go @@ -208,7 +208,12 @@ var _ = Describe("Searchprovider", func() { }) }) - Describe("UpsertItem", func() { + Describe("indexing a resource in full", func() { + BeforeEach(func() { + // a resource the index does not hold yet takes the full path + indexClient.On("Update", mock.Anything, mock.Anything, mock.Anything).Return(search.ErrResourceNotFound) + }) + DescribeTable("marks a resource hidden when a dot starts one of its names", func(path string, hidden bool) { info := &sprovider.ResourceInfo{ @@ -233,7 +238,7 @@ var _ = Describe("Searchprovider", func() { indexed = args.Get(1).(search.Resource) }).Return(nil) - s.UpsertItem(&sprovider.Reference{ResourceId: info.GetId()}) + s.UpdateMetadata(&sprovider.Reference{ResourceId: info.GetId()}) Expect(indexed.Hidden).To(Equal(hidden)) }, Entry("./documents/notes.txt", "./documents/notes.txt", false), @@ -258,7 +263,7 @@ var _ = Describe("Searchprovider", func() { indexed = args.Get(1).(search.Resource) }).Return(nil) - s.UpsertItem(&sprovider.Reference{ResourceId: ri.GetId()}) + s.UpdateMetadata(&sprovider.Reference{ResourceId: ri.GetId()}) Expect(indexed.Name).To(Equal("scan.png")) Expect(indexed.ExtractionFailed).To(BeTrue()) }) @@ -312,7 +317,7 @@ var _ = Describe("Searchprovider", func() { Photo: &libregraph.Photo{CameraMake: libregraph.PtrString("Nikon")}, }, nil) - s.UpsertItem(&sprovider.Reference{ResourceId: info.GetId()}) + s.UpdateMetadata(&sprovider.Reference{ResourceId: info.GetId()}) Expect(calls).To(Equal([]string{"set", "unset"})) Expect(set).To(Equal(map[string]string{"libre.graph.photo.cameraMake": "Nikon"})) Expect(unset).To(ConsistOf("libre.graph.photo.iso", "libre.graph.location.altitude")) @@ -321,7 +326,7 @@ var _ = Describe("Searchprovider", func() { It("removes all facets when the extraction produces none", func() { extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, nil) - s.UpsertItem(&sprovider.Reference{ResourceId: info.GetId()}) + s.UpdateMetadata(&sprovider.Reference{ResourceId: info.GetId()}) Expect(calls).To(Equal([]string{"unset"})) Expect(unset).To(ConsistOf("libre.graph.photo.cameraMake", "libre.graph.photo.iso", "libre.graph.location.altitude")) }) @@ -333,7 +338,7 @@ var _ = Describe("Searchprovider", func() { Location: &libregraph.GeoCoordinates{Altitude: libregraph.PtrFloat64(12)}, }, nil) - s.UpsertItem(&sprovider.Reference{ResourceId: info.GetId()}) + s.UpdateMetadata(&sprovider.Reference{ResourceId: info.GetId()}) Expect(calls).To(Equal([]string{"unset"})) Expect(unset).To(ConsistOf("libre.graph.retiredFacet.field")) }) @@ -344,7 +349,7 @@ var _ = Describe("Searchprovider", func() { Location: &libregraph.GeoCoordinates{Altitude: libregraph.PtrFloat64(12), Latitude: libregraph.PtrFloat64(48.1)}, }, nil) - s.UpsertItem(&sprovider.Reference{ResourceId: info.GetId()}) + s.UpdateMetadata(&sprovider.Reference{ResourceId: info.GetId()}) Expect(calls).To(Equal([]string{"set"})) Expect(set).To(Equal(map[string]string{ "libre.graph.photo.iso": "200", @@ -358,14 +363,14 @@ var _ = Describe("Searchprovider", func() { Location: &libregraph.GeoCoordinates{Altitude: libregraph.PtrFloat64(12)}, }, nil) - s.UpsertItem(&sprovider.Reference{ResourceId: info.GetId()}) + s.UpdateMetadata(&sprovider.Reference{ResourceId: info.GetId()}) Expect(calls).To(BeEmpty()) }) It("keeps the stored facets when the extraction failed", func() { extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, errors.New("tika failed to parse")) - s.UpsertItem(&sprovider.Reference{ResourceId: info.GetId()}) + s.UpdateMetadata(&sprovider.Reference{ResourceId: info.GetId()}) Expect(calls).To(BeEmpty()) }) }) @@ -464,6 +469,7 @@ var _ = Describe("Searchprovider", func() { s.UpdateMetadata(&sprovider.Reference{ResourceId: info.GetId()}) Expect(indexed.ID).To(Equal("storageid$spaceid!tagged-opaqueid")) + gatewayClient.AssertNumberOfCalls(GinkgoT(), "Stat", 1) }) It("does not extract the content when the update fails for another reason", func() { From 7577dbfd5d1c8a94817b323767175fb6bd6beba1 Mon Sep 17 00:00:00 2001 From: Florian Schade Date: Tue, 24 Nov 2026 17:37:54 +0100 Subject: [PATCH 5/6] fix(search): cap and space the retries of unparsable files --- services/search/README.md | 12 +++ .../pkg/bleve/testdata/mapping.golden.json | 37 +++++++-- services/search/pkg/content/tika.go | 9 +- services/search/pkg/content/tika_test.go | 2 + .../opensearch/testdata/resource.golden.json | 11 ++- services/search/pkg/parity/README.md | 15 ++++ services/search/pkg/parity/fixtures_test.go | 14 ++++ services/search/pkg/parity/get_test.go | 42 ++++++++++ services/search/pkg/parity/parity_test.go | 1 + .../pkg/parity/query_extraction_test.go | 22 +++++ services/search/pkg/search/search.go | 17 +++- services/search/pkg/search/service.go | 49 +++++++++-- services/search/pkg/search/service_test.go | 83 ++++++++++++++++--- 13 files changed, 280 insertions(+), 34 deletions(-) create mode 100644 services/search/pkg/parity/get_test.go create mode 100644 services/search/pkg/parity/query_extraction_test.go diff --git a/services/search/README.md b/services/search/README.md index 984a833d50..7d60201ebb 100644 --- a/services/search/README.md +++ b/services/search/README.md @@ -161,6 +161,18 @@ Additionally, the following optional settings can be set: * `SEARCH_EXTRACTOR_TIKA_CLEAN_STOP_WORDS=true` (default: `true`): ignore stop words like `I`, `you`, `the` during content extraction. +#### Files Tika Cannot Parse + +A file Tika cannot parse, such as a broken PDF or an image the OCR fails on, is still indexed by name, path and tags, so it stays findable. The content is tried again on later reindexes, the first retry one hour after the failure, the second one day after that. After the third failure the service logs a warning with the path and stops trying until the file changes. If Tika itself is unreachable, nothing is written and the next reindex tries again. + +To list the files the service gave up on, search for: + +```text +extractionfailure.count>=3 +``` + +A reindex with `--force-rescan` (see below) tries these files again regardless of the limit, for example after a Tika upgrade. + ## Manually Trigger Re-Indexing a Space The service includes a command-line interface to trigger re-indexing a space: diff --git a/services/search/pkg/bleve/testdata/mapping.golden.json b/services/search/pkg/bleve/testdata/mapping.golden.json index ba07083d29..47574d908b 100644 --- a/services/search/pkg/bleve/testdata/mapping.golden.json +++ b/services/search/pkg/bleve/testdata/mapping.golden.json @@ -30,18 +30,37 @@ } ] }, - "ExtractionFailed": { + "ExtractionFailure": { "enabled": true, "dynamic": true, - "fields": [ - { - "type": "boolean", - "store": true, - "index": true, - "include_in_all": true, - "docvalues": true + "properties": { + "Count": { + "enabled": true, + "dynamic": true, + "fields": [ + { + "type": "number", + "store": true, + "index": true, + "include_in_all": true, + "docvalues": true + } + ] + }, + "RetryAt": { + "enabled": true, + "dynamic": true, + "fields": [ + { + "type": "datetime", + "store": true, + "index": true, + "include_in_all": true, + "docvalues": true + } + ] } - ] + } }, "Favorites": { "enabled": true, diff --git a/services/search/pkg/content/tika.go b/services/search/pkg/content/tika.go index b32ec15a79..733ff02517 100644 --- a/services/search/pkg/content/tika.go +++ b/services/search/pkg/content/tika.go @@ -2,6 +2,7 @@ package content import ( "context" + "errors" "fmt" "io" "net/http" @@ -17,6 +18,10 @@ import ( "github.com/opencloud-eu/opencloud/services/search/pkg/config" ) +// ErrUnparsable marks a file tika answered for but could not parse, unlike an +// unreachable tika it fails the same way on the next attempt more often than not +var ErrUnparsable = errors.New("tika failed to parse") + // Tika is used to extract content from a resource, // it uses apache tika to retrieve all the data. type Tika struct { @@ -84,7 +89,7 @@ func (t Tika) Extract(ctx context.Context, ri *provider.ResourceInfo) (Document, } // a file with content always yields metadata, none means tika failed on it if len(metas) == 0 { - return doc, fmt.Errorf("tika returned no metadata for %q", ri.GetName()) + return doc, fmt.Errorf("%w %q: no metadata", ErrUnparsable, ri.GetName()) } // tika answers a failed parse (ocr crash, broken pdf) with 200 and empty // content, only this key tells it apart from a file without text @@ -95,7 +100,7 @@ func (t Tika) Extract(ctx context.Context, ri *provider.ResourceInfo) (Document, if err == nil { // the value is a java stack trace, its first line names the cause cause, _, _ = strings.Cut(cause, "\n") - return doc, fmt.Errorf("tika failed to parse %q: %s", ri.GetName(), cause) + return doc, fmt.Errorf("%w %q: %s", ErrUnparsable, ri.GetName(), cause) } for _, meta := range metas { diff --git a/services/search/pkg/content/tika_test.go b/services/search/pkg/content/tika_test.go index 61940f2a84..ab6605cbf9 100644 --- a/services/search/pkg/content/tika_test.go +++ b/services/search/pkg/content/tika_test.go @@ -107,6 +107,7 @@ var _ = Describe("Tika", func() { Name: "report.pdf", Size: 1, }) + Expect(err).To(MatchError(content.ErrUnparsable)) Expect(err).To(MatchError(ContainSubstring("report.pdf"))) }) @@ -119,6 +120,7 @@ var _ = Describe("Tika", func() { Name: "scan.png", Size: 1, }) + Expect(err).To(MatchError(content.ErrUnparsable)) Expect(err).To(MatchError(And(ContainSubstring("scan.png"), ContainSubstring("bad exit value 1")))) Expect(err.Error()).ToNot(ContainSubstring("at org.apache")) Expect(doc.Name).To(Equal("scan.png")) diff --git a/services/search/pkg/opensearch/testdata/resource.golden.json b/services/search/pkg/opensearch/testdata/resource.golden.json index ff94b32f7e..375cd69254 100644 --- a/services/search/pkg/opensearch/testdata/resource.golden.json +++ b/services/search/pkg/opensearch/testdata/resource.golden.json @@ -9,8 +9,15 @@ "Deleted": { "type": "boolean" }, - "ExtractionFailed": { - "type": "boolean" + "ExtractionFailure": { + "properties": { + "Count": { + "type": "long" + }, + "RetryAt": { + "type": "date" + } + } }, "Favorites": { "type": "keyword" diff --git a/services/search/pkg/parity/README.md b/services/search/pkg/parity/README.md index f73000e16f..69cdde843c 100644 --- a/services/search/pkg/parity/README.md +++ b/services/search/pkg/parity/README.md @@ -461,6 +461,21 @@ Fixtures: | PHOTO-05 | `photo.iso<=100` | bright.jpg | bright.jpg | bright.jpg | ✅ | | PHOTO-06 | `photo.cameraMake>1` | no match | no match | no match | ✅ | +### extraction + +Fixtures: + +- `given-up.pdf` +- `waiting.png` +- `extracted.txt` + +| Case | Query | expected | bleve | OpenSearch | same? | +|---|---|---|---|---|---| +| EXTRACTION-01 | `extractionfailure.count>=3` | given-up.pdf | given-up.pdf | given-up.pdf | ✅ | +| EXTRACTION-02 | `ExtractionFailure.Count>=1` | given-up.pdf, waiting.png | given-up.pdf, waiting.png | given-up.pdf, waiting.png | ✅ | +| EXTRACTION-03 | `extractionfailure.retryat>"2029-01-01T00:00:00Z"` | waiting.png | waiting.png | waiting.png | ✅ | +| EXTRACTION-04 | `extractionfailure.retryat<"2029-01-01T00:00:00Z"` | no match | no match | no match | ✅ | + ### scope Fixtures: diff --git a/services/search/pkg/parity/fixtures_test.go b/services/search/pkg/parity/fixtures_test.go index 9e75f037a1..fcb909d310 100644 --- a/services/search/pkg/parity/fixtures_test.go +++ b/services/search/pkg/parity/fixtures_test.go @@ -58,6 +58,20 @@ func withLocation(location *libregraph.GeoCoordinates) fixtureOption { return func(r *search.Resource) { r.Location = location } } +func withExtractionFailure(count int, retryAt string) fixtureOption { + return func(r *search.Resource) { + f := &search.ExtractionFailure{Count: count} + if retryAt != "" { + t, err := time.Parse(time.RFC3339Nano, retryAt) + if err != nil { + panic(err) + } + f.RetryAt = &t + } + r.ExtractionFailure = f + } +} + func fixtureDoc(name string, opts ...fixtureOption) search.Resource { mtime := fixtureNow r := search.Resource{ diff --git a/services/search/pkg/parity/get_test.go b/services/search/pkg/parity/get_test.go new file mode 100644 index 0000000000..9555673c94 --- /dev/null +++ b/services/search/pkg/parity/get_test.go @@ -0,0 +1,42 @@ +package parity + +import ( + "context" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + + "github.com/opencloud-eu/opencloud/services/search/pkg/search" +) + +// the indexer reads its retry bookkeeping back through Get, a nested object +// with a timestamp has to survive the round trip on every engine +var _ = Describe("Get", Ordered, func() { + failed := fixtureDoc("failed.pdf", withExtractionFailure(2, "2030-01-01T12:30:00Z")) + extracted := fixtureDoc("extracted.txt") + + var engines []testEngine + BeforeAll(func() { + engines = newEngines("opencloud-test-engine-parity-get", []search.Resource{failed, extracted}) + }) + + for _, name := range engineNames { + It("returns the extraction failure as written on "+name, func() { + e := engineNamed(engines, name) + if e.unavailable != "" { + Skip(e.unavailable) + } + + r, err := e.backend.Get(context.Background(), failed.ID) + Expect(err).NotTo(HaveOccurred()) + Expect(r.ExtractionFailure).NotTo(BeNil()) + Expect(r.ExtractionFailure.Count).To(Equal(2)) + Expect(r.ExtractionFailure.RetryAt).NotTo(BeNil()) + Expect(*r.ExtractionFailure.RetryAt).To(BeTemporally("==", *failed.ExtractionFailure.RetryAt)) + + r, err = e.backend.Get(context.Background(), extracted.ID) + Expect(err).NotTo(HaveOccurred()) + Expect(r.ExtractionFailure).To(BeNil()) + }) + } +}) diff --git a/services/search/pkg/parity/parity_test.go b/services/search/pkg/parity/parity_test.go index 55d85078c8..3c82ce043e 100644 --- a/services/search/pkg/parity/parity_test.go +++ b/services/search/pkg/parity/parity_test.go @@ -111,6 +111,7 @@ func queryGroups() []queryGroup { everythingGroup(), rangeGroup(), photoGroup(), + extractionGroup(), scopeGroup(), invalidGroup(), quotingGroup(), diff --git a/services/search/pkg/parity/query_extraction_test.go b/services/search/pkg/parity/query_extraction_test.go new file mode 100644 index 0000000000..998cbe7626 --- /dev/null +++ b/services/search/pkg/parity/query_extraction_test.go @@ -0,0 +1,22 @@ +package parity + +import ( + "github.com/opencloud-eu/opencloud/services/search/pkg/search" +) + +func extractionGroup() queryGroup { + return queryGroup{ + name: "extraction", + fixtures: []search.Resource{ + fixtureDoc("given-up.pdf", withExtractionFailure(3, "")), + fixtureDoc("waiting.png", withExtractionFailure(1, "2030-01-01T00:00:00Z")), + fixtureDoc("extracted.txt"), + }, + cases: []queryCase{ + {id: 1, query: `extractionfailure.count>=3`, want: []string{"given-up.pdf"}}, + {id: 2, query: `ExtractionFailure.Count>=1`, want: []string{"given-up.pdf", "waiting.png"}}, + {id: 3, query: `extractionfailure.retryat>"2029-01-01T00:00:00Z"`, want: []string{"waiting.png"}}, + {id: 4, query: `extractionfailure.retryat<"2029-01-01T00:00:00Z"`}, + }, + } +} diff --git a/services/search/pkg/search/search.go b/services/search/pkg/search/search.go index 162083f177..dcd283d542 100644 --- a/services/search/pkg/search/search.go +++ b/services/search/pkg/search/search.go @@ -7,6 +7,7 @@ import ( "regexp" "strings" "sync" + "time" gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" @@ -85,9 +86,19 @@ type Resource struct { Type uint64 `json:"Type"` Deleted bool `json:"Deleted"` Hidden bool `json:"Hidden"` - // ExtractionFailed marks a document indexed without its content, the next - // reindex extracts it again; entries from before the field count as extracted - ExtractionFailed bool `json:"ExtractionFailed"` + // ExtractionFailure is set while the content of this version could not be + // parsed, nil means extracted; entries from before the field count as extracted + ExtractionFailure *ExtractionFailure `json:"ExtractionFailure,omitempty"` +} + +// ExtractionFailure is the indexer's own bookkeeping, not derived from the +// storage: losing it with the index costs retries, never data. Two walks failing +// at once may count one failure, that buys one more attempt. +type ExtractionFailure struct { + // Count is the number of parse failures of the indexed version + Count int `json:"Count"` + // RetryAt is the earliest next attempt, nil once the attempts are used up + RetryAt *time.Time `json:"RetryAt,omitempty"` } // resourceFieldOverrides is built once (it never changes) and reused on hot diff --git a/services/search/pkg/search/service.go b/services/search/pkg/search/service.go index 2c3e37b8c4..ba47f903c3 100644 --- a/services/search/pkg/search/service.go +++ b/services/search/pkg/search/service.go @@ -88,6 +88,11 @@ type Service struct { var errSkipSpace error +// a parse failure is retried after these delays, then given up until the file +// changes; ocr and image tools also fail under load, so the spacing outlasts a +// burst of uploads instead of spending every attempt inside it +var extractionRetryDelays = []time.Duration{time.Hour, 24 * time.Hour} + // NewService creates a new Provider instance. func NewService(gatewaySelector pool.Selectable[gateway.GatewayAPIClient], eng Engine, extractor content.Extractor, metrics *metrics.Metrics, logger log.Logger, cfg *config.Config) *Service { // NewBasicExtractor has no failure path @@ -832,12 +837,17 @@ func (s *Service) upsertResource(ctx context.Context, ref *provider.Reference, s return } - // a failed extraction still yields the name, path and tags, the resource - // stays findable and the next space walk retries it + // an unparsable file still yields the name, path and tags and stays findable; + // any other failure (tika or the file unreachable) writes nothing, the next + // space walk finds the entry missing or outdated and tries again doc, err := s.extractor.Extract(ctx, stat.GetInfo()) extractionFailed := err != nil - if err != nil { + switch { + case errors.Is(err, content.ErrUnparsable): s.logger.Error().Err(err).Str("path", path).Msg("failed to extract resource content") + case err != nil: + s.logger.Error().Err(err).Str("path", path).Msg("failed to extract resource content, retrying on the next walk") + return } r := Resource{ @@ -852,7 +862,9 @@ func (s *Service) upsertResource(ctx context.Context, ref *provider.Reference, s Document: doc, } r.Hidden = IsHidden(r.Path) - r.ExtractionFailed = extractionFailed + if extractionFailed { + r.ExtractionFailure = s.nextExtractionFailure(ctx, r.ID, stat.GetInfo(), path) + } if parentID := stat.GetInfo().GetParentId(); parentID != nil { r.ParentID = storagespace.FormatResourceID(parentID) @@ -944,7 +956,34 @@ func (s *Service) isIndexed(ctx context.Context, info *provider.ResourceInfo) bo s.logger.Error().Err(err).Interface("id", info.GetId()).Msg("failed to look up the indexed resource, indexing it again") return false } - return !r.Deleted && !r.ExtractionFailed && r.Mtime != nil && !r.Mtime.Before(utils.TSToTime(info.GetMtime())) + if r.Deleted || r.Mtime == nil || r.Mtime.Before(utils.TSToTime(info.GetMtime())) { + return false + } + f := r.ExtractionFailure + return f == nil || f.Count > len(extractionRetryDelays) || (f.RetryAt != nil && time.Now().Before(*f.RetryAt)) +} + +// nextExtractionFailure counts a parse failure on top of the ones the indexed +// entry holds for the same version, a new version starts over +func (s *Service) nextExtractionFailure(ctx context.Context, id string, info *provider.ResourceInfo, path string) *ExtractionFailure { + count := 1 + r, err := s.engine.Get(ctx, id) + switch { + case errors.Is(err, ErrResourceNotFound): + case err != nil: + s.logger.Error().Err(err).Str("id", id).Msg("failed to look up the previous extraction failures, counting this one as the first") + case r.ExtractionFailure != nil && r.Mtime != nil && !r.Mtime.Before(utils.TSToTime(info.GetMtime())): + count = r.ExtractionFailure.Count + 1 + } + + f := &ExtractionFailure{Count: count} + if count > len(extractionRetryDelays) { + s.logger.Warn().Str("path", path).Int("failures", count).Msg("giving up on extracting the resource content until it changes, opencloud search index --force-rescan tries again") + return f + } + retryAt := time.Now().Add(extractionRetryDelays[count-1]) + f.RetryAt = &retryAt + return f } func (s *Service) resInfo(ctx context.Context, ref *provider.Reference) (*provider.StatResponse, string) { diff --git a/services/search/pkg/search/service_test.go b/services/search/pkg/search/service_test.go index fd15999a5c..9fc87d5885 100644 --- a/services/search/pkg/search/service_test.go +++ b/services/search/pkg/search/service_test.go @@ -3,6 +3,7 @@ package search_test import ( "context" "errors" + "fmt" "time" gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" @@ -158,14 +159,24 @@ var _ = Describe("Searchprovider", func() { info("outdated", sprovider.ResourceType_RESOURCE_TYPE_FILE, 5000), info("missing", sprovider.ResourceType_RESOURCE_TYPE_FILE, 4000), info("trashed", sprovider.ResourceType_RESOURCE_TYPE_FILE, 4000), - info("failed", sprovider.ResourceType_RESOURCE_TYPE_FILE, 4000), + info("failed-due", sprovider.ResourceType_RESOURCE_TYPE_FILE, 4000), + info("failed-waiting", sprovider.ResourceType_RESOURCE_TYPE_FILE, 4000), + info("failed-given-up", sprovider.ResourceType_RESOURCE_TYPE_FILE, 4000), + info("failed-given-up-changed", sprovider.ResourceType_RESOURCE_TYPE_FILE, 5000), } indexed := map[string]*search.Resource{ "storageid$spaceid!spaceid": {Document: content.Document{Mtime: &indexedAt}}, "storageid$spaceid!current": {Document: content.Document{Mtime: &indexedAt}}, "storageid$spaceid!outdated": {Document: content.Document{Mtime: &indexedAt}}, "storageid$spaceid!trashed": {Document: content.Document{Mtime: &indexedAt}, Deleted: true}, - "storageid$spaceid!failed": {Document: content.Document{Mtime: &indexedAt}, ExtractionFailed: true}, + "storageid$spaceid!failed-due": {Document: content.Document{Mtime: &indexedAt}, + ExtractionFailure: &search.ExtractionFailure{Count: 1, RetryAt: ptr(time.Now().Add(-time.Minute))}}, + "storageid$spaceid!failed-waiting": {Document: content.Document{Mtime: &indexedAt}, + ExtractionFailure: &search.ExtractionFailure{Count: 2, RetryAt: ptr(time.Now().Add(time.Hour))}}, + "storageid$spaceid!failed-given-up": {Document: content.Document{Mtime: &indexedAt}, + ExtractionFailure: &search.ExtractionFailure{Count: 3}}, + "storageid$spaceid!failed-given-up-changed": {Document: content.Document{Mtime: &indexedAt}, + ExtractionFailure: &search.ExtractionFailure{Count: 3}}, } gatewayClient.On("GetUserByClaim", mock.Anything, mock.Anything).Return(&userv1beta1.GetUserByClaimResponse{ @@ -204,7 +215,13 @@ var _ = Describe("Searchprovider", func() { err := s.IndexSpace(&sprovider.StorageSpaceId{OpaqueId: "storageid$spaceid!spaceid"}, false) Expect(err).ShouldNot(HaveOccurred()) - Expect(upserted).To(ConsistOf("storageid$spaceid!outdated", "storageid$spaceid!missing", "storageid$spaceid!trashed", "storageid$spaceid!failed")) + Expect(upserted).To(ConsistOf( + "storageid$spaceid!outdated", + "storageid$spaceid!missing", + "storageid$spaceid!trashed", + "storageid$spaceid!failed-due", + "storageid$spaceid!failed-given-up-changed", + )) }) }) @@ -251,21 +268,56 @@ var _ = Describe("Searchprovider", func() { Entry("/", "/", false), ) - It("indexes a resource whose extraction failed by name and marks it", func() { + DescribeTable("indexes an unparsable resource by name and counts the failures of its version", + func(previous *search.Resource, count int, retryIn time.Duration) { + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(&sprovider.StatResponse{ + Status: status.NewOK(context.Background()), + Info: ri, + }, nil) + extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{Name: "scan.png"}, fmt.Errorf("%w %q", content.ErrUnparsable, "scan.png")) + if previous == nil { + indexClient.On("Get", mock.Anything, mock.Anything).Return(nil, search.ErrResourceNotFound) + } else { + indexClient.On("Get", mock.Anything, mock.Anything).Return(previous, nil) + } + + var indexed search.Resource + indexClient.On("Upsert", mock.Anything, mock.Anything).Run(func(args mock.Arguments) { + indexed = args.Get(1).(search.Resource) + }).Return(nil) + + s.UpdateMetadata(&sprovider.Reference{ResourceId: ri.GetId()}) + Expect(indexed.Name).To(Equal("scan.png")) + Expect(indexed.ExtractionFailure).ToNot(BeNil()) + Expect(indexed.ExtractionFailure.Count).To(Equal(count)) + if retryIn == 0 { + Expect(indexed.ExtractionFailure.RetryAt).To(BeNil()) + } else { + Expect(indexed.ExtractionFailure.RetryAt).NotTo(BeNil()) + Expect(*indexed.ExtractionFailure.RetryAt).To(BeTemporally("~", time.Now().Add(retryIn), time.Minute)) + } + }, + Entry("first failure", nil, 1, time.Hour), + Entry("second failure of the same version", + &search.Resource{Document: content.Document{Mtime: ptr(time.Unix(4000, 0))}, ExtractionFailure: &search.ExtractionFailure{Count: 1}}, + 2, 24*time.Hour), + Entry("third failure of the same version gives up", + &search.Resource{Document: content.Document{Mtime: ptr(time.Unix(4000, 0))}, ExtractionFailure: &search.ExtractionFailure{Count: 2}}, + 3, time.Duration(0)), + Entry("a new version starts over", + &search.Resource{Document: content.Document{Mtime: ptr(time.Unix(3000, 0))}, ExtractionFailure: &search.ExtractionFailure{Count: 3}}, + 1, time.Hour), + ) + + It("writes nothing when tika or the file is unreachable", func() { gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(&sprovider.StatResponse{ Status: status.NewOK(context.Background()), Info: ri, }, nil) - extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{Name: "scan.png"}, errors.New("tika failed to parse")) - - var indexed search.Resource - indexClient.On("Upsert", mock.Anything, mock.Anything).Run(func(args mock.Arguments) { - indexed = args.Get(1).(search.Resource) - }).Return(nil) + extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{Name: "scan.png"}, errors.New("connection refused")) s.UpdateMetadata(&sprovider.Reference{ResourceId: ri.GetId()}) - Expect(indexed.Name).To(Equal("scan.png")) - Expect(indexed.ExtractionFailed).To(BeTrue()) + indexClient.AssertNotCalled(GinkgoT(), "Upsert", mock.Anything, mock.Anything) }) Context("with facets stored on the resource", func() { @@ -368,7 +420,8 @@ var _ = Describe("Searchprovider", func() { }) It("keeps the stored facets when the extraction failed", func() { - extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, errors.New("tika failed to parse")) + extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, content.ErrUnparsable) + indexClient.On("Get", mock.Anything, mock.Anything).Return(nil, search.ErrResourceNotFound) s.UpdateMetadata(&sprovider.Reference{ResourceId: info.GetId()}) Expect(calls).To(BeEmpty()) @@ -940,3 +993,7 @@ var _ = DescribeTable("Parse Scope", `1234$5678!90`, ), ) + +func ptr[T any](v T) *T { + return &v +} From cf5a087de2d1c5510f5d56e308ee402eb975be15 Mon Sep 17 00:00:00 2001 From: Florian Schade Date: Tue, 24 Nov 2026 17:51:11 +0100 Subject: [PATCH 6/6] fix(search): index files by name while tika is unreachable --- services/search/README.md | 2 +- services/search/pkg/search/search.go | 6 ++- services/search/pkg/search/service.go | 54 ++++++++++++++-------- services/search/pkg/search/service_test.go | 50 ++++++++++++++++---- 4 files changed, 82 insertions(+), 30 deletions(-) diff --git a/services/search/README.md b/services/search/README.md index 7d60201ebb..8b2bdecc30 100644 --- a/services/search/README.md +++ b/services/search/README.md @@ -163,7 +163,7 @@ Additionally, the following optional settings can be set: #### Files Tika Cannot Parse -A file Tika cannot parse, such as a broken PDF or an image the OCR fails on, is still indexed by name, path and tags, so it stays findable. The content is tried again on later reindexes, the first retry one hour after the failure, the second one day after that. After the third failure the service logs a warning with the path and stops trying until the file changes. If Tika itself is unreachable, nothing is written and the next reindex tries again. +A file Tika cannot parse, such as a broken PDF or an image the OCR fails on, is still indexed by name, path and tags, so it stays findable. The content is tried again on later reindexes, the first retry one hour after the failure, the second one day after that. After the third failure the service logs a warning with the path and stops trying until the file changes. If Tika or the file is unreachable, a new or changed file is indexed by name as well, this does not count as a failure and every later reindex tries again. To list the files the service gave up on, search for: diff --git a/services/search/pkg/search/search.go b/services/search/pkg/search/search.go index dcd283d542..90a9ac6d0e 100644 --- a/services/search/pkg/search/search.go +++ b/services/search/pkg/search/search.go @@ -95,9 +95,11 @@ type Resource struct { // storage: losing it with the index costs retries, never data. Two walks failing // at once may count one failure, that buys one more attempt. type ExtractionFailure struct { - // Count is the number of parse failures of the indexed version + // Count is the number of parse failures of the indexed version, 0 when only + // tika or the file was unreachable and every walk retries it Count int `json:"Count"` - // RetryAt is the earliest next attempt, nil once the attempts are used up + // RetryAt is the earliest next attempt, nil for an immediate retry or once + // the attempts are used up RetryAt *time.Time `json:"RetryAt,omitempty"` } diff --git a/services/search/pkg/search/service.go b/services/search/pkg/search/service.go index ba47f903c3..bbbabdf0c5 100644 --- a/services/search/pkg/search/service.go +++ b/services/search/pkg/search/service.go @@ -837,17 +837,12 @@ func (s *Service) upsertResource(ctx context.Context, ref *provider.Reference, s return } - // an unparsable file still yields the name, path and tags and stays findable; - // any other failure (tika or the file unreachable) writes nothing, the next - // space walk finds the entry missing or outdated and tries again + // a failed extraction still yields the name, path and tags, the resource + // stays findable and a later space walk retries it doc, err := s.extractor.Extract(ctx, stat.GetInfo()) extractionFailed := err != nil - switch { - case errors.Is(err, content.ErrUnparsable): + if err != nil { s.logger.Error().Err(err).Str("path", path).Msg("failed to extract resource content") - case err != nil: - s.logger.Error().Err(err).Str("path", path).Msg("failed to extract resource content, retrying on the next walk") - return } r := Resource{ @@ -863,7 +858,11 @@ func (s *Service) upsertResource(ctx context.Context, ref *provider.Reference, s } r.Hidden = IsHidden(r.Path) if extractionFailed { - r.ExtractionFailure = s.nextExtractionFailure(ctx, r.ID, stat.GetInfo(), path) + var write bool + r.ExtractionFailure, write = s.nextExtractionFailure(ctx, r.ID, stat.GetInfo(), path, errors.Is(err, content.ErrUnparsable)) + if !write { + return + } } if parentID := stat.GetInfo().GetParentId(); parentID != nil { @@ -964,26 +963,45 @@ func (s *Service) isIndexed(ctx context.Context, info *provider.ResourceInfo) bo } // nextExtractionFailure counts a parse failure on top of the ones the indexed -// entry holds for the same version, a new version starts over -func (s *Service) nextExtractionFailure(ctx context.Context, id string, info *provider.ResourceInfo, path string) *ExtractionFailure { - count := 1 +// entry holds for the same version, a new version starts over. Any other failure +// (tika or the file unreachable) says nothing about the file: it is not counted, +// leaves a current entry alone and is retried by every walk. write is false +// when the indexed entry has to stay as it is. +func (s *Service) nextExtractionFailure(ctx context.Context, id string, info *provider.ResourceInfo, path string, unparsable bool) (f *ExtractionFailure, write bool) { + var previous *Resource r, err := s.engine.Get(ctx, id) switch { case errors.Is(err, ErrResourceNotFound): case err != nil: - s.logger.Error().Err(err).Str("id", id).Msg("failed to look up the previous extraction failures, counting this one as the first") - case r.ExtractionFailure != nil && r.Mtime != nil && !r.Mtime.Before(utils.TSToTime(info.GetMtime())): - count = r.ExtractionFailure.Count + 1 + s.logger.Error().Err(err).Str("id", id).Msg("failed to look up the previous extraction failures") + if !unparsable { + // without knowing the entry, a name-only document could replace extracted content + return nil, false + } + case r.Mtime != nil && !r.Mtime.Before(utils.TSToTime(info.GetMtime())): + previous = r } - f := &ExtractionFailure{Count: count} + if !unparsable { + if previous != nil && !previous.Deleted { + return nil, false + } + return &ExtractionFailure{}, true + } + + count := 1 + if previous != nil && previous.ExtractionFailure != nil { + count = previous.ExtractionFailure.Count + 1 + } + + f = &ExtractionFailure{Count: count} if count > len(extractionRetryDelays) { s.logger.Warn().Str("path", path).Int("failures", count).Msg("giving up on extracting the resource content until it changes, opencloud search index --force-rescan tries again") - return f + return f, true } retryAt := time.Now().Add(extractionRetryDelays[count-1]) f.RetryAt = &retryAt - return f + return f, true } func (s *Service) resInfo(ctx context.Context, ref *provider.Reference) (*provider.StatResponse, string) { diff --git a/services/search/pkg/search/service_test.go b/services/search/pkg/search/service_test.go index 9fc87d5885..27724b5176 100644 --- a/services/search/pkg/search/service_test.go +++ b/services/search/pkg/search/service_test.go @@ -163,6 +163,7 @@ var _ = Describe("Searchprovider", func() { info("failed-waiting", sprovider.ResourceType_RESOURCE_TYPE_FILE, 4000), info("failed-given-up", sprovider.ResourceType_RESOURCE_TYPE_FILE, 4000), info("failed-given-up-changed", sprovider.ResourceType_RESOURCE_TYPE_FILE, 5000), + info("failed-unreachable", sprovider.ResourceType_RESOURCE_TYPE_FILE, 4000), } indexed := map[string]*search.Resource{ "storageid$spaceid!spaceid": {Document: content.Document{Mtime: &indexedAt}}, @@ -177,6 +178,8 @@ var _ = Describe("Searchprovider", func() { ExtractionFailure: &search.ExtractionFailure{Count: 3}}, "storageid$spaceid!failed-given-up-changed": {Document: content.Document{Mtime: &indexedAt}, ExtractionFailure: &search.ExtractionFailure{Count: 3}}, + "storageid$spaceid!failed-unreachable": {Document: content.Document{Mtime: &indexedAt}, + ExtractionFailure: &search.ExtractionFailure{}}, } gatewayClient.On("GetUserByClaim", mock.Anything, mock.Anything).Return(&userv1beta1.GetUserByClaimResponse{ @@ -221,6 +224,7 @@ var _ = Describe("Searchprovider", func() { "storageid$spaceid!trashed", "storageid$spaceid!failed-due", "storageid$spaceid!failed-given-up-changed", + "storageid$spaceid!failed-unreachable", )) }) }) @@ -309,16 +313,44 @@ var _ = Describe("Searchprovider", func() { 1, time.Hour), ) - It("writes nothing when tika or the file is unreachable", func() { - gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(&sprovider.StatResponse{ - Status: status.NewOK(context.Background()), - Info: ri, - }, nil) - extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{Name: "scan.png"}, errors.New("connection refused")) + DescribeTable("indexes a resource by name without counting when tika or the file is unreachable", + func(previous *search.Resource, getErr error, written bool) { + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(&sprovider.StatResponse{ + Status: status.NewOK(context.Background()), + Info: ri, + }, nil) + extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{Name: "scan.png"}, errors.New("connection refused")) + indexClient.On("Get", mock.Anything, mock.Anything).Return(previous, getErr) - s.UpdateMetadata(&sprovider.Reference{ResourceId: ri.GetId()}) - indexClient.AssertNotCalled(GinkgoT(), "Upsert", mock.Anything, mock.Anything) - }) + var indexed []search.Resource + indexClient.On("Upsert", mock.Anything, mock.Anything).Run(func(args mock.Arguments) { + indexed = append(indexed, args.Get(1).(search.Resource)) + }).Return(nil) + + s.UpdateMetadata(&sprovider.Reference{ResourceId: ri.GetId()}) + if !written { + Expect(indexed).To(BeEmpty()) + return + } + Expect(indexed).To(HaveLen(1)) + Expect(indexed[0].Name).To(Equal("scan.png")) + Expect(indexed[0].ExtractionFailure).To(Equal(&search.ExtractionFailure{})) + }, + Entry("a new resource", nil, search.ErrResourceNotFound, true), + Entry("an outdated entry", + &search.Resource{Document: content.Document{Mtime: ptr(time.Unix(3000, 0)), Content: "old"}}, + nil, true), + Entry("an outdated entry with parse failures starts over", + &search.Resource{Document: content.Document{Mtime: ptr(time.Unix(3000, 0))}, ExtractionFailure: &search.ExtractionFailure{Count: 2}}, + nil, true), + Entry("a current entry keeps its content", + &search.Resource{Document: content.Document{Mtime: ptr(time.Unix(4000, 0)), Content: "extracted"}}, + nil, false), + Entry("a current entry keeps its parse failures", + &search.Resource{Document: content.Document{Mtime: ptr(time.Unix(4000, 0))}, ExtractionFailure: &search.ExtractionFailure{Count: 3}}, + nil, false), + Entry("an unknown entry is left alone", nil, errors.New("index unavailable"), false), + ) Context("with facets stored on the resource", func() { var (