Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 17 additions & 5 deletions provider/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,14 @@ const (
defaultPageSize = 50
// ApplyEvents stops starting new events, and a rating snapshot page stops
// starting history reads, after this long, or sooner when the call's
// deadline, less syncDeadlineMargin, comes first. A cold Floppy write can
// deadline, less the deadline margin, comes first. A cold Floppy write can
// trigger a slow metadata fetch, and the host must receive the finished
// results before its RPC deadline.
syncBudget = 90 * time.Second
syncBudget = 90 * time.Second
// syncDeadlineMargin is the time kept free before the call's deadline. A
// call with less than four margins left keeps a quarter of its time
// instead: Silo sends a confirmed Jellyfin-compat stop with a five-second
// deadline, and a fixed margin would leave that stop no time to reach Floppy.
syncDeadlineMargin = 5 * time.Second
)

Expand Down Expand Up @@ -116,21 +120,29 @@ func (s *Server) ApplyEvents(ctx context.Context, req *pluginv1.WatchSyncApplyEv
func syncTimeBox(ctx context.Context) time.Duration {
budget := syncBudget
if deadline, ok := ctx.Deadline(); ok {
budget = min(budget, time.Until(deadline)-syncDeadlineMargin)
budget = min(budget, untilMargin(deadline))
}
return budget
}

// syncRequestLimit bounds every request of one call: the client's request
// timeout, cut to end syncDeadlineMargin before the call's deadline.
// timeout, cut to end the deadline margin before the call's deadline.
func syncRequestLimit(ctx context.Context) time.Duration {
limit := defaultRequestTimeout
if deadline, ok := ctx.Deadline(); ok {
limit = min(limit, max(time.Until(deadline)-syncDeadlineMargin, 0))
limit = min(limit, max(untilMargin(deadline), 0))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

kody code-review Kody Rules high

Short deadlines leave less than the required response reserve

For deadlines under 20 seconds, untilMargin reserves only a quarter of the remaining time, allowing ApplyEvents requests to exceed the required five-second reserve. Use syncDeadlineMargin to calculate the cutoff.

Also found in:

  • provider/provider_test.go:483-483
  • provider/provider.go:143-143
  • provider/provider_test.go:487-487
  • provider/ratings_test.go:907-907

Kody rule violation: Reserve response time before the ApplyEvents host deadline

Prompt for LLM
File provider/provider.go, line 133:

Short deadlines leave less than the required response reserve

Use the fixed five-second margin when calculating the ApplyEvents request cutoff. For deadlines less than 20 seconds away, untilMargin reserves only a quarter of the remaining time, allowing upstream requests to run past the required host-deadline-minus-five-seconds cutoff.

**Also found in:**
- `provider/provider_test.go:483-483`
- `provider/provider.go:143-143`
- `provider/provider_test.go:487-487`
- `provider/ratings_test.go:907-907`

Kody rule violation: [Reserve response time before the ApplyEvents host deadline](https://kodus.siloserver.org/settings/code-review/1324553393/kody-rules/1ab2c6d6-2601-4df9-bf6f-9e7e6ef0110d?teamId=ba9922fc-c0ea-4cf8-87bb-9d4f42ffc73e)

Suggested code:

limit = min(limit, max(time.Until(deadline)-syncDeadlineMargin, 0))

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

}
return limit
}

// untilMargin returns the time left before deadline, less the margin kept for
// returning results: syncDeadlineMargin, or a quarter of the time left when
// that is shorter. It is negative once the deadline has passed.
func untilMargin(deadline time.Time) time.Duration {
remaining := time.Until(deadline)
return remaining - min(syncDeadlineMargin, remaining/4)
}

func (s *Server) ListRemoteState(ctx context.Context, req *pluginv1.WatchSyncListRemoteStateRequest) (*pluginv1.WatchSyncListRemoteStateResponse, error) {
client, fault := s.authenticatedClient(req.GetContext())
if fault != nil {
Expand Down
63 changes: 63 additions & 0 deletions provider/provider_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,69 @@ func TestApplyRateLimitIsConnectionWide(t *testing.T) {
}
}

// Silo delivers a Jellyfin-compat client's Stopped report as a confirmed stop
// under a five-second deadline, and spends part of it before the call reaches
// the plugin. The stop must still reach Floppy, not be deferred untried on
// every retry.
func TestApplyEventsSendsAStopUnderAShortHostDeadline(t *testing.T) {
t.Parallel()
for _, deadline := range []time.Duration{4500 * time.Millisecond, 2 * time.Second} {
t.Run(deadline.String(), func(t *testing.T) {
t.Parallel()
var mu sync.Mutex
var stops []scrobblePayload
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost || r.URL.Path != "/api/v1/scrobble/" {
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
http.NotFound(w, r)
return
}
var payload scrobblePayload
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
t.Errorf("decode payload: %v", err)
}
mu.Lock()
stops = append(stops, payload)
mu.Unlock()
writeJSON(t, w, map[string]any{"status": "ok"})
}))
defer upstream.Close()

ctx, cancel := context.WithTimeout(context.Background(), deadline)
defer cancel()
response, err := NewServer(upstream.Client()).ApplyEvents(ctx, &pluginv1.WatchSyncApplyEventsRequest{
Context: authenticatedContext(upstream.URL),
Events: []*pluginv1.WatchSyncEvent{{
EventId: "stop-1",
Operation: pluginv1.WatchSyncOperation_WATCH_SYNC_OPERATION_SCROBBLE_STOP,
PositionSeconds: 780,
DurationSeconds: 3400,
Media: &pluginv1.WatchSyncMedia{
MediaType: pluginv1.WatchSyncMediaType_WATCH_SYNC_MEDIA_TYPE_EPISODE,
SeriesExternalIds: map[string]string{"tmdb": "1399"},
SeasonNumber: 1,
EpisodeNumber: 2,
},
}},
})
if err != nil {
t.Fatal(err)
}
mu.Lock()
defer mu.Unlock()
results := response.GetResults()
if response.GetFault() != nil || len(results) != 1 ||
results[0].GetStatus() != pluginv1.WatchSyncApplyStatus_WATCH_SYNC_APPLY_STATUS_APPLIED {
t.Fatalf("results = %v, fault = %v, Floppy requests = %d; want the stop applied",
results, response.GetFault(), len(stops))
}
if len(stops) != 1 || stops[0].Action != "stop" || stops[0].Completed == nil || *stops[0].Completed {
t.Fatalf("Floppy received %#v, want one incomplete stop", stops)
}
})
}
}

func providerConfig(baseURL string) *pluginv1.WatchSyncProviderConfig {
return &pluginv1.WatchSyncProviderConfig{Values: map[string]string{configBaseURL: baseURL}}
}
Expand Down
28 changes: 21 additions & 7 deletions provider/ratings_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -433,12 +433,12 @@ func TestListRatingsKeepsResolvedTitlesWhenTheDeadlineCutsARead(t *testing.T) {
}))
defer upstream.Close()

// Requests may run until half a second before the margin; the fixed clock
// keeps the time box from ending the page first.
// A 2-second deadline keeps a half-second margin, so requests may run for
// 1.5 seconds; the fixed clock keeps the time box from ending the page first.
server := NewServer(upstream.Client())
fixed := time.Date(2026, time.September, 23, 12, 0, 0, 0, time.UTC)
server.now = func() time.Time { return fixed }
ctx, cancel := context.WithTimeout(context.Background(), syncDeadlineMargin+500*time.Millisecond)
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
response, err := server.ListRemoteState(ctx, &pluginv1.WatchSyncListRemoteStateRequest{
Context: authenticatedContext(upstream.URL), StateKinds: ratingKinds,
Expand Down Expand Up @@ -902,7 +902,10 @@ func TestApplyEventsDefersEventsPastTheTimeBox(t *testing.T) {
{name: "budget", writeTakes: time.Minute, wantApplied: 2},
// A 30-second deadline leaves 25 seconds: events start at 0s and 20s.
{name: "call deadline", deadline: 30 * time.Second, writeTakes: 20 * time.Second, wantApplied: 2},
{name: "call deadline already too close", deadline: 3 * time.Second, writeTakes: time.Second},
// A 4-second deadline keeps a 1-second margin and leaves 3 seconds:
// events start at 0s, 1s, and 2s.
{name: "short call deadline", deadline: 4 * time.Second, writeTakes: time.Second, wantApplied: 3},
{name: "call deadline already passed", deadline: -time.Second, writeTakes: time.Second},
} {
t.Run(test.name, func(t *testing.T) {
t.Parallel()
Expand Down Expand Up @@ -930,7 +933,7 @@ func TestApplyEventsDefersEventsPastTheTimeBox(t *testing.T) {
return now
}
ctx := context.Background()
if test.deadline > 0 {
if test.deadline != 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, test.deadline)
defer cancel()
Expand Down Expand Up @@ -978,6 +981,11 @@ func TestSyncTimeBox(t *testing.T) {
if got := syncTimeBox(near); got > time.Minute-syncDeadlineMargin || got < time.Minute-syncDeadlineMargin-5*time.Second {
t.Fatalf("time box with a one-minute deadline = %s", got)
}
short, cancelShort := context.WithTimeout(context.Background(), 4*time.Second)
defer cancelShort()
if got := syncTimeBox(short); got > 3*time.Second || got < 2*time.Second {
t.Fatalf("time box with a 4s deadline = %s, want just under 3s", got)
}
}

// fakeRatingRow is one consumption in fakeRatingFloppy.
Expand Down Expand Up @@ -1315,9 +1323,15 @@ func TestSyncRequestLimitEndsBeforeTheHostDeadline(t *testing.T) {
if got := syncRequestLimit(near); got > 30*time.Second-syncDeadlineMargin || got < 20*time.Second {
t.Fatalf("limit with a 30s deadline = %s, want just under 25s", got)
}
past, cancelPast := context.WithTimeout(context.Background(), time.Second)
// A deadline shorter than four margins keeps a quarter of its time.
short, cancelShort := context.WithTimeout(context.Background(), 4*time.Second)
defer cancelShort()
if got := syncRequestLimit(short); got > 3*time.Second || got < 2*time.Second {
t.Fatalf("limit with a 4s deadline = %s, want just under 3s", got)
}
past, cancelPast := context.WithTimeout(context.Background(), -time.Second)
defer cancelPast()
if got := syncRequestLimit(past); got != 0 {
t.Fatalf("limit inside the margin = %s, want 0", got)
t.Fatalf("limit after the deadline = %s, want 0", got)
}
}