Skip to content

fix: derive staged build-context names from sha256, not salted hash() - #29

Open
rcbevans wants to merge 2 commits into
mainfrom
fix/stable-content-hash
Open

rcbevans wants to merge 2 commits into
mainfrom
fix/stable-content-hash

Conversation

@rcbevans

@rcbevans rcbevans commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Per-site verdicts on the reported defects

Claim 1 — hash() used where a content hash is required: PARTIALLY REAL.

There is exactly one call to the built-in hash() in the package, at src/containerspec/spec.py:503 (pre-fix):

dest_name = f"ctx_{hash(layer.src) & 0xFFFFFFFF:08x}_{src_path.name}"
  • Does the value escape the process? Yes. dest_name is substituted into the emitted Dockerfile (COPY ctx_<n>_<name> <dest>) and handed to the backend. hash() is PYTHONHASHSEED-salted for str, so two identical builds in two processes emit different Dockerfiles — the resulting image ID differs and Docker's layer cache misses.
  • But the headline framing is wrong. ImageSpec.content_hash() was already correct — spec.py:421 is hashlib.sha256 over _canonical_json (json.dumps(..., sort_keys=True)), and the payload never contained dest_name. containerspec's own cache keys, tags (sha-<16>), and sidecar metadata were stable all along. The damage was confined to the Dockerfile text and the Docker-side build cache.
  • No in-process __hash__ implementations were touched — there are none; layers are frozen dataclasses using the default.

Claim 2 — temp copy of the user's source tree leaked on every build: REAL, at spec.py:496. _prepare_build_context created tempfile.mkdtemp(prefix="containerspec-context-"), copied every Copy source into it (whole trees via copytree), and nothing ever removed it. build() had try/except around target.export but no finally.

Cited location rootfs.py:99-150 — NOT REAL. That is convert_oci_to_rootfs, which already wraps its mkdtemp in try/finally: shutil.rmtree(work_dir, ignore_errors=True) (rootfs.py:110, rootfs.py:155). Backend Dockerfile temp files (backends.py:51) are likewise already unlinked in finally by both callers. The leak was only in spec.py.

Bonus defect, found while proving the above — REAL: copying one source to two destinations crashed. Both Copy layers resolved to the same dest_name and the second shutil.copytree raised FileExistsError.

Red-green evidence

RED was re-run against the parent commit f1c4cce in a detached worktree with only tests/test_build_context.py added (git status showed exactly one untracked file; spec.py:503 still read hash(layer.src)). Output below is verbatim.

$ git worktree add --detach $SCRATCH/red HEAD~1 && cp tests/test_build_context.py $SCRATCH/red/tests/
$ cd $SCRATCH/red && uv run pytest tests/test_build_context.py -q
FFFFFFF..                                                                [100%]
7 failed, 2 passed in 0.44s

Defect 1 — salted hash() (RED)

Three seeds, three different Dockerfiles — the failure is the bug itself, not a collateral error:

E   AssertionError: staged Dockerfile varies across hash seeds: {
      '...COPY ctx_1d2d3540_app.py /app/app.py\n',
      '...COPY ctx_e16ad426_app.py /app/app.py\n',
      '...COPY ctx_0eb6cda8_app.py /app/app.py\n'}
    assert 3 == 1
tests/test_build_context.py:102: AssertionError

Corroborated independently at the interpreter: PYTHONHASHSEED=1/2/3 python -c "print(hash('./src') & 0xFFFFFFFF)" gives 1653447069 / 1684494079 / 3212230322.

Defect 2 — leaked source tree (RED)

All three cleanup tests fail by finding real residue — the extra item is an actual staged directory left behind:

E   AssertionError: assert {PosixPath('/...ctb8jo'), ...} == {PosixPath('/...tz0rg1'), ...}
      Extra items in the left set:
      PosixPath('/tmp/containerspec-context-ia4cjuhi')
tests/test_build_context.py:146: AssertionError        # success path

      Extra items in the left set:
      PosixPath('/tmp/containerspec-context-rnmqzm9c')
tests/test_build_context.py:164: AssertionError        # generic-exception path

      Extra items in the left set:
      PosixPath('/tmp/containerspec-context-392af5vg')
tests/test_build_context.py:187: AssertionError        # MissingToolError re-raise path

Across the pre-fix runs, 11 containerspec-context-* directories accumulated in /tmp, each holding a full copy of the test sources; they had to be deleted by hand.

Defect 3 — one source, two destinations (RED)

src/containerspec/spec.py:506: in _prepare_build_context
    shutil.copytree(src_path, ctx_dest)
E   FileExistsError: [Errno 17] File exists: '/tmp/containerspec-context-rstz0rg1/ctx_768d85c3_pkg'
tests/test_build_context.py:206

The 2 that pass pre-fix — stated honestly

test_distinct_sources_sharing_a_basename_stay_separate and test_trailing_separator_source_is_staged_and_rewritten pass at the parent commit. They are regression guards on the fix, not bug proofs: distinct sources already got distinct names within a single process. They are included because collapsing distinct sources onto one staged name is the most plausible way this fix could have been subtly wrong.

Two further tests fail pre-fix only with ImportError: cannot import name '_staged_name'. Those characterize the new helper (test_staged_name_stable_for_awkward_sources, test_staged_name_matches_sha256_of_source) and are not counted as proof of any defect — an import error proves nothing. The five genuine bug proofs above all fail on behavior.

GREEN (this branch)

$ uv run pytest tests/test_build_context.py -q
.........                                                                [100%]
9 passed in 0.64s

$ uv run ruff check .        -> All checks passed!
$ uv run ruff format --check -> 26 files already formatted
$ uv run pyright src         -> 0 errors, 0 warnings, 0 informations
$ uv run pytest -q           -> 307 passed, 19 skipped in 0.78s
$ ls -d /tmp/containerspec-context-* | wc -l   -> 0   (after the full suite)

The fix

New module-level helper _staged_name(src, *, basename) returning ctx_{sha256(src)[:8]}_{basename}; a staged: set[str] dedupes sources so one source serves several destinations; the staged context is removed in a finally in build().

Canonicalization decisions

  • Hash input is the src string exactly as written in the spec, UTF-8 encoded — the same string rewritten_dockerfile.replace(f"COPY {layer.src} ...") keys on. No path normalization, no resolve(): normalizing would make the staged name depend on host CWD and platform separator, reintroducing cross-machine instability in the very value being stabilized.
  • Sources that denote the same file but are written differently (src vs ./src, with vs without a trailing separator) get two staged copies — correct, just not maximally deduplicated. Covered by test_staged_name_stable_for_awkward_sources, which asserts no collisions across those forms.
  • Non-ASCII sources never reach a Dockerfile: validate_path's allowlist rejects them first. The helper is nonetheless tested directly against non-ASCII, whitespace and empty inputs so it cannot acquire a locale dependence.
  • No dict or set iteration feeds the digest; _canonical_json already pins ordering with sort_keys=True and package lists are tuple(sorted(...)) at construction.
  • Hex prefix width kept at 8 to match the previous name shape.

Compatibility / cache invalidation

Not a breaking change, and no containerspec cache is invalidated. content_hash() is byte-identical before and after — it never included staged names, and the golden-hash tests (tests/test_hash.py, tests/golden/*) pass unchanged. Tags, target.exists() cache keys and rootfs sidecars are unaffected.

Only user-visible effect: for specs using .copy(), the emitted COPY line changes once, so Docker's own layer cache misses once on the next build and the image ID changes. Before this PR that happened on every build, so this is strictly an improvement.

Versioning: fix: conventional commit, so release-please cuts a patch (0.1.7 to 0.1.8) and generates the CHANGELOG entry — no hand-edit of CHANGELOG.md, per the repo's release-please setup. The uv.lock hunk is an incidental lock refresh (it still recorded 0.1.5 against a 0.1.7 pyproject.toml).

Not addressed

Nothing further was found. The two other "verified bugs" the original review claimed appear to be the rootfs.py false positive above plus double-counting of the single hash() site.

`_prepare_build_context` named each staged source with the built-in
`hash()` of the source string. `hash()` is PYTHONHASHSEED-salted for
`str`, so two identical builds in two processes emitted different
`COPY ctx_<n>_<name>` lines and therefore produced different images and
missed Docker's own layer cache. Derive the discriminator from a sha256
prefix of the source string instead.

Also fixes two defects in the same function:

- The staged context — a full copy of the user's sources — was created
  with `mkdtemp` and never removed, leaking on every build. It is now
  removed in a `finally`, on the success and error paths alike.
- Copying one source to two destinations raised `FileExistsError` from
  `copytree`, because both COPY layers resolved to the same staged name.
  Sources are now staged once and referenced by both COPY lines.

`ImageSpec.content_hash()` is unaffected: it hashes the canonical spec
payload, which never contained staged names. Tags and cache keys are
unchanged; the golden hash tests confirm it.
Adds the awkward-source naming cases (non-ASCII, whitespace, empty,
trailing separator), a pin on the sha256 naming scheme, cleanup on the
MissingToolError/BuildError re-raise path, content assertions for a
source copied to two destinations, and distinct sources sharing a
basename.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant