Repository navigation
Conversation
`_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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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, atsrc/containerspec/spec.py:503(pre-fix):dest_nameis substituted into the emitted Dockerfile (COPY ctx_<n>_<name> <dest>) and handed to the backend.hash()is PYTHONHASHSEED-salted forstr, so two identical builds in two processes emit different Dockerfiles — the resulting image ID differs and Docker's layer cache misses.ImageSpec.content_hash()was already correct —spec.py:421ishashlib.sha256over_canonical_json(json.dumps(..., sort_keys=True)), and the payload never containeddest_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.__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_contextcreatedtempfile.mkdtemp(prefix="containerspec-context-"), copied everyCopysource into it (whole trees viacopytree), and nothing ever removed it.build()hadtry/exceptaroundtarget.exportbut nofinally.Cited location
rootfs.py:99-150— NOT REAL. That isconvert_oci_to_rootfs, which already wraps itsmkdtempintry/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 infinallyby both callers. The leak was only inspec.py.Bonus defect, found while proving the above — REAL: copying one source to two destinations crashed. Both
Copylayers resolved to the samedest_nameand the secondshutil.copytreeraisedFileExistsError.Red-green evidence
RED was re-run against the parent commit
f1c4ccein a detached worktree with onlytests/test_build_context.pyadded (git statusshowed exactly one untracked file;spec.py:503still readhash(layer.src)). Output below is verbatim.Defect 1 — salted
hash()(RED)Three seeds, three different Dockerfiles — the failure is the bug itself, not a collateral error:
Corroborated independently at the interpreter:
PYTHONHASHSEED=1/2/3 python -c "print(hash('./src') & 0xFFFFFFFF)"gives1653447069/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:
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)
The 2 that pass pre-fix — stated honestly
test_distinct_sources_sharing_a_basename_stay_separateandtest_trailing_separator_source_is_staged_and_rewrittenpass 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)
The fix
New module-level helper
_staged_name(src, *, basename)returningctx_{sha256(src)[:8]}_{basename}; astaged: set[str]dedupes sources so one source serves several destinations; the staged context is removed in afinallyinbuild().Canonicalization decisions
srcstring exactly as written in the spec, UTF-8 encoded — the same stringrewritten_dockerfile.replace(f"COPY {layer.src} ...")keys on. No path normalization, noresolve(): normalizing would make the staged name depend on host CWD and platform separator, reintroducing cross-machine instability in the very value being stabilized.srcvs./src, with vs without a trailing separator) get two staged copies — correct, just not maximally deduplicated. Covered bytest_staged_name_stable_for_awkward_sources, which asserts no collisions across those forms.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._canonical_jsonalready pins ordering withsort_keys=Trueand package lists aretuple(sorted(...))at construction.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 emittedCOPYline 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 ofCHANGELOG.md, per the repo's release-please setup. Theuv.lockhunk is an incidental lock refresh (it still recorded 0.1.5 against a 0.1.7pyproject.toml).Not addressed
Nothing further was found. The two other "verified bugs" the original review claimed appear to be the
rootfs.pyfalse positive above plus double-counting of the singlehash()site.