Skip to content

Bytecode compiled during build is always discarded at runtime: SAM packaging writes 1980 timestamps, so timestamp-based .pyc never validate #924

Description

@tomaDev

Describe the bug

.pyc files produced during a build use timestamp-based invalidation by default: each one records
the source file's mtime and size, and CPython recompiles the module if either differs at import
time.

SAM CLI writes Lambda ZIPs with no timestamps at all, so every source file arrives in /var/task
dated 1980-01-01 and no timestamp-based .pyc can ever validate. The bytecode is shipped, read,
rejected, and recompiled on every cold start. Because /var/task is read-only, the recompiled
result cannot be cached either, so the cost is paid again by every execution environment.

This means any bytecode compilation added to a builder — see #839, and the compile_bytecode
field in the python_uv workflow — produces artifacts that are strictly worse than not compiling:
larger package, identical cold start.

Why the timestamps are zero

samcli/lib/package/utils.py, make_zip_with_permissions() constructs each entry as a bare
zipfile.ZipInfo(relative_path) and deliberately does not set date_time:

info = zipfile.ZipInfo(relative_path)
...
# ZIP date time can be set to the last time the zip content was modified using this logic.
# info.date_time = time.localtime()[0:6]

# If the date time above is added, the caching logic that compares ZIP files sha will break.
# Currently we skip executing sync flows for sam sync command when the logic ZIP hash is
# the same as the remote lambda ZIP hash. A timestamp will make the evaluation always false.
# However, without this field, contents of the zip file will have a last modified date 1980
# because python's zipfile.ZipInfo is set to: https://docs.python.org/3/library/zipfile.html.
zf.writestr(info, file_bytes, compress_type=compression_type)

Both make_zip and make_zip_with_lambda_permissions are functools.partial wrappers with
non-empty permission_mappers, so this branch always runs for Lambda artifacts.

The omission is intentional and load-bearing for sam sync hash comparison, so the fix belongs on
the builder side, not in the packaging code.

Steps to reproduce

import zipfile, io
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf:
    info = zipfile.ZipInfo("mod.py")   # exactly what samcli does
    info.create_system = 3
    zf.writestr(info, b"x = 1")
with zipfile.ZipFile(buf) as zf:
    print(zf.getinfo("mod.py").date_time)

Observed: (1980, 1, 1, 0, 0, 0)

End to end, against a real build artifact containing 718 uv-compiled .pyc (produced with
UV_COMPILE_BYTECODE=1 sam build), comparing each .pyc header's recorded source mtime and size
against the source file on disk, before and after a ZIP round trip:

as built (on disk)           valid=718  STALE=0
after zip round-trip         valid=0    STALE=718

Note that ZIP timestamps could not fix this even if they were written: the format stores DOS
date/time at 2-second resolution, while .pyc records the source mtime as whole seconds, so
roughly half of all files would still mismatch.

Expected result

Builders that compile bytecode should use hash-based, unchecked invalidation, which records a hash
of the source instead of its mtime and does not consult the source file at import time:

python -m compileall --invalidation-mode unchecked-hash <artifact dir>

or, for uv, whatever equivalent it grows. Verified on the same artifact:

compileall -f --invalidation-mode unchecked-hash, then zip round-trip:
  .py files:            977
  unchecked-hash .pyc:  977
  timestamp .pyc:         0
  zip size:            17.2 MB (unchanged)

-f matters if uv has already compiled part of the tree: plain compileall skips any file that
already has a .pyc, so it leaves uv's timestamp-based ones in place and fixes only the rest.

Why this is worth doing

On a FastAPI function with 977 .py files in the artifact, measured with the same module graph
(899 modules) and the only difference being whether __pycache__ was present:

with .pyc:      293 / 297 / 298 / 299 / 302 ms
without .pyc:   822 / 878 / 887 ms

Compilation is roughly 65% of import time. On the deployed function the import graph accounts for
2081 ms of a 2145 ms init, so shipping valid bytecode is worth several hundred milliseconds per
cold start, on a code path where SnapStart and provisioned concurrency are the only alternatives
and both cost money.

Versions

  • aws-lambda-builders 1.67.0
  • SAM CLI 1.166.2
  • Host Python 3.14.3, target runtime python3.14, architecture arm64

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions