feat(search): retry extractions tika could not answer during a walk

This commit is contained in:
Florian Schade committed 2026-11-25 11:13:32 +01:00
1 parent 9ebb6a75a6
commit debbeae2cb
4 files changed
+244 -16

No files matched your search

+1 -1
View File
@@ -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 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.
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 space reindex retries the extraction up to five times, one second apart, so a restarting Tika does not leave gaps. A file still unreachable after that is indexed by name as well, this does not count as a failure and every later reindex tries again. After five such files in a row the reindex assumes Tika is down: it indexes the remaining files by name without retries until an extraction succeeds again, and reports an error naming the number of files indexed by name only once the space is done.
To list the files the service gave up on, search for:
+11
View File
@@ -0,0 +1,11 @@
package search
import "time"
// SetUnreachableRetryDelay shortens the wait between extraction retries, a walk
// test would otherwise sleep a second per retry
func SetUnreachableRetryDelay(d time.Duration) (restore func()) {
previous := unreachableRetryDelay
unreachableRetryDelay = d
return func() { unreachableRetryDelay = previous }
}
+86 -15
View File
@@ -93,6 +93,17 @@ var errSkipSpace error
// burst of uploads instead of spending every attempt inside it
var extractionRetryDelays = []time.Duration{time.Hour, 24 * time.Hour}
// a restarting tika answers again within seconds, so a space walk retries an
// extraction that could not reach tika or the file before indexing it by name
var (
unreachableRetries = 5
unreachableRetryDelay = time.Second
)
// this many files in a row out of reach after their retries means tika is down,
// not that one file is gone
const unreachableStreakLimit = 5
// 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
@@ -549,6 +560,7 @@ func (s *Service) IndexSpace(spaceID *provider.StorageSpaceId, forceRescan bool)
}()
w := walker.NewWalker(s.gatewaySelector)
unreachable := &unreachableExtractions{}
batch, err := s.engine.NewBatch(s.batchSize)
if err != nil {
return err
@@ -583,7 +595,7 @@ func (s *Service) IndexSpace(spaceID *provider.StorageSpaceId, forceRescan bool)
s.logger.Debug().Str("path", ref.Path).Msg("Walking tree")
if forceRescan {
s.doUpsertItem(session.Ctx(), ref, batch)
s.doUpsertItem(session.Ctx(), ref, batch, unreachable)
return nil
}
@@ -594,11 +606,15 @@ func (s *Service) IndexSpace(spaceID *provider.StorageSpaceId, forceRescan bool)
return nil
}
s.doUpsertItem(session.Ctx(), ref, batch)
s.doUpsertItem(session.Ctx(), ref, batch, unreachable)
return nil
})
if err != nil {
return err
}
err = unreachable.err()
if err != nil {
return err
}
@@ -706,21 +722,12 @@ func (s *Service) UpdateMetadata(ref *provider.Reference) {
})
switch {
case errors.Is(err, ErrResourceNotFound):
s.upsertResource(ctx, ref, stat, path, nil)
s.upsertResource(ctx, ref, stat, path, nil, 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)
if stat == nil || path == "" {
return
}
s.upsertResource(ctx, ref, stat, path, batch)
}
// SanitizeHighlights keeps the <mark> tags and escapes everything else.
func SanitizeHighlights(highlights string) string {
var b strings.Builder
@@ -830,8 +837,18 @@ 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) {
// doUpsertItem indexes or stores Resource data fields.
func (s *Service) doUpsertItem(ctx context.Context, ref *provider.Reference, batch BatchOperator, unreachable *unreachableExtractions) {
stat, path := s.resInfo(ctx, ref)
if stat == nil || path == "" {
return
}
s.upsertResource(ctx, ref, stat, path, batch, unreachable)
}
// upsertResource extracts and indexes the resource stat describes, a space walk
// passes unreachable to retry extractions that could not reach tika or the file
func (s *Service) upsertResource(ctx context.Context, ref *provider.Reference, stat *provider.StatResponse, path string, batch BatchOperator, unreachable *unreachableExtractions) {
if utils.IsProcessing(stat.GetInfo()) {
s.logger.Debug().Str("path", path).Msg("resource is still being processed. Skipping.")
return
@@ -839,7 +856,7 @@ func (s *Service) upsertResource(ctx context.Context, ref *provider.Reference, s
// 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())
doc, err := s.extract(ctx, stat.GetInfo(), unreachable)
extractionFailed := err != nil
if err != nil {
s.logger.Error().Err(err).Str("path", path).Msg("failed to extract resource content")
@@ -945,6 +962,36 @@ func (s *Service) upsertResource(ctx context.Context, ref *provider.Reference, s
}
}
// extract runs the content extraction and retries it while tika or the file is
// out of reach, unless unreachable is nil or says tika is down
func (s *Service) extract(ctx context.Context, info *provider.ResourceInfo, unreachable *unreachableExtractions) (content.Document, error) {
doc, err := s.extractor.Extract(ctx, info)
if unreachable == nil {
return doc, err
}
for retry := 0; retry < unreachableRetries && !unreachable.down && isUnreachable(err); retry++ {
select {
case <-ctx.Done():
return doc, err
case <-time.After(unreachableRetryDelay):
}
doc, err = s.extractor.Extract(ctx, info)
}
if !isUnreachable(err) {
unreachable.streak, unreachable.down = 0, false
return doc, err
}
unreachable.streak++
unreachable.files++
unreachable.last = err
if unreachable.streak == unreachableStreakLimit {
unreachable.down, unreachable.tripped = true, true
s.logger.Warn().Err(err).Int("files", unreachable.streak).Msg("tika or the files stay out of reach, the remaining files are indexed by name without retries until an extraction succeeds")
}
return doc, err
}
// 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()))
@@ -1058,3 +1105,27 @@ func tokenExpiry(ctx context.Context) (time.Time, error) {
}
return claims.ExpiresAt.Time, nil
}
// unreachableExtractions follows the extractions of one space walk that could
// not reach tika or the file. The walk does not stop when tika is down: the
// files are indexed by name, and IndexSpace reports the outage at the end.
type unreachableExtractions struct {
streak int
down bool
tripped bool
files int
last error
}
func (u *unreachableExtractions) err() error {
if !u.tripped {
return nil
}
return fmt.Errorf("tika or the files were out of reach, %d files indexed by name only: %w", u.files, u.last)
}
// isUnreachable tells a failure worth retrying from a file tika cannot parse,
// which fails the same way on the next attempt
func isUnreachable(err error) bool {
return err != nil && !errors.Is(err, content.ErrUnparsable)
}
+146
View File
@@ -227,6 +227,152 @@ var _ = Describe("Searchprovider", func() {
"storageid$spaceid!failed-unreachable",
))
})
Context("when tika or the files are out of reach", func() {
var (
files []string
extract func(name string, attempt int) (content.Document, error)
attempts map[string]int
upserted map[string]search.Resource
unreached = errors.New("connection refused")
)
BeforeEach(func() {
DeferCleanup(search.SetUnreachableRetryDelay(time.Millisecond))
attempts = map[string]int{}
upserted = map[string]search.Resource{}
root := &sprovider.ResourceInfo{
Id: &sprovider.ResourceId{StorageId: "storageid", SpaceId: "spaceid", OpaqueId: "spaceid"},
Type: sprovider.ResourceType_RESOURCE_TYPE_CONTAINER,
Path: ".",
Mtime: &typesv1beta1.Timestamp{Seconds: 4000},
}
children := func() []*sprovider.ResourceInfo {
infos := make([]*sprovider.ResourceInfo, 0, len(files))
for _, name := range files {
infos = append(infos, &sprovider.ResourceInfo{
Id: &sprovider.ResourceId{StorageId: "storageid", SpaceId: "spaceid", OpaqueId: name},
ParentId: root.GetId(),
Type: sprovider.ResourceType_RESOURCE_TYPE_FILE,
Path: name,
Mtime: &typesv1beta1.Timestamp{Seconds: 4000},
})
}
return infos
}
gatewayClient.On("GetUserByClaim", mock.Anything, mock.Anything).Return(&userv1beta1.GetUserByClaimResponse{
Status: status.NewOK(context.Background()),
User: user,
}, nil)
gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(
func(_ context.Context, req *sprovider.StatRequest, _ ...grpc.CallOption) (*sprovider.StatResponse, error) {
for _, child := range children() {
if req.GetRef().GetPath() == "./"+child.GetPath() {
return &sprovider.StatResponse{Status: status.NewOK(context.Background()), Info: child}, nil
}
}
return &sprovider.StatResponse{Status: status.NewOK(context.Background()), Info: root}, nil
})
gatewayClient.On("ListContainer", mock.Anything, mock.Anything).Return(
func(context.Context, *sprovider.ListContainerRequest, ...grpc.CallOption) (*sprovider.ListContainerResponse, error) {
return &sprovider.ListContainerResponse{Status: status.NewOK(context.Background()), Infos: children()}, nil
})
indexClient.On("Get", mock.Anything, mock.Anything).Return(nil, search.ErrResourceNotFound)
extractor.On("Extract", mock.Anything, mock.Anything).Return(
func(_ context.Context, info *sprovider.ResourceInfo) (content.Document, error) {
if info.GetType() == sprovider.ResourceType_RESOURCE_TYPE_CONTAINER {
return content.Document{}, nil
}
attempts[info.GetPath()]++
return extract(info.GetPath(), attempts[info.GetPath()])
})
batch := &engineMocks.BatchOperator{}
batch.EXPECT().Push().Return(nil)
batch.On("Upsert", mock.Anything, mock.Anything).Run(func(args mock.Arguments) {
upserted[args.String(0)] = args.Get(1).(search.Resource)
}).Return(nil)
indexClient.On("NewBatch", mock.Anything).Return(batch, nil)
})
It("retries the extraction and indexes the content once tika answers again", func() {
files = []string{"report.pdf"}
extract = func(_ string, attempt int) (content.Document, error) {
if attempt < 3 {
return content.Document{Name: "report.pdf"}, unreached
}
return content.Document{Name: "report.pdf", Content: "quarterly numbers"}, nil
}
Expect(s.IndexSpace(&sprovider.StorageSpaceId{OpaqueId: "storageid$spaceid!spaceid"}, false)).To(Succeed())
Expect(attempts).To(Equal(map[string]int{"report.pdf": 3}))
r := upserted["storageid$spaceid!report.pdf"]
Expect(r.Content).To(Equal("quarterly numbers"))
Expect(r.ExtractionFailure).To(BeNil())
})
It("indexes a file still out of reach by name without failing the walk", func() {
files = []string{"gone.pdf", "report.pdf"}
extract = func(name string, _ int) (content.Document, error) {
if name == "gone.pdf" {
return content.Document{Name: name}, unreached
}
return content.Document{Name: name}, nil
}
Expect(s.IndexSpace(&sprovider.StorageSpaceId{OpaqueId: "storageid$spaceid!spaceid"}, false)).To(Succeed())
Expect(attempts).To(Equal(map[string]int{"gone.pdf": 6, "report.pdf": 1}))
Expect(upserted["storageid$spaceid!gone.pdf"].ExtractionFailure).To(Equal(&search.ExtractionFailure{}))
})
It("does not retry a file tika cannot parse", func() {
files = []string{"scan.png"}
extract = func(name string, _ int) (content.Document, error) {
return content.Document{Name: name}, fmt.Errorf("%w %q", content.ErrUnparsable, name)
}
Expect(s.IndexSpace(&sprovider.StorageSpaceId{OpaqueId: "storageid$spaceid!spaceid"}, false)).To(Succeed())
Expect(attempts).To(Equal(map[string]int{"scan.png": 1}))
})
It("stops retrying once tika stays down, indexes the remaining files by name and reports it", func() {
files = []string{"a.pdf", "b.pdf", "c.pdf", "d.pdf", "e.pdf", "f.pdf", "g.pdf"}
extract = func(name string, _ int) (content.Document, error) {
return content.Document{Name: name}, unreached
}
err := s.IndexSpace(&sprovider.StorageSpaceId{OpaqueId: "storageid$spaceid!spaceid"}, false)
Expect(err).To(MatchError(unreached))
Expect(err).To(MatchError(ContainSubstring("7 files indexed by name only")))
Expect(attempts).To(Equal(map[string]int{
"a.pdf": 6, "b.pdf": 6, "c.pdf": 6, "d.pdf": 6, "e.pdf": 6,
"f.pdf": 1, "g.pdf": 1,
}))
for _, name := range files {
Expect(upserted).To(HaveKey("storageid$spaceid!" + name))
}
})
It("retries again once an extraction succeeds after tika was down", func() {
files = []string{"a.pdf", "b.pdf", "c.pdf", "d.pdf", "e.pdf", "back.pdf", "z.pdf"}
extract = func(name string, attempt int) (content.Document, error) {
switch {
case name == "back.pdf":
return content.Document{Name: name}, nil
case name == "z.pdf" && attempt > 1:
return content.Document{Name: name}, nil
}
return content.Document{Name: name}, unreached
}
// tika was down during the walk, which is still reported
Expect(s.IndexSpace(&sprovider.StorageSpaceId{OpaqueId: "storageid$spaceid!spaceid"}, false)).To(MatchError(unreached))
Expect(attempts).To(HaveKeyWithValue("back.pdf", 1))
Expect(attempts).To(HaveKeyWithValue("z.pdf", 2))
})
})
})
Describe("indexing a resource in full", func() {