Media Primitives
miniproto handles chunked upload, messages.sendMedia, upload.getFile, CDN redirects and reupload tokens, AES-CTR CDN decryption, resumable destinations and progress callbacks. Rich-media wrappers, bound message helpers, albums, thumbnail generation and framework ergonomics belong in the planned mpgram layer.
Upload
Section titled “Upload”Use Client.send_file(peer, file, caption="...") for a standard upload. It uses 512 KiB parts by default, upload.saveFilePart for files up to 10 MiB and upload.saveBigFilePart for larger files, then sends messages.sendMedia with inputMediaUploadedDocument by default. quick_ack=True or quick_ack_callback=callback applies only to that final RPC. It does not request an acknowledgement for each upload part or replace the final Telegram result.
High-level uploads use two dedicated MTProto sender lanes by default. A reset on a media lane leaves unrelated requests on the main sender and other media lanes alone. media_lanes=0 uses the main sender; a positive value sets the number of media lanes independently of part concurrency. Low-level callers can use miniproto.media.upload_file() to get the generated InputFile or InputFileBig object.
For uploads, max_buffer_size checks that the requested part_size * concurrency fits. The producer queue and active sends both retain part payloads, and automatic part-size growth to meet max_file_parts can raise memory use beyond that value. Treat it as a concurrency-window check, not a process-memory cap.
Normalized Media objects for documents and photos expose media.file_id. The mpf1_ value is base64-encoded JSON containing reusable Telegram location fields, including the access hash and file reference. Treat it as sensitive reference data. Decoding does not check account permissions or refresh an expired file reference. Pushed Message.media may still be a raw TL object, so call media_from_raw() before reading .file_id. Passing a file ID to Client.send_file(peer, file_id, caption="...") sends inputMediaDocument or inputMediaPhoto and skips reuploading the bytes. Telegram represents videos, GIFs, audio, voice notes, stickers and ordinary files as document media with different DocumentAttribute values, so miniproto groups those under the document file-ID family and photos under photo. upload_file() enforces Telegram’s upload-part ceiling and can grow a caller-supplied small part_size up to the 512 KiB maximum to stay under max_file_parts. Client.send_file(..., upload_limit_parts="app_config") fetches the current help.getAppConfig value when you need the server’s current part limit.
Supported upload inputs are paths, bytes-like objects, seekable binary file objects, sync iterables of byte chunks and async iterables of byte chunks. Unknown-size sources are spooled to a temporary file before upload because Telegram’s big-file method requires the total part count. When max_file_parts is enabled, the spool rejects a chunk before writing beyond that count times the maximum 512 KiB part size. max_file_parts=None explicitly removes that bound. Immediate chunk producers periodically yield so cancellation can run. Owned spools close on setup failure, transfer failure or cancellation, while caller-owned readers stay open. Short reads are combined to fill each expected part. EOF before the measured size raises MediaUploadError, a successful result matches the bytes and parts accepted by Telegram. Keep seekable sources unchanged while the upload runs.
Download
Section titled “Download”Use Client.download_media(media, destination=None) for a standard download. It resolves public Media, miniproto file IDs, raw MessageMediaDocument, MessageMediaPhoto, Document, Photo or generated InputFileLocation objects into upload.getFile requests. With no destination, it returns bytes in MediaDownloadResult.data; a path destination writes to disk.
Public media operations require a connected client before creating lanes or scheduler registrations. Path destinations grow as downloaded chunks are written, declared sizes and limits do not preallocate disk space. Size metadata still controls requested coverage and progress, so applications should validate their own accepted download sizes.
With resume=True, the client appends to an existing path and starts at its current byte count. It drops and re-downloads any tail past the last 1 KiB boundary because Telegram cannot serve sub-1 KiB offsets. Resume trusts the aligned prefix by length. Make sure it belongs to the same remote file and verify it when integrity matters.
With no concurrency or ClientConfig.media_concurrency override, downloads use concurrency=6 pipelined requests across two warm sender lanes. They start with 512 KiB parts, can adapt up to 1 MiB and use an 8 MiB rolling in-flight byte window. media_lanes=0 uses the main sender. max_in_flight_bytes (or the legacy max_buffer_size alias) limits the requested-but-unyielded and reorder byte window. It does not cap total process memory. Plain-hash verification and CDN verification may assemble complete hash intervals outside this window; cache/read-ahead, transport and writer buffers, and in-memory results also need separate allowances.
The 8 MiB window applies to one transfer. All transfers from one client also share byte-weighted schedulers keyed by (target DC, direction). Download and upload traffic use separate budgets. Each request reserves bytes in 64 KiB units while its RPC runs; retry and flood sleeps keep the transfer’s local slot but release the shared permit. The defaults are 16 MiB for downloads and 8 MiB for uploads per DC, configured with ClientConfig.media_download_max_in_flight_bytes_per_dc and ClientConfig.media_upload_max_in_flight_bytes_per_dc. These values are separate from media_max_buffer_size and max_in_flight_bytes.
Schedulers use deficit round robin across transfers. Foreground requests get priority. After eight foreground grants, a scheduler tries a background queue head first; it grants that request only when its deficit, byte budget and operation limit fit. If the background head does not fit, the scheduler tries foreground work.
For downloads, the scheduler applies Telegram’s 20 MiB small/large same-DC operation classes. Explicit ClientConfig.media_download_small_queue_limit and media_download_large_queue_limit values take precedence. Otherwise, miniproto uses fallback limits of five small and two large transfers, then updates them when help.getAppConfig supplies small_queue_max_active_operations_count or large_queue_max_active_operations_count. Missing dynamic values do not set capacity to zero. FILE_MIGRATE_X moves the transfer registration and future permits to the target DC without changing the main session.
Client.iter_download(media, ...) exposes the same ordered engine as an async byte iterator. It accepts the range, precision, part-size, concurrency, lane, retry, cache, read-ahead, reference-refresh and integrity options from download_media(), but it has no destination and does not accept resume or bot multi_session. Resume a stream by setting offset. The iterator yields the first verified part before later requests finish. It holds out-of-order results until their predecessors arrive, and max_in_flight_bytes bounds requested but unyielded data and the reorder buffer. Verifier overfetch, cache/read-ahead, transport and destination memory use separate allowances.
Call await iterator.aclose() or use async with contextlib.aclosing(iterator): to close early and cancel and join iterator-owned part tasks. A bare break from async for does not close the iterator at that point. Closing the iterator does not cancel shared range-cache fetches. The cache owns those tasks and retains cached bytes until eviction or await cache.clear(), which cancels pending cache producers and clears entries. download_file() and download_media() use the same engine and a destination writer, so they share its range validation, migration, refresh, CDN, retry, ordering and integrity behavior.
Bot downloads can use auxiliary authorization keys with multi_session=True. Miniproto uses one session through 50 MiB, two through 250 MiB and four above 250 MiB. The option is off by default and applies only to complete, known-size bot downloads. For user accounts, resumed or ranged downloads, and unknown-size inputs, miniproto logs an error and uses one session. It creates auxiliary sessions only when the file size needs them. Each one issues one 1 MiB request at a time and does not poll or receive updates.
Auxiliary sessions keep their storage for later downloads and process restarts. Failure cleanup stops forwarding new aggregate progress callbacks, cancels and joins all workers, then waits for any assembly already running in a thread before removing temporary parts and disconnecting auxiliary clients. That assembly may finish writing the destination despite cancellation. Cleanup preserves the original failure or cancellation, disconnect errors are logged. Main-client shutdown also runs auxiliary cleanup. With EncryptedSQLiteSessionStorage("bot.sqlite", ...), sibling storage names are bot-download-1.sqlite through bot-download-3.sqlite. Pass the bot token through ClientConfig(..., bot_token=token) when a missing auxiliary session may need authorization after restart. A token passed to sign_in_bot(token) stays in memory only for that client lifetime. Built-in in-memory and encrypted SQLite storage support sibling sessions, custom storage without sibling support logs an error and uses one session.
Media-lane pools are keyed by operation kind and target DC. New pool targets must match a configured session DC option, including media-only endpoints, before a pool or idle reaper is allocated. Requesting a different lane count resizes the existing pool. Miniproto prewarms lanes in parallel at transfer start and closes lanes that sit idle for ClientConfig.media_idle_close seconds, 120 by default. Set it to None to keep them open, closed lanes reopen on the next transfer. Media stored on another DC uses a dedicated pool for that DC and an exported authorization (auth.exportAuthorization -> per-DC auth key -> auth.importAuthorization on the media connection). FILE_MIGRATE_X moves future media requests to the target DC without changing the main session.
Every emitted upload.getFile request satisfies Telegram’s alignment rules: without precise, offsets and limits are 4 KiB-aligned, limits divide 1 MiB and requests never straddle a 1 MiB boundary; miniproto switches individual transfers to precise mode automatically when 1 KiB granularity is needed (odd resume offsets or sub-4 KiB part sizes). part_size/max_part_size must be powers of two.
Concurrent downloads treat FLOOD_WAIT as a pacing signal. The flooded request sleeps while holding its window slot, so miniproto does not launch replacement work into that slot. Other active requests continue. Flood retries use a separate cap of 16 per part and do not consume max_retries. FLOOD_WAIT_0 sleeps for at least 1 second; each flood sleep adds at most 0.3 seconds of jitter.
Generic floods pause adaptive-window growth but do not shrink the window. After a cooldown, eight clean request completions increase the window by one. Disconnects and timeouts reduce it by one. FloodPremiumWait switches the adaptive window to one request for the rest of the transfer and prevents further window growth.
Launch pacing damps bursts. The first window uses a 50 ms stagger that decays by 0.8 to a 3 ms floor. After a generic flood, the pacer estimates a target launch rate from recent successful requests, with a floor of 1 request per second, then caps the added pacing interval at 250 ms. This interval describes the scheduler’s spacing, not achieved throughput. Pacing is skipped when the active window is one. launch_stagger=True by default; disabling it is an advanced benchmark control for paired comparisons. Large downloads also adapt part size by sampling throughput and trying larger chunks up to 1 MiB. Miniproto returns to the best observed size when a larger chunk slows the transfer. Set adaptive_part_size=False to keep chunk size fixed or adaptive_concurrency=False to keep the request window fixed.
For range-style workflows, pass range_cache=True or a DownloadRangeCache plus an optional read_ahead_bytes budget. Both high-level download APIs derive an automatic canonical file ID from the resolved document/photo location, including its type, ID, access hash, file reference and thumbnail. A supplied Media.file_id cannot name a different raw attachment’s cache entries. Size, filename, MIME metadata and alternate JSON spellings do not partition the same effective location. Legacy locations without a supported file-ID encoding have no automatic key. Raw download_file() callers can pass range_cache_key, they own its correspondence to the requested location.
Read-ahead is disabled for open-ended streams (limit=None) and ranges that reach or pass the known file end. Miniproto records media.download.read_ahead_disabled when it disables read-ahead. Background prefetch is capped at 32 tasks. Path-backed writes use a threaded writer on sequential and concurrent downloads. Each destination write() must accept the full payload, a short write raises MediaDownloadError. Known-size concurrent downloads require every requested byte range to be received and committed before success. An empty or short response before the target end raises MediaDownloadError. Failure or cancellation joins owned part and writer tasks before attempting to remove a path created by the call or restore a resumed path to its retained 1 KiB-aligned prefix. Secondary progress or write acknowledgement errors during unwind cannot skip cleanup or replace the original failure, and progress callbacks remain cancellable. Filesystem rollback failures are logged without replacing the original error or cancellation. Resume does not compare the retained prefix with the remote file, so verify that it belongs to the same file when integrity matters. Progress callbacks run at most once per 250 ms or 8 parts. The final callback runs only after complete coverage and destination flush.
The default download does not enable a range cache. range_cache=True or read-ahead without an explicit cache intentionally uses the process-shared cache. Its media/range keys do not distinguish accounts, sessions or Telegram environments, so a hit or pending fetch can reuse bytes without another account’s file request. Use this sharing only when all callers may access the same cached data.
For account/session isolation, create a separate DownloadRangeCache for each account/session and Telegram environment, then pass it explicitly to every cached or read-ahead download. Stop its consumers and call await cache.clear() before disconnecting its producing client or changing the cache’s account/session ownership. Clearing cancels and joins pending producers and drops entries. Cached payloads are not zeroized. The cache retains 32-byte SHA-256 key identities and evicts completed ranges by both max_bytes and max_entries, the latter defaults to 4,096. The byte budget measures payloads only, pending fetch counts still follow caller concurrency.
File-reference refresh is available through the low-level file_reference_refresher hook, and miniproto deduplicates concurrent refreshes for the same old reference. Client.download_media() installs a message-backed refresher when the source is a raw Message or a Media whose raw value is a raw Message. It refetches the message through messages.getMessages or channels.getMessages and retries with a renewed reference only when the concrete location type and every other TL location field still match the original. An edited attachment raises MediaDownloadError instead of replacing the requested file, even if its size matches. Multi-session assembly also checks each worker’s returned location identity.
Ordinary non-CDN downloads can opt into Telegram’s upload.getFileHashes verification with verify_plain_hashes=True; the default is off. Miniproto validates and caches hash metadata by file-location identity, fetches missing coverage through the same target-DC media context, then checks SHA-256 before yielding a part or writing it. Hash intervals may not match upload.getFile request boundaries, so miniproto assembles the bounded hash interval before comparing and trimming the requested overlap. Invalid intervals, gaps, contradictory overlaps, response loops, location changes and digest mismatches raise MediaIntegrityError with only the non-secret offset and length. CDN verification is mandatory; CDN integrity failures raise CdnIntegrityError. With plain verification off, miniproto sends no upload.getFileHashes requests.
Plain verification admits at most 4,096 entries in one hash response, including duplicates, and retains at most 65,536 distinct intervals per location identity. These are local resource policies, independent of Telegram limits and the plaintext cache. Exceeding either raises MediaIntegrityError. Metadata commits only after the bounded batch passes duplicate and overlap checks, retained contradiction history is not evicted. Ordered interval lookup avoids rescanning the full history for each hash.
When upload.getFile returns upload.fileCdnRedirect, miniproto keeps upload.getCdnFileHashes and upload.reuploadCdnFile on the authorized origin path. It creates a separate auth-key-only sender for the CDN datacenter and sends upload.getCdnFile through that sender. CDN senders use RSA keys from help.getCdnConfig; miniproto does not import user authorization into a CDN datacenter.
CDN data requests register the logical transfer with the shared download scheduler for the actual CDN DC, preserving its size class and priority. Each wire attempt reserves its requested bytes, including verifier overfetch, and releases the permit before retry or flood-wait sleep. Origin metadata and reupload requests keep their origin routing and permits.
CDN requests use stricter boundaries than precise origin-file requests. Miniproto over-fetches a legal 4 KiB-aligned range whose limit divides 1 MiB, decrypts it with the redirect IV prefix plus the requested block counter, verifies every complete Telegram-declared SHA-256 interval through origin metadata, then returns the requested slice. Miniproto does not accept a finite 1 KiB or 4 KiB range based on partial bytes alone. Live CDN authorization, routing and edge behavior require separate gated integration coverage.
Live Tests
Section titled “Live Tests”The opt-in live check is tests/integration/test_media_live.py. It requires MINIPROTO_INTEGRATION=1, MINIPROTO_REAL_INTEGRATION=1, MINIPROTO_API_ID, MINIPROTO_API_HASH, MINIPROTO_SESSION_KEY and an existing MINIPROTO_TEST_UPLOAD_FILE. It reuses an encrypted phone session when one exists; otherwise it also requires MINIPROTO_REAL_PHONE and login-code entry enabled by MINIPROTO_LIVE_PROMPT_CODE=1 in an interactive shell. If the account uses 2FA, provide MINIPROTO_REAL_PASSWORD or enter it interactively. MINIPROTO_TEST_DOWNLOAD_PATH is optional and defaults to .tmp/miniproto-live-download.bin. The test skips when external prerequisites are absent.
Interactive login codes and 2FA passwords use hidden terminal input. If hidden input is unavailable, the prompt raises rather than falling back to echoed input. Environment-provided passwords retain their exact whitespace. The benchmark’s HTTP form also masks code entry. Authorized POST bodies require one decimal Content-Length of at most 256 bytes, transfer encoding is rejected, and an absolute five-second read deadline is capped by the remaining prompt lifetime. Keep this transient prompt behind the access boundary described in the development guide.