Make Python Gzip Artifacts Reproducible with Fixed Headers

A build compresses the same asset manifest twice, but its checksum changes. Before investigating the manifest generator, check the gzip wrapper: metadata can differ even when decompression produces identical bytes. This creates unnecessary uploads when a deployment tool uses compressed-file hashes to detect changes.

These examples use Python 3.10 or later and the standard library. They target repeatable output within a pinned Python and compression-library environment. The input is an already prepared byte sequence; JSON serialization and source-file ordering belong to the preceding build step.

Reproduce a Metadata-Only Difference

Run this standalone example. Explicit timestamps make the demonstration reliable without waiting between writes:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import gzip
import io


def pack_at(payload, timestamp):
    buffer = io.BytesIO()
    with gzip.GzipFile(
        fileobj=buffer, filename="", mode="wb", mtime=timestamp,
        compresslevel=6,
    ) as archive:
        archive.write(payload)
    return buffer.getvalue()


payload = b'{"version":1}\n'
first = pack_at(payload, 1)
second = pack_at(payload, 2)
print(first == second)
print(gzip.decompress(first) == gzip.decompress(second) == payload)
# False
# True

The changed bytes do not indicate changed manifest content. Comparing only the decompressed result would miss the reason a compressed-artifact cache keeps invalidating.

Fix the Timestamp and Omit the Filename

Save this helper as stable_gzip.py:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import gzip
import io


def gzip_bytes(payload):
    if not isinstance(payload, bytes):
        raise TypeError("payload must be bytes")
    buffer = io.BytesIO()
    with gzip.GzipFile(
        fileobj=buffer,
        filename="",
        mode="wb",
        mtime=0,
        compresslevel=6,
    ) as archive:
        archive.write(payload)
    return buffer.getvalue()

The Python GzipFile reference documents both header inputs: an omitted modification time uses the current time, and a file object’s name can supply an original filename. Setting mtime=0 fixes the timestamp; filename="" omits the filename. An explicit compression level also makes the build’s choice visible.

Read the buffer after the context exits, so the gzip stream has its trailer. Closing GzipFile leaves the supplied buffer open. The helper requires bytes to keep text encoding outside the compression step.

Separate the Artifact Name from Its Contents

Save this demonstration beside the helper and run it in a scratch directory:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import gzip
from pathlib import Path
from stable_gzip import gzip_bytes

payload = b'{"version":1}\n'
first = Path("manifest-build-a.json.gz")
second = Path("manifest-build-b.json.gz")
first.write_bytes(gzip_bytes(payload))
second.write_bytes(gzip_bytes(payload))

print(first.read_bytes() == second.read_bytes())
print(gzip.decompress(first.read_bytes()) == payload)
# True
# True

The destination paths describe where the artifacts are stored. They never reach the gzip writer, so renaming an output cannot change its embedded metadata. This example overwrites those two demonstration files; choose fresh paths when trying it with other assets.

For large assets, use a streaming writer with the same explicit header settings rather than collecting both source and compressed bytes in memory. Keep source reading, gzip writing, and output closing in a defined order. Writing directly to a final destination can leave a partial artifact after an error; staging and publication are separate concerns.

Test Equality and the Round Trip

Save this as test_stable_gzip.py beside the helper and run python test_stable_gzip.py:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import gzip
from stable_gzip import gzip_bytes

for payload in [b"", b"x", bytes(range(256)), b"record\n" * 10000]:
    first = gzip_bytes(payload)
    second = gzip_bytes(payload)
    assert first == second
    assert gzip.decompress(first) == payload
    assert first[4:8] == b"\x00" * 4  # Gzip MTIME field
    assert not first[3] & 0x08  # No FNAME flag

for value in [None, "text", bytearray(b"text")]:
    try:
        gzip_bytes(value)
    except TypeError:
        pass
    else:
        raise AssertionError("non-bytes input accepted")

print("Reproducible gzip checks passed.")

Equality catches variation, while decompression checks that the artifact still represents the intended payload. The header assertions identify the two metadata rules directly. The samples cover an empty stream, binary data, and repetitive content without depending on one exact compressed byte string.

Define the Reproducibility Boundary

Fixed headers do not promise identical compressed bytes across Python or zlib upgrades. Pin the build environment when compressed hashes form part of a release contract, and review artifact changes when upgrading it. The gzip.compress version notes also describe a header OS-byte difference in Python 3.11 and 3.12 when mtime=0 delegates to zlib; API and runtime choices matter.

Make the uncompressed input stable first: choose a text encoding, a newline convention, and a serialization order before compression. If two payloads already differ, changing gzip metadata cannot make their artifacts equivalent. When a checksum changes, compare the input bytes, header policy, compression settings, and environment in that order.