Bind a partial file to a strong validator and distinguish appendable 206 responses from replacement 200 responses.
An offset is not the identity of a file
A download stops after four bytes of a synthetic object. The client saves the prefix and later asks for the remaining bytes. Between those requests, the object changes. If the client appends the new suffix to the old prefix, it can create a file that never existed on the server. The byte count may be correct and the HTTP request may have succeeded, yet the assembled representation is invalid.
Safe resumption therefore needs two pieces of state: how much of the representation is present and which representation those bytes belong to. The offset answers the first question. A suitable validator answers the second. This is an evergreen HTTP mechanism with direct relevance to artifact downloaders, model-file installers and any worker that resumes large inputs after interruption. It does not depend on a model or an agent making the decision.
The worked fixture uses eight ASCII bytes so every result is visible. Version one is ABCDEFGH; version two is 12345678. A four-byte prefix from version one is ABCD. Appending bytes four through seven from version two produces ABCD5678, a corrupt hybrid. The experiment calculates this exact failure without downloading any real artifact or claiming a measured transfer speed.
Bind the partial copy to a strong validator
HTTP's If-Range condition lets a client request a range when the representation still matches its validator and otherwise receive the complete current representation. RFC 9110 specifies that a client must not send a weak entity tag in If-Range. A weak tag can express semantic equivalence without guaranteeing the byte-level identity needed to assemble a partial representation.
Store the validator with the partial data rather than in an unrelated cache entry. Also retain the selected representation's identity, including relevant negotiation settings. A range offset refers to bytes of that representation, so changing content encoding or another representation-selection input between requests can invalidate assumptions about what the offset means. A simple downloader can deliberately request one stable representation and reject unexpected changes.
The example accepts only strong entity tags and single open-ended byte ranges. HTTP also permits date validators under specific conditions, multipart ranges and other behaviors that this teaching client does not implement. A narrow supported subset is easier to verify than a client that accepts every response shape and hopes its append operation is appropriate.
Distinguish append, replace and refuse
A successful 206 response is a candidate for appending, but its Content-Range must begin exactly where the saved prefix ends. The total length and returned body length must agree with the requested completion. A 200 response is a complete replacement, even if the client sent Range. Servers may ignore range requests; the client must not interpret every successful response as a suffix.
This original function models the client decision for an eight-byte synthetic representation. It requires a matching strong validator on a partial response and rejects an inconsistent range. The tuple supplied as content_range represents a header already parsed by a strict transport adapter. A production parser must validate the actual header grammar before constructing that tuple.
# Author: Sandeep Belgavi. Original single-range response consumer.
def strong(tag):
return isinstance(tag, str) and tag.startswith('"') and tag.endswith('"')
def consume(prefix, saved_tag, status, body, response_tag, content_range=None):
if not isinstance(prefix, bytes) or not isinstance(body, bytes):
raise ValueError("byte inputs required")
if status == 200:
return {"action": "replace", "bytes": body, "tag": response_tag}
if status != 206:
raise ValueError("response needs separate recovery")
if not strong(saved_tag) or response_tag != saved_tag:
raise ValueError("partial representation identity mismatch")
if not isinstance(content_range, tuple) or len(content_range) != 3:
raise ValueError("missing parsed Content-Range")
start, end, total = content_range
if any(type(v) is not int for v in content_range):
raise ValueError("integer range bounds required")
if start != len(prefix) or end < start or end + 1 != total:
raise ValueError("range is not the requested remaining suffix")
if len(body) != end - start + 1:
raise ValueError("truncated range body")
return {"action": "append", "bytes": prefix + body, "tag": response_tag}
assert consume(b"ABCD", '"v1"', 206, b"EFGH", '"v1"', (4, 7, 8))["bytes"] == b"ABCDEFGH"
assert consume(b"ABCD", '"v1"', 200, b"12345678", '"v2"')["bytes"] == b"12345678"The strong helper is intentionally a fixture check rather than a complete entity-tag parser. Real transports should use a standards-aware parser and preserve tags as opaque values. Do not remove the weak prefix, lowercase an entity tag or otherwise normalize it into a match. A validator's apparent readability does not make it an application version number that the client may reinterpret.
Handle incomplete and exceptional responses explicitly
A 416 response does not automatically prove that the local file is complete. The object might have shrunk or changed. Use a separate reconciliation path to establish representation identity and expected length; do not mark success solely because the requested offset is outside the current range. A 404, authorization failure or transport interruption likewise belongs to a recovery state, not to the append path.
A connection can end after the response headers but before the advertised suffix arrives. Validate the received length before making the result the accepted complete artifact. Depending on the downloader design, a newly received partial suffix may itself be retained with carefully updated metadata, but the simple example refuses incomplete completion. It does not model a second interruption within the resumed transfer.
Final integrity verification is still useful. A trusted expected digest or signed manifest can establish whether the completed artifact is the intended one. An entity tag is opaque and is not generally a cryptographic digest. Correct range handling prevents one class of accidental hybrid, while integrity and authenticity checks address different concerns. Do not substitute a guessed hash interpretation for the server's documented contract.
Make persistence of partial state deliberate
Save partial bytes and their metadata so a crash cannot pair a new prefix with an old validator. One approach is to write a temporary data file and metadata record, then publish a consistent checkpoint through a small local protocol. The details depend on the filesystem and durability requirements. A plain JSON sidecar written independently from the data file is not automatically an atomic checkpoint.
Keep the partial file separate from the accepted artifact. Only promote it after the response checks and final integrity checks succeed. A consumer should not discover a half-assembled file under the same path used for verified inputs. The article's byte-array model avoids filesystem races deliberately; a real implementation needs tests around interruption during checkpoint and promotion as well as around HTTP responses.
If the client cannot establish a suitable validator, restarting from zero is often the clearest policy. That costs bandwidth but preserves a simple correctness argument. Supporting more aggressive resumption requires a documented representation contract, not an assumption that the resource usually stays unchanged. Make this tradeoff explicit in a downloader's result trace so operators understand why a resume was refused.
Test every response decision with exact bytes
The core fixtures are unchanged-version 206, changed-version 200 and a server that ignores Range with 200. The expected actions are append, replace and replace. Add mismatched validators, weak saved tags, wrong starting offsets, truncated bodies and 416. Assert the final byte string as well as the action label. A test that checks only the output length would miss the eight-byte hybrid entirely.
The interactive lab lets readers select the object version, prefix length, validator strength and server behavior. A deliberately unsafe append-all-successes mode exposes the corruption. The strict mode records why it appends, replaces or refuses. Reset restores the original fixture and export captures the controls, response and resulting bytes. These are deterministic protocol calculations, not live browser network measurements.
Integrate resumption beneath the agent boundary
An agent may decide which approved artifact is useful, but the downloader should own resumption. Expose structured results such as resumed, restarted, rejected-response and integrity-failed. Do not ask the model to inspect raw headers and decide whether concatenating files is safe. The transport layer has the byte counts and validators needed to make that decision consistently.
For small inputs or unreliable validators, a complete redownload may be preferable. For large artifacts, a carefully constrained range protocol can save repeated transfer without compromising representation identity. The governing invariant stays the same in either case: every byte in the accepted artifact must belong to one verified representation, and a successful HTTP status alone is not sufficient evidence of that invariant.
Interactive experiment
HTTP range resume: validators, partial bytes and replacement responses. Change object versions, validator strength and server responses; inspect append, replace and refusal decisions.
Run the example yourself
The synthetic fixtures, expected output and tests behind this guide are in the companion code on GitHub; its README lists the prerequisites, exact commands, expected output and limits.