fix(search): cap and space the retries of unparsable files

This commit is contained in:
Florian Schade committed 2026-11-24 17:37:54 +01:00
1 parent 8dc18b7f1d
commit 7577dbfd5d
13 files changed
+280 -34

No files matched your search

+12
View File
@@ -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:
+28 -9
View File
@@ -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,
+7 -2
View File
@@ -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 {
+2
View File
@@ -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"))
@@ -9,8 +9,15 @@
"Deleted": {
"type": "boolean"
},
"ExtractionFailed": {
"type": "boolean"
"ExtractionFailure": {
"properties": {
"Count": {
"type": "long"
},
"RetryAt": {
"type": "date"
}
}
},
"Favorites": {
"type": "keyword"
+15
View File
@@ -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:
@@ -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{
+42
View File
@@ -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())
})
}
})
@@ -111,6 +111,7 @@ func queryGroups() []queryGroup {
everythingGroup(),
rangeGroup(),
photoGroup(),
extractionGroup(),
scopeGroup(),
invalidGroup(),
quotingGroup(),
@@ -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"`},
},
}
}
+14 -3
View File
@@ -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
+44 -5
View File
@@ -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) {
+70 -13
View File
@@ -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
}