kolibri icon indicating copy to clipboard operation
kolibri copied to clipboard

Failed content download requests are retried indefinitely, risking server overload after channel upgrades

Open AlexVelezLl opened this issue 7 months ago • 4 comments

❌ This issue is not open for contribution. Visit Contributing guidelines to learn about the contributing process and how to find suitable issues.

Target branch: develop

Observed behavior

When a ContentDownloadRequest fails, it is saved with ContentRequestStatus.Failed. However, INCOMPLETE_STATUSES (defined in content_request.py) includes Failed, so incomplete_downloads_queryset() (line 445) re-queues every failed request on the next sync — indefinitely.

This affects two code paths:

  1. Content download failures — process_download_request (line 1037): exceptions (e.g. NoPeerAvailable, resource 404) set status = Failed and return, but the request will be picked up again on every subsequent content processing cycle.

  2. Metadata import failures — _import_metadata (line 752): when fetching metadata for a node returns a 4xx (e.g. the node no longer exists on the peer), a warning is logged but no failure state is recorded. The request remains Pending/Failed and is re-attempted every sync.

This is particularly acute following channel upgrades (introduced in #14619): after an upgrade, contentnodes from prior channel versions may no longer exist, leaving behind permanently unresolvable download requests that will never succeed.

Errors and logs

No crash — the symptom manifests as repeated log warnings on every sync cycle:

WARNING Failed to import content metadata for <contentnode_id>
WARNING Unable to import <contentnode_id> from peers

The number of these warnings grows over time as stale requests accumulate.

Expected behavior

The system should distinguish between transient failures (e.g. network timeout — worth retrying) and permanent failures (e.g. contentnode no longer exists in the channel — should not be retried). Permanently failed requests should reach a terminal state and be excluded from future processing cycles.

Similarly, when metadata import fails repeatedly for a contentnode (e.g. because the node is not found on any peer), the corresponding content request should eventually be marked as permanently failed rather than re-attempted forever.

User-facing consequences

  • Server overload risk: every sync retries all failed requests, including those for resources that will never be available. This scales poorly as stale requests accumulate.
  • Amplified by channel upgrades: PR #14619 introduced channel upgrade support. After a channel upgrade, contentnodes from prior versions may be removed, leaving unresolvable download requests that are retried on every sync.
  • Low-resource environments: Kolibri is designed for low-bandwidth environments. Futile network requests from stale content requests consume bandwidth and processing capacity on both the device and the server.

Steps to reproduce

  1. Create a ContentDownloadRequest for a specific contentnode.
  2. Perform a channel upgrade that removes that contentnode (or simulate by making the node unreachable on all peers).
  3. Trigger a content processing cycle (e.g. via sync or process_content_requests()).
  4. Observe that the failed request appears in incomplete_downloads_queryset() and is retried on every subsequent cycle.

Context

  • Introduced / amplified by: #14619 — Channel upgrade support
  • Relevant file: kolibri/core/content/utils/content_request.py
    • INCOMPLETE_STATUSES (line 61–64): includes Failed, causing re-queuing
    • incomplete_downloads_queryset() (line 445): selects all incomplete including failed
    • process_download_request() (line 1037): sets Failed on exception but no retry limit
    • _import_metadata() (line 752): logs warning on 4xx but does not record failure state

Open Questions

These are options to consider — decisions needed from the team before implementation:

  1. Retry counter: Add a retry_count field to ContentRequest. Enforce a maximum (e.g. 3–5 retries). After the limit, mark the request as permanently failed and exclude it from INCOMPLETE_STATUSES.

  2. Error reason field: Add an error_reason field to store why a request failed (e.g. "node_not_found", "no_peer", "metadata_404"). Use this to decide whether to retry at all.

  3. Error-specific retry policy: Only retry for recoverable error types (network timeout, peer unavailable) and immediately mark others as permanently failed (node not found, 4xx from metadata endpoint).

  4. Channel-upgrade–aware cleanup: When a channel upgrade removes a contentnode, proactively mark any pending or failed download requests for that node as permanently failed instead of letting them accumulate.

  5. Combination: A retry counter with an error-reason field gives both a safety cap and the ability to fast-fail known-permanent errors.

Acceptance Criteria

  • [ ] Failed content download requests for contentnodes that no longer exist do not retry indefinitely — they reach a terminal state
  • [ ] Failed metadata import requests track failure state; repeated failures for the same contentnode eventually result in that content request being permanently excluded from processing
  • [ ] The system distinguishes between transient failures (retryable) and permanent failures (non-retryable), and does not re-queue the latter
  • [ ] Server load from failed content requests does not grow unboundedly as stale requests accumulate across syncs
  • [ ] A regression test covers the scenario where a content request for a non-existent contentnode does not get retried after reaching a terminal failure state

AI usage

This issue was drafted with Claude Code assistance from session context and code review. The problem description, code locations, and acceptance criteria were verified against the actual source in kolibri/core/content/utils/content_request.py. The possible approaches were reviewed and edited for accuracy.

AlexVelezLl avatar Apr 29 '26 19:04 AlexVelezLl

@rtibbles one decision changes the design. Findings in kolibri/core/content/utils/content_request.py:

  • Nodes removed by a channel upgrade never reach process_download_request: the local ContentNode is gone, so the request stays Pending in the metadata-import path and gets a 4xx from every peer, preferred then fallback.
  • That path runs during the sync itself (kolibri/core/content/kolibri_plugin.py:77), then again on every sync completion and peer connect, so cost is stale requests × peers per event.
  • A single 4xx or NoPeerAvailable doesn't prove the node is gone: the peer may hold an older channel version or a partial import, and may import the node later.
  • A terminal row is never revived: create_content_download_requests uses get_or_create, which returns the existing row unchanged. Only an assignment with a new channel_version makes a fresh row.

Should failed requests back off (failure count plus last-attempt time, retried at growing intervals, never fully stopped), or reach a true terminal state that only a changed assignment can clear? I lean to backoff, since it needs no permanence rule, but it would replace the "terminal state" acceptance criterion.

rtibblesbot avatar Oct 21 '26 23:10 rtibblesbot

Backoff is fine. I think after the sync process has run and these backoffs have happened we should also verify that the failed requests are still valid?

rtibbles avatar Oct 22 '26 00:10 rtibbles

Plan, per the backoff decision:

Backoff

  • Add failure_count and last_failed_at to ContentRequest (migration).
  • Both failure paths increment them: a metadata 4xx from every peer tried in _import_metadata, and any Failed set in process_download_request.
  • incomplete_downloads_queryset() skips requests whose last_failed_at + interval(failure_count) is in the future; interval doubles from 1 hour, capped at 7 days.
  • Same filter applies to the in-sync metadata import (kolibri_plugin.py:77) and enqueue_automatic_resource_import_if_needed, so fully backed-off devices queue nothing.
  • Success resets failure_count. Requests never stop retrying entirely.

Validity check, at the end of process_content_requests

  • A failed sync-initiated request is valid only if a current downloadable assignment matches its source_model, source_id, contentnode_id and channel_version.
  • Today nothing removes rows for an active lesson/quiz that dropped a node, or whose channel_version moved on (the new version gets a new row; the old one stays) — those are the stale rows a channel upgrade leaves.
  • Invalid ones are deleted. User-initiated requests are left alone.

Acceptance criteria changes

  • "Terminal state" becomes: backed off at growing intervals, and deleted once no assignment references it.
  • Regression tests: a 4xx'd request is skipped until its interval passes; a request whose assignment no longer references the node is deleted.

rtibblesbot avatar Oct 22 '26 02:10 rtibblesbot

Plan: Failed ContentDownloadRequests are retried at growing intervals instead of on every cycle, and failed sync-initiated requests no assignment still references are deleted.

  • [ ] Backoff fields and due filter
  • [ ] Record failures and reset on success
  • [ ] Delete failed requests no assignment references
  • [ ] Self-review the produced code

Assumptions — the issue did not settle these; say so if one is wrong.

  • retry_after replaces the posted last_failed_at; if the timestamp is wanted, compute the due filter in SQL per count.
  • No peer reachable records no failure; if offline attempts should count, offline learner devices wait up to 7 days after reconnecting.
  • Metadata failure on a request whose node already exists does not back off; if it should, that request stops downloading the old version.
  • Metadata-path failures leave status unchanged; if Failed is wanted, learners see user downloads marked failed in the UI.
  • Interval constants are module constants, not OPTIONS; if configurable, add them to kolibri/utils/options.py.
  • A user re-requesting a backed-off download does not reset it; if it should, ContentDownloadRequestSerializer.create resets the fields.
  • Stale rows are deleted only after one failure, so an assignment change costs one more attempt; if not acceptable, also run the check in synchronize_content_requests.

Written by rtibblesbot, an LLM-based coding agent.

rtibblesbot avatar Oct 22 '26 02:10 rtibblesbot