Skip to content

Commit f2cb7e1

Browse files
committed
Fix settle-window drainer cancellation in library ingest
1 parent ea5be46 commit f2cb7e1

2 files changed

Lines changed: 95 additions & 36 deletions

File tree

‎internal/libraryingest/executor.go‎

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,8 @@ func (e *Executor) ingest(ctx context.Context, folder *models.MediaFolder, mode
165165
CurrentScope: claim.path,
166166
})
167167
runStartedAt := time.Now().UTC()
168-
drainerCtx, stopDrainers := context.WithCancel(scanCtx)
168+
drainerStopCtx, stopDrainers := context.WithCancel(context.Background())
169+
defer stopDrainers()
169170
drainerErrCh := make(chan error, 1)
170171
var drainerWG sync.WaitGroup
171172
if len(matchScopes) > 0 {
@@ -180,24 +181,21 @@ func (e *Executor) ingest(ctx context.Context, folder *models.MediaFolder, mode
180181
ticker := time.NewTicker(scopedDrainInterval)
181182
defer ticker.Stop()
182183
for {
183-
if drainerCtx.Err() != nil {
184+
select {
185+
case <-scanCtx.Done():
186+
return
187+
case <-drainerStopCtx.Done():
184188
return
189+
default:
185190
}
186191
started := time.Now()
187-
processed, err := e.matcher.ProcessBatchByFolderAndPathPrefix(drainerCtx, folder.ID, scopePath, runStartedAt)
192+
processed, err := e.matcher.ProcessBatchByFolderAndPathPrefix(scanCtx, folder.ID, scopePath, runStartedAt)
188193
concurrentMatchDuration.Add(time.Since(started).Nanoseconds())
189194
if processed > 0 {
190195
concurrentMatched.Add(int64(processed))
191196
}
192197
if err != nil {
193-
// A cancelled drainer context means this is a deliberate
194-
// shutdown (the settle window ended and stopDrainers ran, or
195-
// the whole scan is being torn down), not a real failure. The
196-
// in-flight ProcessBatch call returns context.Canceled here, so
197-
// exit cleanly without escalating. Genuine external
198-
// cancellation still reaches the run via the scanCtx checks in
199-
// the main goroutine, so this does not swallow real cancels.
200-
if drainerCtx.Err() != nil {
198+
if scanCtx.Err() != nil {
201199
return
202200
}
203201
select {
@@ -208,7 +206,9 @@ func (e *Executor) ingest(ctx context.Context, folder *models.MediaFolder, mode
208206
return
209207
}
210208
select {
211-
case <-drainerCtx.Done():
209+
case <-scanCtx.Done():
210+
return
211+
case <-drainerStopCtx.Done():
212212
return
213213
case <-ticker.C:
214214
}
@@ -234,6 +234,7 @@ func (e *Executor) ingest(ctx context.Context, folder *models.MediaFolder, mode
234234
scanStarted := time.Now()
235235
scanMatchScopes, scanResult, err := e.scan(scanProgressCtx, folder, mode, claim.path)
236236
if err != nil {
237+
cancel()
237238
stopDrainers()
238239
drainerWG.Wait()
239240
if len(matchScopes) > 0 {

‎internal/libraryingest/executor_test.go‎

Lines changed: 82 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package libraryingest
22

33
import (
44
"context"
5+
"sync"
56
"sync/atomic"
67
"testing"
78
"time"
@@ -10,25 +11,50 @@ import (
1011
"github.com/Silo-Server/silo-server/internal/scanner"
1112
)
1213

13-
// settleBlockingMatcher simulates a TV match drainer whose provider lookup is
14-
// still in flight when the settle window expires: the batch call blocks until
15-
// its context is cancelled, then returns context.Canceled — exactly what
16-
// stopDrainers triggers when it cancels the drainer context.
17-
type settleBlockingMatcher struct {
18-
batchCalls atomic.Int64
14+
// settleControlledMatcher simulates a TV match drainer whose provider lookup is
15+
// still in flight when the settle window expires. The batch only returns once
16+
// the test releases it, so the test can catch stopDrainers cancelling the active
17+
// batch context instead of only stopping the drainer loop.
18+
type settleControlledMatcher struct {
19+
batchCalls atomic.Int64
20+
batchCompleted atomic.Bool
21+
batchCtxCanceled atomic.Bool
22+
processAllBeforeBatch atomic.Bool
23+
batchStarted chan struct{}
24+
releaseBatch chan struct{}
25+
closeBatchStartedOnce sync.Once
1926
}
2027

21-
func (m *settleBlockingMatcher) ProcessBatchByFolderAndPathPrefix(ctx context.Context, _ int, _ string, _ time.Time) (int, error) {
28+
func newSettleControlledMatcher() *settleControlledMatcher {
29+
return &settleControlledMatcher{
30+
batchStarted: make(chan struct{}),
31+
releaseBatch: make(chan struct{}),
32+
}
33+
}
34+
35+
func (m *settleControlledMatcher) ProcessBatchByFolderAndPathPrefix(ctx context.Context, _ int, _ string, _ time.Time) (int, error) {
2236
m.batchCalls.Add(1)
23-
<-ctx.Done()
24-
return 0, ctx.Err()
37+
m.closeBatchStartedOnce.Do(func() {
38+
close(m.batchStarted)
39+
})
40+
select {
41+
case <-ctx.Done():
42+
m.batchCtxCanceled.Store(true)
43+
return 0, ctx.Err()
44+
case <-m.releaseBatch:
45+
m.batchCompleted.Store(true)
46+
return 1, nil
47+
}
2548
}
2649

27-
func (m *settleBlockingMatcher) ProcessAllByFolderAndPathPrefix(context.Context, int, string, time.Time) (int, error) {
50+
func (m *settleControlledMatcher) ProcessAllByFolderAndPathPrefix(context.Context, int, string, time.Time) (int, error) {
51+
if !m.batchCompleted.Load() {
52+
m.processAllBeforeBatch.Store(true)
53+
}
2854
return 0, nil
2955
}
3056

31-
func (m *settleBlockingMatcher) RetryUnmatchedItemsByFolderAndPathPrefix(context.Context, int, string) (int, int, error) {
57+
func (m *settleControlledMatcher) RetryUnmatchedItemsByFolderAndPathPrefix(context.Context, int, string) (int, int, error) {
3258
return 0, 0, nil
3359
}
3460

@@ -54,29 +80,61 @@ func (s *settleStubScanner) FinalizeVariantsByPathPrefix(context.Context, *model
5480
return nil
5581
}
5682

57-
// TestIngestFolderCompletesWhenDrainerCanceledMidBatch is a regression test for
58-
// the settle-window cancellation bug: a TV library full scan was recorded as
59-
// "cancelled" because a drainer batch in flight when stopDrainers() ran returned
60-
// context.Canceled, which the drainer escalated as a fatal scan error. The
61-
// ingest must instead complete normally.
62-
func TestIngestFolderCompletesWhenDrainerCanceledMidBatch(t *testing.T) {
63-
matcher := &settleBlockingMatcher{}
83+
// TestIngestFolderLetsActiveDrainerBatchFinishAfterSettleWindow is a regression
84+
// test for the settle-window cancellation bug: a TV library full scan was
85+
// recorded as "cancelled" because stopDrainers cancelled a drainer batch that
86+
// was already in flight. The active batch must be allowed to finish; otherwise
87+
// rows it already claimed can be excluded from the final scoped matcher by the
88+
// runStartedAt attempt window.
89+
func TestIngestFolderLetsActiveDrainerBatchFinishAfterSettleWindow(t *testing.T) {
90+
const settleWindow = 25 * time.Millisecond
91+
92+
matcher := newSettleControlledMatcher()
6493
exec := &Executor{
6594
scanner: &settleStubScanner{result: &scanner.ScanResult{New: 1}},
6695
matcher: matcher,
6796
now: time.Now,
68-
tvDrainSettleWindow: 50 * time.Millisecond,
97+
tvDrainSettleWindow: settleWindow,
6998
}
7099
folder := &models.MediaFolder{ID: 5, Type: "series", Paths: []string{"/tv"}}
71100

72-
result, err := exec.IngestFolder(context.Background(), folder)
73-
if err != nil {
74-
t.Fatalf("expected ingest to complete, got error: %v", err)
101+
type ingestResult struct {
102+
result *Result
103+
err error
75104
}
76-
if result == nil || result.Skipped {
77-
t.Fatalf("expected a non-skipped result, got %+v", result)
105+
done := make(chan ingestResult, 1)
106+
go func() {
107+
result, err := exec.IngestFolder(context.Background(), folder)
108+
done <- ingestResult{result: result, err: err}
109+
}()
110+
111+
select {
112+
case <-matcher.batchStarted:
113+
case <-time.After(time.Second):
114+
t.Fatal("drainer never started a batch")
115+
}
116+
time.Sleep(2 * settleWindow)
117+
close(matcher.releaseBatch)
118+
119+
var got ingestResult
120+
select {
121+
case got = <-done:
122+
case <-time.After(time.Second):
123+
t.Fatal("ingest did not complete after releasing the active drainer batch")
124+
}
125+
if got.err != nil {
126+
t.Fatalf("expected ingest to complete, got error: %v", got.err)
127+
}
128+
if got.result == nil || got.result.Skipped {
129+
t.Fatalf("expected a non-skipped result, got %+v", got.result)
78130
}
79131
if matcher.batchCalls.Load() == 0 {
80132
t.Fatal("drainer never ran a batch; test did not exercise the settle-window shutdown path")
81133
}
134+
if matcher.batchCtxCanceled.Load() {
135+
t.Fatal("settle-window shutdown cancelled the active drainer batch context")
136+
}
137+
if matcher.processAllBeforeBatch.Load() {
138+
t.Fatal("final scoped matcher ran before the active drainer batch completed")
139+
}
82140
}

0 commit comments

Comments
 (0)