Karan Adhikari commited on
Refactor adaptive chunk size and retry logic
Browse files- Backend/helper/custom_dl.py +88 -38
Backend/helper/custom_dl.py
CHANGED
|
@@ -23,20 +23,19 @@ def get_adaptive_chunk_size(client_index: int) -> int:
|
|
| 23 |
"""Return the best chunk size (bytes) for this client based on recent speed.
|
| 24 |
|
| 25 |
Speed tiers:
|
| 26 |
-
< 5 MB/s β
|
| 27 |
-
5-20 MB/s β
|
| 28 |
-
20-60 MB/s β
|
| 29 |
-
> 60 MB/s β
|
| 30 |
"""
|
| 31 |
speed = client_avg_mbps.get(client_index, 0.0)
|
| 32 |
if speed >= 60:
|
| 33 |
return 4 * 1024 * 1024
|
| 34 |
if speed >= 20:
|
| 35 |
return 2 * 1024 * 1024
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
return 512 * 1024
|
| 40 |
|
| 41 |
class ByteStreamer:
|
| 42 |
CHUNK_SIZE = 1024 * 1024 # 1 MB
|
|
@@ -115,6 +114,32 @@ class ByteStreamer:
|
|
| 115 |
self._file_id_cache[message_id] = file_id
|
| 116 |
return self._file_id_cache[message_id]
|
| 117 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
async def prefetch_stream(
|
| 119 |
self,
|
| 120 |
file_id: FileId,
|
|
@@ -162,31 +187,31 @@ class ByteStreamer:
|
|
| 162 |
|
| 163 |
media_session = await self._get_media_session(file_id)
|
| 164 |
location = await self._get_location(file_id)
|
|
|
|
| 165 |
|
| 166 |
async def fetch_chunk_with_retries(seq_idx: int, off: int) -> Tuple[int, Optional[bytes]]:
|
| 167 |
-
"""Fetch one chunk with timeout, exponential back-off, and
|
| 168 |
-
|
| 169 |
-
Retry schedule (max
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
|
|
|
| 175 |
"""
|
| 176 |
tries = 0
|
| 177 |
-
|
|
|
|
|
|
|
|
|
|
| 178 |
# --- choose which media session to use this attempt ---
|
| 179 |
use_session = media_session
|
| 180 |
use_client_idx = client_index
|
|
|
|
| 181 |
if tries >= 1 and len(multi_clients) > 1:
|
| 182 |
-
#
|
| 183 |
-
|
| 184 |
-
return work_loads.get(idx, 0) + 3 * client_failures.get(idx, 0)
|
| 185 |
-
fallback_idx = min(
|
| 186 |
-
(i for i in multi_clients if i != client_index),
|
| 187 |
-
key=_score,
|
| 188 |
-
default=None,
|
| 189 |
-
)
|
| 190 |
if fallback_idx is not None:
|
| 191 |
fb_streamer = ByteStreamer._instances.get(fallback_idx)
|
| 192 |
if fb_streamer is None:
|
|
@@ -195,10 +220,12 @@ class ByteStreamer:
|
|
| 195 |
use_session = await fb_streamer._get_media_session(file_id)
|
| 196 |
use_client_idx = fallback_idx
|
| 197 |
LOGGER.debug(
|
| 198 |
-
"Chunk fallback: seq=%s try=%s primary=%s β fallback=%s",
|
| 199 |
-
seq_idx, tries, client_index,
|
|
|
|
| 200 |
)
|
| 201 |
-
except Exception:
|
|
|
|
| 202 |
use_session = media_session # revert if fallback session fails
|
| 203 |
use_client_idx = client_index
|
| 204 |
|
|
@@ -210,38 +237,55 @@ class ByteStreamer:
|
|
| 210 |
location=location, offset=off, limit=chunk_size
|
| 211 |
)
|
| 212 |
),
|
| 213 |
-
timeout=
|
| 214 |
)
|
| 215 |
chunk_bytes = getattr(r, "bytes", None) if r else None
|
| 216 |
|
| 217 |
if chunk_bytes == b"":
|
|
|
|
| 218 |
return seq_idx, None
|
| 219 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
# If we succeeded via a fallback, mark primary as degraded
|
| 221 |
if use_client_idx != client_index:
|
| 222 |
client_failures[client_index] = client_failures.get(client_index, 0) + 1
|
|
|
|
|
|
|
|
|
|
| 223 |
return seq_idx, chunk_bytes
|
| 224 |
|
| 225 |
except asyncio.TimeoutError:
|
| 226 |
tries += 1
|
| 227 |
client_failures[use_client_idx] = client_failures.get(use_client_idx, 0) + 1
|
| 228 |
LOGGER.warning(
|
| 229 |
-
"Chunk timeout seq=%s off=%s try=%s client=%s",
|
| 230 |
-
seq_idx, off, tries, use_client_idx,
|
| 231 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
except Exception as e:
|
| 233 |
tries += 1
|
| 234 |
LOGGER.debug(
|
| 235 |
"Fetch chunk error seq=%s off=%s try=%s client=%s err=%s",
|
| 236 |
seq_idx, off, tries, use_client_idx, getattr(e, "args", e),
|
| 237 |
)
|
|
|
|
|
|
|
| 238 |
|
| 239 |
-
|
| 240 |
-
await asyncio.sleep(min(0.5 * (2 ** (tries - 1)), 10.0))
|
| 241 |
-
|
| 242 |
LOGGER.error(
|
| 243 |
-
"Failed to fetch chunk seq=%s off=%s after
|
| 244 |
-
seq_idx, off, client_index,
|
| 245 |
)
|
| 246 |
return seq_idx, None
|
| 247 |
|
|
@@ -293,8 +337,14 @@ class ByteStreamer:
|
|
| 293 |
scheduled_tasks.pop(completed_seq, None)
|
| 294 |
|
| 295 |
if chunk_bytes is None:
|
| 296 |
-
|
| 297 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 298 |
|
| 299 |
results_buffer[seq_idx] = chunk_bytes
|
| 300 |
|
|
|
|
| 23 |
"""Return the best chunk size (bytes) for this client based on recent speed.
|
| 24 |
|
| 25 |
Speed tiers:
|
| 26 |
+
< 5 MB/s β 1 MB (conservative, faster first-byte)
|
| 27 |
+
5-20 MB/s β 1 MB (default)
|
| 28 |
+
20-60 MB/s β 2 MB (fewer round-trips on fast sessions)
|
| 29 |
+
> 60 MB/s β 4 MB (maximise throughput on very fast sessions)
|
| 30 |
"""
|
| 31 |
speed = client_avg_mbps.get(client_index, 0.0)
|
| 32 |
if speed >= 60:
|
| 33 |
return 4 * 1024 * 1024
|
| 34 |
if speed >= 20:
|
| 35 |
return 2 * 1024 * 1024
|
| 36 |
+
# Default to 1MB (increased from 512KB to reduce round-trips)
|
| 37 |
+
return 1 * 1024 * 1024
|
| 38 |
+
|
|
|
|
| 39 |
|
| 40 |
class ByteStreamer:
|
| 41 |
CHUNK_SIZE = 1024 * 1024 # 1 MB
|
|
|
|
| 114 |
self._file_id_cache[message_id] = file_id
|
| 115 |
return self._file_id_cache[message_id]
|
| 116 |
|
| 117 |
+
def _get_best_fallback_client(self, client_index: int, target_dc: int) -> Optional[int]:
|
| 118 |
+
"""Select best fallback client: prefer DC-local, avoid high-failure clients."""
|
| 119 |
+
def _score(idx: int) -> int:
|
| 120 |
+
# Heavy penalty (1000Γ) for clients with 3+ failures
|
| 121 |
+
if client_failures.get(idx, 0) >= 3:
|
| 122 |
+
return 10000
|
| 123 |
+
# Penalize by failure count + workload
|
| 124 |
+
return (client_failures.get(idx, 0) * 50) + work_loads.get(idx, 0)
|
| 125 |
+
|
| 126 |
+
# Tier 1: DC-local clients (prefer same DC)
|
| 127 |
+
dc_local = [
|
| 128 |
+
idx for idx in multi_clients.keys()
|
| 129 |
+
if idx != client_index and client_dc_map.get(idx) == target_dc
|
| 130 |
+
]
|
| 131 |
+
if dc_local:
|
| 132 |
+
best = min(dc_local, key=_score)
|
| 133 |
+
return best if _score(best) < 5000 else None
|
| 134 |
+
|
| 135 |
+
# Tier 2: Any available client (excluding primary)
|
| 136 |
+
other_clients = [idx for idx in multi_clients.keys() if idx != client_index]
|
| 137 |
+
if other_clients:
|
| 138 |
+
best = min(other_clients, key=_score)
|
| 139 |
+
return best if _score(best) < 5000 else None
|
| 140 |
+
|
| 141 |
+
return None
|
| 142 |
+
|
| 143 |
async def prefetch_stream(
|
| 144 |
self,
|
| 145 |
file_id: FileId,
|
|
|
|
| 187 |
|
| 188 |
media_session = await self._get_media_session(file_id)
|
| 189 |
location = await self._get_location(file_id)
|
| 190 |
+
target_dc = file_id.dc_id
|
| 191 |
|
| 192 |
async def fetch_chunk_with_retries(seq_idx: int, off: int) -> Tuple[int, Optional[bytes]]:
|
| 193 |
+
"""Fetch one chunk with timeout, exponential back-off, and smart fallback.
|
| 194 |
+
|
| 195 |
+
Retry schedule (max 4 tries):
|
| 196 |
+
try 0 β primary client / session, 20 s timeout
|
| 197 |
+
try 1-2 β best fallback client (DC-local preferred), 20 s timeout
|
| 198 |
+
try 3 β any available fallback, 20 s timeout
|
| 199 |
+
|
| 200 |
+
Increments failure counter on timeout so select_best_client() deprioritizes
|
| 201 |
+
hammered clients.
|
| 202 |
"""
|
| 203 |
tries = 0
|
| 204 |
+
MAX_RETRIES = 4 # Increased from 3 to 4 for better resilience
|
| 205 |
+
TIMEOUT_SEC = 20.0 # Increased from 15s to 20s for cross-DC jitter
|
| 206 |
+
|
| 207 |
+
while tries < MAX_RETRIES and not stop_event.is_set():
|
| 208 |
# --- choose which media session to use this attempt ---
|
| 209 |
use_session = media_session
|
| 210 |
use_client_idx = client_index
|
| 211 |
+
|
| 212 |
if tries >= 1 and len(multi_clients) > 1:
|
| 213 |
+
# Smart fallback: pick best other client (DC-aware)
|
| 214 |
+
fallback_idx = self._get_best_fallback_client(client_index, target_dc)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 215 |
if fallback_idx is not None:
|
| 216 |
fb_streamer = ByteStreamer._instances.get(fallback_idx)
|
| 217 |
if fb_streamer is None:
|
|
|
|
| 220 |
use_session = await fb_streamer._get_media_session(file_id)
|
| 221 |
use_client_idx = fallback_idx
|
| 222 |
LOGGER.debug(
|
| 223 |
+
"Chunk fallback: seq=%s try=%s primary=%s (DC%s) β fallback=%s (DC%s)",
|
| 224 |
+
seq_idx, tries, client_index, client_dc_map.get(client_index, "?"),
|
| 225 |
+
fallback_idx, client_dc_map.get(fallback_idx, "?"),
|
| 226 |
)
|
| 227 |
+
except Exception as e:
|
| 228 |
+
LOGGER.debug(f"Fallback session creation failed: {e}, retrying with primary")
|
| 229 |
use_session = media_session # revert if fallback session fails
|
| 230 |
use_client_idx = client_index
|
| 231 |
|
|
|
|
| 237 |
location=location, offset=off, limit=chunk_size
|
| 238 |
)
|
| 239 |
),
|
| 240 |
+
timeout=TIMEOUT_SEC,
|
| 241 |
)
|
| 242 |
chunk_bytes = getattr(r, "bytes", None) if r else None
|
| 243 |
|
| 244 |
if chunk_bytes == b"":
|
| 245 |
+
# Empty chunk = EOF (legitimate)
|
| 246 |
return seq_idx, None
|
| 247 |
|
| 248 |
+
if chunk_bytes is None:
|
| 249 |
+
# None from server = real error, retry
|
| 250 |
+
tries += 1
|
| 251 |
+
LOGGER.debug(
|
| 252 |
+
"Chunk returned None seq=%s off=%s try=%s client=%s, retrying",
|
| 253 |
+
seq_idx, off, tries, use_client_idx,
|
| 254 |
+
)
|
| 255 |
+
continue
|
| 256 |
+
|
| 257 |
# If we succeeded via a fallback, mark primary as degraded
|
| 258 |
if use_client_idx != client_index:
|
| 259 |
client_failures[client_index] = client_failures.get(client_index, 0) + 1
|
| 260 |
+
LOGGER.debug("Primary client degraded (used fallback); failures=%s",
|
| 261 |
+
client_failures[client_index])
|
| 262 |
+
|
| 263 |
return seq_idx, chunk_bytes
|
| 264 |
|
| 265 |
except asyncio.TimeoutError:
|
| 266 |
tries += 1
|
| 267 |
client_failures[use_client_idx] = client_failures.get(use_client_idx, 0) + 1
|
| 268 |
LOGGER.warning(
|
| 269 |
+
"Chunk timeout seq=%s off=%s try=%s client=%s (failures=%s), retrying...",
|
| 270 |
+
seq_idx, off, tries, use_client_idx, client_failures[use_client_idx],
|
| 271 |
)
|
| 272 |
+
if tries < MAX_RETRIES:
|
| 273 |
+
# Exponential back-off: 0.5, 1, 2, 4 seconds (cap at 10)
|
| 274 |
+
await asyncio.sleep(min(0.5 * (2 ** (tries - 1)), 10.0))
|
| 275 |
+
|
| 276 |
except Exception as e:
|
| 277 |
tries += 1
|
| 278 |
LOGGER.debug(
|
| 279 |
"Fetch chunk error seq=%s off=%s try=%s client=%s err=%s",
|
| 280 |
seq_idx, off, tries, use_client_idx, getattr(e, "args", e),
|
| 281 |
)
|
| 282 |
+
if tries < MAX_RETRIES:
|
| 283 |
+
await asyncio.sleep(min(0.5 * (2 ** (tries - 1)), 10.0))
|
| 284 |
|
| 285 |
+
# All retries exhausted
|
|
|
|
|
|
|
| 286 |
LOGGER.error(
|
| 287 |
+
"Failed to fetch chunk seq=%s off=%s after %d retries, client=%s (failures=%s)",
|
| 288 |
+
seq_idx, off, MAX_RETRIES, client_index, client_failures.get(client_index, 0),
|
| 289 |
)
|
| 290 |
return seq_idx, None
|
| 291 |
|
|
|
|
| 337 |
scheduled_tasks.pop(completed_seq, None)
|
| 338 |
|
| 339 |
if chunk_bytes is None:
|
| 340 |
+
# Failed to fetch after all retries: terminate stream cleanly
|
| 341 |
+
LOGGER.error(
|
| 342 |
+
"Chunk permanently failed for stream=%s seq=%s. Terminating stream.",
|
| 343 |
+
stream_id, seq_idx
|
| 344 |
+
)
|
| 345 |
+
ACTIVE_STREAMS[stream_id]["status"] = "error"
|
| 346 |
+
await q.put((None, None))
|
| 347 |
+
return
|
| 348 |
|
| 349 |
results_buffer[seq_idx] = chunk_bytes
|
| 350 |
|