The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(build): handle large release uploads and trim packaging waste
ethernet9a42d60f2534
diff --git a/.github/actions/setup-pm/action.yml b/.github/actions/setup-pm/action.ymlindex 3c14042db2f..9fcc17c7c22 100644--- a/.github/actions/setup-pm/action.yml+++ b/.github/actions/setup-pm/action.yml@@ -22,6 +22,9 @@ inputs:cache-node:description: Cache npm downloads; never cache node_modules.default: 'true'+ save-node-cache:+ description: Save automatically on success. Set false to save a consumer-scoped rolling snapshot with actions/cache/save after npm preparation.+ default: 'true'python-cache-dependency-glob:description: Dependency files that invalidate the uv cache.default: |@@ -72,7 +75,13 @@ outputs:value: ${{ steps.install.outputs.uv-cache-path }}node-cache-hit:description: Exact npm dependency cache hit.- value: ${{ steps.node-cache.outputs.cache-hit }}+ value: ${{ steps.node-cache.outputs.cache-hit || steps.node-cache-restore.outputs.cache-hit }}+ node-cache-key:+ description: Rolling snapshot key when save-node-cache is false.+ value: ${{ steps.node-cache-restore.outputs.cache-primary-key }}+ npm-cache-path:+ description: npm download cache directory for an explicit consumer save.+ value: ${{ steps.install.outputs.npm-cache-path }}runs:using: compositesteps:@@ -163,12 +172,22 @@ runs:- name: Cache npm dependency downloadsid: node-cache- if: inputs.toolchain != 'python' && inputs.cache-node == 'true'+ if: inputs.toolchain != 'python' && inputs.cache-node == 'true' && inputs.save-node-cache == 'true'uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0with:path: ${{ steps.install.outputs.npm-cache-path }}key: node-cache-${{ runner.os }}-${{ steps.prepare.outputs.arch }}-npm-${{ hashFiles(inputs.node-cache-dependency-path) }}${{ inputs.cache-suffix != '' && format('-{0}', inputs.cache-suffix) || '' }}+ - name: Restore npm dependencies for an explicit save+ id: node-cache-restore+ if: inputs.toolchain != 'python' && inputs.cache-node == 'true' && inputs.save-node-cache == 'false'+ uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0+ with:+ path: ${{ steps.install.outputs.npm-cache-path }}+ # Scope producers so tool-only jobs cannot replace a full desktop cache.+ key: setup-pm-npm-v1-${{ inputs.cache-suffix || 'production' }}-${{ steps.prepare.outputs.target }}-${{ steps.prepare.outputs.npm-version }}-${{ hashFiles(inputs.node-cache-dependency-path) }}-${{ github.job }}-${{ github.run_id }}-${{ github.run_attempt }}+ restore-keys: setup-pm-npm-v1-${{ inputs.cache-suffix || 'production' }}-${{ steps.prepare.outputs.target }}-${{ steps.prepare.outputs.npm-version }}-${{ hashFiles(inputs.node-cache-dependency-path) }}-${{ github.job }}-+- name: Install the requested Python extras through PMid: dependenciesif: inputs.extras != ''diff --git a/.github/workflows/desktop-bundled-release.yml b/.github/workflows/desktop-bundled-release.ymlindex c1148a80540..ba76570d790 100644--- a/.github/workflows/desktop-bundled-release.yml+++ b/.github/workflows/desktop-bundled-release.yml@@ -323,6 +323,7 @@ jobs:# The payload tools cache does not include uv's built wheels.cache-python: truesave-python-cache: false+ save-node-cache: false- name: Resolve toolchain cache keyid: toolchain@@ -435,6 +436,12 @@ jobs:tests-js/node_moduleskey: ${{ steps.node-modules-cache.outputs.cache-primary-key }}+ - name: Save warmed npm downloads+ uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0+ with:+ path: ${{ steps.pm.outputs.npm-cache-path }}+ key: ${{ steps.pm.outputs.node-cache-key }}+- name: Azure login (OIDC)if: vars.AZURE_CLIENT_ID != ''uses: azure/login@f5d393ae46f8fde4be8b75f32e3fc50e654ad0ca # v3.0.1@@ -606,6 +613,7 @@ jobs:# The payload tools cache does not include uv's built wheels.cache-python: truesave-python-cache: false+ save-node-cache: false- name: Resolve toolchain cache keyid: toolchain@@ -699,6 +707,12 @@ jobs:tests-js/node_moduleskey: ${{ steps.node-modules-cache.outputs.cache-primary-key }}+ - name: Save warmed npm downloads+ uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0+ with:+ path: ${{ steps.pm.outputs.npm-cache-path }}+ key: ${{ steps.pm.outputs.node-cache-key }}+# Commit artifacts are downloadable too. Require signing for them,# candidates, and published tags before building any payload.- name: Require signing credentials when publishing@@ -1371,9 +1385,8 @@ jobs:env:GITHUB_TOKEN: ${{ github.token }}GITHUB_REPOSITORY_OWNER: ${{ github.repository_owner }}- # Content-addressed off the pm lock digest: builds once per lock- # bump, then no-ops. The wheelhouse container phase boots this- # instead of the bare base, skipping the ~10-min toolchain apt.+ # The pinned base and Dockerfile select the pre-baked toolchain.+ # Recipe changes must not reuse an image built without those tools.run: |mkdir -p termux-build# The builder script prints progress (build logs, smoke output)@@ -1385,10 +1398,8 @@ jobs:echo "image=$img" >> "$GITHUB_OUTPUT"- name: Restore the wheelhouse- # The manufactured native wheels are the expensive artifact of this- # job. build_wheels.py skips any dist whose exact-pinned wheel is- # already present, so a restored wheelhouse turns the 20-minute- # native compile phase into a cache-hit verification.+ # Reuse manufactured wheels only when the complete input identity+ # and wheel hashes pass admission. A prefix hit alone is not proof.uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0with:path: |diff --git a/apps/desktop/electron-builder.config.cjs b/apps/desktop/electron-builder.config.cjsindex 8dc8b7dbde4..8412c71421f 100644--- a/apps/desktop/electron-builder.config.cjs+++ b/apps/desktop/electron-builder.config.cjs@@ -169,6 +169,8 @@ module.exports = {})},dmg: {+ // Avoid the failing optional APFS shrink pass; keep compressed conversion.+ shrink: false,title: `Install ${displayName}`,backgroundColor: '#f5f5f7',iconSize: 96,diff --git a/apps/desktop/scripts/batch-sign-binaries.mjs b/apps/desktop/scripts/batch-sign-binaries.mjsindex c1fca17593f..8fab64af992 100644--- a/apps/desktop/scripts/batch-sign-binaries.mjs+++ b/apps/desktop/scripts/batch-sign-binaries.mjs@@ -22,8 +22,9 @@// afterPack, which invalidates any signature. It is signed per-file by the// customSign hook AFTER rcedit, on the exact Azure mechanism sign-msix.mjs// uses for the package itself.-// - The customSign hook returns true (does nothing) for every file the batch-// already covered, so electron-builder never re-signs one-by-one.+// - Extra-resource copies invoke customSign BEFORE afterPack; payload files+// are deferred to the sanitized batch. Later per-file calls are no-ops,+// so electron-builder never re-signs those binaries one-by-one.//// Sign-nested-chromium.mjs stays as-is: it is macOS-only (codesign --deep over// .app bundles inside the payload for Apple notarization) and is invoked from@@ -40,10 +41,14 @@import { execFile } from 'node:child_process'import fs from 'node:fs'import path from 'node:path'+import { Arch } from 'app-builder-lib'+import { computeArchToTargetNamesMap } from 'app-builder-lib/internal'import { isMain } from './utils.mjs'import { createPayloadSignCache } from './payload-sign-cache.mjs'import { ensureWindowsBundleTools } from './windows-bundle-tools.mjs'+/** @typedef {(cmd: string, args: string[], options?: import('node:child_process').ExecFileOptions) => unknown} SignExecutor */+export const CHUNK_SIZE = 100// How many signtool children may run at once. Azure Trusted Signing and the// timestamp server are both network round-trips per file, so N concurrent@@ -177,7 +182,7 @@ export function azureSigningConfigured(env = process.env) {* server, and a timestamp failure would force a full re-sign).** @param {string[]} files- * @param {{ signtool: string, dlib: string, metadataPath: string, exec?: typeof execFile, execOptions?: import('node:child_process').ExecFileOptions }} opts+ * @param {{ signtool: string, dlib: string, metadataPath: string, exec?: SignExecutor, execOptions?: import('node:child_process').ExecFileOptions }} opts*/export async function signChunk(files, opts) {const args = [@@ -202,7 +207,7 @@ export async function signChunk(files, opts) {* whole re-sign) and runs concurrently like the sign pass.** @param {string[]} files- * @param {{ signtool: string, timestampUrl?: string, exec?: typeof execFile, execOptions?: import('node:child_process').ExecFileOptions, timestampAttempts?: number, timestampRetryDelayMs?: number }} opts+ * @param {{ signtool: string, timestampUrl?: string, exec?: SignExecutor, execOptions?: import('node:child_process').ExecFileOptions, timestampAttempts?: number, timestampRetryDelayMs?: number }} opts*/export async function timestampChunk(files, opts) {const args = [@@ -233,7 +238,7 @@ export async function timestampChunk(files, opts) {* passes. Identical cacheable inputs share one signing operation.** @param {string[]} binaries file list from getBinaries- * @param {{ env?: NodeJS.ProcessEnv, exec?: typeof execFile, chunkSize?: number, concurrency?: number, mkdtemp?: typeof fs.mkdtempSync, signtool?: string, dlib?: string, dotnetRoot?: string, config?: import('app-builder-lib').Configuration, resourcesDir?: string, timestampUrl?: string, timestampAttempts?: number, timestampRetryDelayMs?: number, cache?: ReturnType<typeof createPayloadSignCache> }} [opts]+ * @param {{ env?: NodeJS.ProcessEnv, exec?: SignExecutor, chunkSize?: number, concurrency?: number, mkdtemp?: typeof fs.mkdtempSync, signtool?: string, dlib?: string, dotnetRoot?: string, config?: import('app-builder-lib').Configuration, resourcesDir?: string, timestampUrl?: string, timestampAttempts?: number, timestampRetryDelayMs?: number, cache?: ReturnType<typeof createPayloadSignCache> }} [opts]* @returns {Promise<{ signed: number, chunks: number, skipped: boolean }>}* skipped=true when Azure signing is not configured (caller warns).*/@@ -346,12 +351,38 @@ export async function batchSignAppTree(appOutDir, productExePath, opts = {}) {const SIGNABLE_PACKAGE_EXTENSIONS = ['.msix', '.msixbundle']const STORE_ARTIFACT_PREFIX = 'Store-'+/**+ * Match the paths WinPackager.signApp signs after editing the root executable.+ * The per-file hook has no arch/appOutDir: use the same target normalization,+ * output macros and computeAppOutDir as Packager.doBuild/PlatformPackager.pack.+ * @param {string} file+ * @param {import('app-builder-lib').WinPackager} packager+ * @returns {boolean}+ */+function isProductExe(file, packager) {+ // Packager initializes targets and validateConfig supplies directories.output+ // before doBuild can invoke this hook (the public input types are optional).+ const targets = /** @type {Map<Arch, string[]>} */ (packager.packagerOptions.targets?.get(packager.platform))+ const output = /** @type {string} */ (packager.config.directories?.output)+ const arches = computeArchToTargetNamesMap(targets, packager, packager.platform)+ const resolved = path.resolve(file).toLowerCase()+ for (const arch of arches.keys()) {+ const outDir = path.resolve(packager.projectDir, packager.expandMacro(output, Arch[arch]))+ // Protected in the declarations, but this is the actual pack() resolver;+ // bracket access avoids inventing a parallel output-directory convention.+ const appOutDir = packager['computeAppOutDir'](outDir, arch)+ const productExe = path.resolve(appOutDir, `${packager.appInfo.productFilename}.exe`)+ if (resolved === productExe.toLowerCase()) return true+ }+ return false+}+/*** The electron-builder custom win.sign hook.** @param {{ path: string }} configuration- * @param {any} packager- * @param {{ signMsix?: (configuration: any, packager: any) => Promise<void>, azureSignFile?: (file: string, packager: any) => Promise<void> }} [deps]+ * @param {import('app-builder-lib').WinPackager} packager+ * @param {{ signMsix?: (configuration: { path: string }, packager: import('app-builder-lib').WinPackager) => Promise<void>, azureSignFile?: (file: string, packager: import('app-builder-lib').WinPackager) => Promise<void> }} [deps]* @returns {Promise<boolean>} true when this hook handled the file* (batch-signed: nothing to do) — electron-builder must not re-sign it.*/@@ -368,13 +399,14 @@ export async function customSign(configuration, packager, deps = {}) {}// The product exe was rcedit-ed after the batch ran, so it is signed here,// after its resources are final, on the same Azure manager sign-msix uses.- const productName = packager?.appInfo?.productFilename- if (productName && base.toLowerCase() === `${productName.toLowerCase()}.exe`) {+ const productName = packager.appInfo.productFilename+ if (base.toLowerCase() === `${productName.toLowerCase()}.exe` && isProductExe(file, packager)) {const { azureSignFile } = await import('./sign-msix.mjs')await (deps.azureSignFile ?? azureSignFile)(file, packager)return true}- // Everything else the hook is offered was already batch-signed in afterPack.+ // Payload copies arrive before afterPack; defer them to its sanitized batch.+ // Calls after afterPack are no-ops for binaries that batch already signed.return true}diff --git a/apps/desktop/scripts/batch-sign-binaries.test.mjs b/apps/desktop/scripts/batch-sign-binaries.test.mjsindex 67ea52ad082..1fad4d5739c 100644--- a/apps/desktop/scripts/batch-sign-binaries.test.mjs+++ b/apps/desktop/scripts/batch-sign-binaries.test.mjs@@ -3,8 +3,11 @@ import fs from 'node:fs'import os from 'node:os'import path from 'node:path'+import { Arch, Packager, Platform, WinPackager } from 'app-builder-lib'import { afterEach, test } from 'vitest'+import builderConfig from '../electron-builder.config.cjs'+import {azureSigningConfigured,batchSignAppTree,@@ -127,24 +130,48 @@ test('customSign skips Store- submission packages (Partner Center signs)', asyncassert.equal(result, true)})-test('customSign delegates the msix package and the product exe to the Azure signer', async () => {+test('customSign delegates only the msix package and root product exe to the Azure signer', async () => {+ /** @type {string[][]} */const delegated = []+ /** @type {Parameters<typeof customSign>[2]} */const deps = {- signMsix: async configuration => delegated.push(['msix', configuration.path]),- azureSignFile: async file => delegated.push(['exe', file])+ signMsix: async configuration => { delegated.push(['msix', configuration.path]) },+ azureSignFile: async file => { delegated.push(['exe', file]) }+ }+ const output = path.join(tmpTree(), '${os}', '${arch}')+ const info = new Packager({+ projectDir: path.resolve(import.meta.dirname, '..'),+ targets: Platform.WINDOWS.createTarget(['msix'], Arch.x64, Arch.arm64),+ config: {+ ...builderConfig,+ // validateConfig normalizes these file sets in place.+ files: structuredClone(builderConfig.files),+ extraResources: structuredClone(builderConfig.extraResources),+ directories: { output },+ win: { ...builderConfig.win, executableName: 'hermes-collision' }+ }+ })+ await info.validateConfig()+ const packager = new WinPackager(info)+ const msix = path.join(tmpTree(), 'HermesBundled-0.28.0-win-x64.msix')+ assert.equal(await customSign({ path: msix }, packager, deps), true)+ assert.deepEqual(delegated, [['msix', msix]])++ for (const arch of [Arch.x64, Arch.arm64]) {+ const root = packager['computeAppOutDir'](packager.expandMacro(output, Arch[arch]), arch)+ const exeName = `${packager.appInfo.productFilename}.exe`+ const exe = path.join(root, exeName)+ delegated.length = 0+ // Same basename is not enough: payload copies wait for the afterPack batch.+ for (const file of [path.join(root, 'resources', 'agent-payload', 'bin', exeName), path.join(`${root}-other`, exeName)]) {+ assert.equal(await customSign({ path: file }, packager, deps), true)+ }+ assert.deepEqual(delegated, [])+ // Returning true suppresses electron-builder's fallback per-file signer.+ assert.equal(await customSign({ path: exe }, packager, deps), true)+ assert.equal(await customSign({ path: exe.toUpperCase() }, packager, deps), true)+ assert.deepEqual(delegated, [['exe', exe], ['exe', exe.toUpperCase()]])}- const packager = { appInfo: { productFilename: 'Hermes' } }-- await customSign({ path: 'C:/out/HermesBundled-0.28.0-win-x64.msix' }, packager, deps)- await customSign({ path: 'C:/out/win-unpacked/Hermes.exe' }, packager, deps)-- // The hook's contract is `true` (handled) even when it delegated —- // electron-builder must not fall back to per-file default signing.- assert.deepEqual(delegated, [- ['msix', 'C:/out/HermesBundled-0.28.0-win-x64.msix'],- ['exe', 'C:/out/win-unpacked/Hermes.exe']- ])- assert.equal(await customSign({ path: 'C:/out/win-unpacked/Hermes.exe' }, packager, deps), true)})test('customSign does not mistake a similarly-named payload exe for the product exe', async () => {diff --git a/docs/shared-bundle-builds.md b/docs/shared-bundle-builds.mdindex 404bbe33584..8b0946390b7 100644--- a/docs/shared-bundle-builds.md+++ b/docs/shared-bundle-builds.md@@ -214,8 +214,10 @@ consumers. They are not interchangeable cleanup targets.- Native staging prunes obsolete entries only in its build-owned tool store.It does not prune the user's machine-wide store.- Native staging retains `uv-cache/` for offline mutable-environment rebuilds.- It keeps extracted wheel entries but removes wheel ZIPs beneath `sdists-v*`- so native signing can reach the extracted binaries.+ It copies extracted wheels and index/revision metadata, but excludes redundant+ wheel ZIPs and cached sdist `src/` trees (including Rust `target/` outputs)+ before copying. The provider cache is unchanged; native signing reaches the+ extracted binaries without scanning build-only artifacts.- PM-runtime and application builds share the provider's persistent uv cache.CI restores/saves that cache, not the temporary build HOME. Failed buildsretain completed wheels. Only v2 keys are restored; there is no legacy fallback.diff --git a/scripts/bundles/dmgbuild_diagnostics.py b/scripts/bundles/dmgbuild_diagnostics.pyindex 1492016dfec..b2e13ac2a1b 100644--- a/scripts/bundles/dmgbuild_diagnostics.py+++ b/scripts/bundles/dmgbuild_diagnostics.py@@ -5,6 +5,7 @@ import functoolsimport jsonimport subprocessimport sys+import timedef report_detach_failure(target, attachment, output, *, run=subprocess.run, stream=None):@@ -56,11 +57,18 @@ def report_detach_failure(target, attachment, output, *, run=subprocess.run, strdef wrap_hdiutil(native, *, report=report_detach_failure, stream=None):attachments = {}+ stream = sys.stderr if stream is None else stream@functools.wraps(native)def observed(command, *args, **kwargs):+ started = time.monotonic()+ print(f"[dmg-hdiutil] start {command} {json.dumps(args)}", file=stream, flush=True)result = native(command, *args, **kwargs)code, output = result+ print(f"[dmg-hdiutil] end {command} status={code} elapsed={time.monotonic() - started:.2f}s",+ file=stream, flush=True)+ if code != 0:+ print(f"[dmg-hdiutil] output: {output!r}", file=stream, flush=True)if command == "attach" and code == 0 and isinstance(output, dict):attachment = {"image": args[-1], "entities": output.get("system-entities", [])}for entity in attachment["entities"]:diff --git a/scripts/bundles/native.py b/scripts/bundles/native.pyindex ee5bddd594d..1809fc44903 100644--- a/scripts/bundles/native.py+++ b/scripts/bundles/native.py@@ -53,16 +53,30 @@ def _arch_guard(store_dir: Path) -> list[str]:def stage_uv_cache(source: Path, destination: Path) -> None:- """Keep extracted wheels for offline installs, not unsigned build ZIPs.+ """Keep offline wheel/index entries, without copying sdist build inputs.- The macOS signer reaches extracted native code, but not code inside ZIPs.- uv installs built wheels from their extracted cache entries.+ uv installs built wheels from extracted entries; their ZIPs and source+ trees (including Rust target/ outputs) are build-only. Scope exclusions+ to cache metadata boundaries so extracted package data stays intact."""- shutil.copytree(source, destination)- for bucket in destination.glob("sdists-v*"):- for wheel in bucket.rglob("*.whl"):- if wheel.is_file():- wheel.unlink()+ def ignore(directory: str, names: list[str]) -> set[str]:+ path = Path(directory)+ parts = path.relative_to(source).parts+ if not parts or not parts[0].startswith("sdists-v"):+ return set()+ omitted = set()+ # Source trees live under a revision selected by a sibling pointer.+ if "src" in names and (path / "src").is_dir() and any(+ (path.parent / pointer).is_file() for pointer in ("revision.http", "revision.rev")+ ):+ omitted.add("src")+ # Build settings can put wheel entries in a shard below the revision.+ # The signer can reach extracted code, but not native code inside ZIPs.+ if "metadata.msgpack" in names:+ omitted.update(name for name in names if name.endswith(".whl") and (path / name).is_file())+ return omitted++ shutil.copytree(source, destination, ignore=ignore)def stage_pm_runtime(root: Path, python: Path, repo: Path, *, offline: bool = False,diff --git a/scripts/releases/r2.py b/scripts/releases/r2.pyindex 1bf596615a4..78dec9594ad 100644--- a/scripts/releases/r2.py+++ b/scripts/releases/r2.py@@ -11,7 +11,7 @@ import reimport sysimport timefrom datetime import datetime, timezone-from typing import Callable, Iterable+from typing import Callable, Iterable, castfrom urllib.parse import quote, urlparseREGION = "auto"@@ -538,11 +538,13 @@ def put_object(content_type: str | None,conditions: dict[str, str] | None = None,fetcher: Callable[..., Response] | None = None,+ *,+ multipart_part_size: int = 64 * 1024 * 1024,) -> None:- """`payload` is a FILE PATH (streamed — the msixbundle is ~2.7GB; str or- os.PathLike accepted) or a small in-memory bytes body (feed manifests- from finalize). A 412 on an immutable path PUT verifies the remote bytes- match before treating the conflict as success."""+ """Stream file paths, using multipart for large artifacts, or send bytes.++ Immutable conflicts must match the local digest before reuse.+ """conditions = conditions or {}is_path = isinstance(payload, (str, os.PathLike))if is_path:@@ -570,6 +572,11 @@ def put_object(response: Response | None = Nonefor _ in range(3):try:+ if is_path and size > multipart_part_size:+ from .r2_multipart import upload_file++ upload_file(url, cast(str, payload), size, creds, content_type, extra, multipart_part_size)+ breakresponse = (fetcher(method="PUT", url=url, body_hash=body_hash, body=body,content_length=size, extra_headers=extra)@@ -1006,8 +1013,11 @@ def main(argv: list[str] | None = None) -> None:if __name__ == "__main__":+ # Siblings import the canonical module; run the CLI on that same identity.+ from scripts.releases.r2 import main as cli_main+try:- main()+ cli_main()except SystemExit:raiseexcept Exception as err: # pragma: no cover — CLI error surfacediff --git a/scripts/releases/r2_multipart.py b/scripts/releases/r2_multipart.pynew file mode 100644index 00000000000..bc690d72d87--- /dev/null+++ b/scripts/releases/r2_multipart.py@@ -0,0 +1,94 @@+"""Multipart transport for release files larger than a single upload part."""+from __future__ import annotations++from concurrent.futures import ThreadPoolExecutor+import hashlib+import http.client+from typing import Iterable+from xml.etree import ElementTree as ET+++def _file_range(path: str, offset: int, size: int) -> Iterable[bytes]:+ with open(path, "rb") as handle:+ handle.seek(offset)+ while size:+ chunk = handle.read(min(size, 1024 * 1024))+ if not chunk:+ raise OSError(f"Upload source was truncated: {path}")+ size -= len(chunk)+ yield chunk+++def upload_file(+ url: str, path: str, size: int, creds: dict[str, str],+ content_type: str | None, headers: dict[str, str], part_size: int,+) -> None:+ from . import r2++ if not 5 * 1024 * 1024 <= part_size <= 5 * 1024**3:+ raise ValueError("Multipart parts must be between 5 MiB and 5 GiB")+ if (size + part_size - 1) // part_size > 10000:+ raise ValueError("Multipart upload exceeds 10,000 parts")+ response = r2.signed_request(+ "POST", url + "?uploads=", creds=creds, now=r2.amz_timestamp(),+ content_length=0, content_type=content_type, extra_headers=headers,+ )+ upload_id = ET.fromstring(response.text()).findtext("{*}UploadId")+ if not upload_id:+ raise r2.R2RequestError("POST", url, 502, "Missing multipart upload ID")+ upload_url = url + "?" + r2.canonical_query({"uploadId": upload_id})++ def upload_part(offset: int) -> tuple[int, str]:+ number = offset // part_size + 1+ length = min(part_size, size - offset)+ digest = hashlib.sha256()+ for chunk in _file_range(path, offset, length):+ digest.update(chunk)+ part_url = url + "?" + r2.canonical_query({+ "partNumber": str(number), "uploadId": upload_id,+ })+ part = r2.signed_request(+ "PUT", part_url, creds=creds, now=r2.amz_timestamp(),+ body_iter_factory=lambda: _file_range(path, offset, length),+ body_hash=digest.hexdigest(), content_length=length,+ )+ etag = part.header("etag")+ if not etag:+ raise r2.R2RequestError("PUT", part_url, 502, "Missing part ETag")+ print(f"r2: uploaded part {number} ({length} bytes)", flush=True)+ return number, etag++ try:+ # Each worker reopens its range on retries; no whole-artifact buffer.+ with ThreadPoolExecutor() as pool:+ parts = list(pool.map(upload_part, range(0, size, part_size)))+ document = ET.Element("CompleteMultipartUpload")+ for number, etag in parts:+ part = ET.SubElement(document, "Part")+ ET.SubElement(part, "PartNumber").text = str(number)+ ET.SubElement(part, "ETag").text = etag+ body = ET.tostring(document, encoding="utf-8")+ conditions = {key: value for key, value in headers.items() if key.lower().startswith("if-")}+ try:+ response = r2.signed_request(+ "POST", upload_url, creds=creds, now=r2.amz_timestamp(),+ body=body, body_hash=hashlib.sha256(body).hexdigest(),+ content_length=len(body), content_type="application/xml",+ extra_headers=conditions, tries=1,+ )+ except (OSError, http.client.HTTPException) as error:+ # Completion may already have committed. A fresh conditional upload+ # either succeeds or reaches the caller's immutable digest check.+ raise r2.R2RequestError("POST", upload_url, 503, str(error)) from error+ # S3 can return an error XML document after sending HTTP 200 headers.+ result = ET.fromstring(response.text())+ if result.tag.rsplit("}", 1)[-1] != "CompleteMultipartUploadResult":+ code = result.findtext("{*}Code")+ status = 503 if code in {"InternalError", "SlowDown", "ServiceUnavailable", "RequestTimeout"} else 400+ raise r2.R2RequestError("POST", upload_url, status, response.text())+ except BaseException as error:+ try:+ r2.signed_request("DELETE", upload_url, creds=creds, now=r2.amz_timestamp())+ except Exception as cleanup_error:+ error.add_note(f"Multipart abort failed: {cleanup_error}")+ raisediff --git a/scripts/termux/build_builder_image.sh b/scripts/termux/build_builder_image.shindex feb8a1bda9e..901b9e4bff6 100755--- a/scripts/termux/build_builder_image.sh+++ b/scripts/termux/build_builder_image.sh@@ -1,9 +1,8 @@#!/usr/bin/env bash# Build + push the derived termux builder image (toolchain pre-baked).#-# The image is content-addressed off the pinned base: its tag IS the-# pm/lock.json termux-docker digest (short form), so a lock bump produces-# a new builder image and the old one is never reused against a new base.+# The image tag hashes the full pinned base digest and Dockerfile bytes,+# so either a lock bump or a toolchain recipe change produces a new image.# Pushes to GHCR with the repo's CI identity (GITHUB_TOKEN); idempotent --# an existing identical tag is left alone.#@@ -18,8 +17,12 @@ DIGEST="$(python3 -c 'import sys; sys.path.insert(0, "."); from pm.lock import t[ -n "$DIGEST" ] || { echo "termux-docker digest missing" >&2; exit 1; }BASE="termux/termux-docker@${DIGEST}"-SHORT="${DIGEST#sha256:}"-SHORT="${SHORT:0:12}"+DOCKERFILE="scripts/termux/termux-builder.Dockerfile"+SHORT="$(python3 -c '+import hashlib, pathlib, sys+identity = sys.argv[1].encode() + b"\0" + pathlib.Path(sys.argv[2]).read_bytes()+print(hashlib.sha256(identity).hexdigest()[:12])+' "$BASE" "$DOCKERFILE")"REGISTRY="ghcr.io"OWNER="${GITHUB_REPOSITORY_OWNER,,}"IMAGE="${REGISTRY}/${OWNER}/hermes-termux-builder:${SHORT}"@@ -32,7 +35,7 @@ fiecho "building $IMAGE from $BASE"docker build \- -f scripts/termux/termux-builder.Dockerfile \+ -f "$DOCKERFILE" \--build-arg "BASE=${BASE}" \-t "$IMAGE" \scripts/termux \diff --git a/tests-js/setup-pm-cache.test.mjs b/tests-js/setup-pm-cache.test.mjsindex 6669c3f64e7..f359be6f465 100644--- a/tests-js/setup-pm-cache.test.mjs+++ b/tests-js/setup-pm-cache.test.mjs@@ -71,3 +71,32 @@ it('all bundle consumers save on failure, after building, without discarding offexpect(upload.uses.split('@')[0]).toBe('actions/cache/save')expect(upload.with).toEqual({ path: '${{ inputs.path }}', key: '${{ inputs.key }}' })})++it('desktop consumers can replace an underfilled npm snapshot before packaging fails', () => {+ const restored = setup.runs.steps.find(step => step.id === 'node-cache-restore')+ expect(restored).toBeDefined()+ const prefix = restored.with['restore-keys'].trim()+ expect(restored.with.key).toBe(`${prefix}\${{ github.run_id }}-\${{ github.run_attempt }}`)+ // A toolchain-only job must not shadow the desktop consumer's warm snapshot.+ for (const boundary of ['github.job', 'node-cache-dependency-path', 'cache-suffix', 'target', 'npm-version']) {+ expect(prefix).toContain(boundary)+ }+ expect(setup.outputs['node-cache-key'].value).toContain('steps.node-cache-restore.outputs.cache-primary-key')+ const workflow = action('../.github/workflows/desktop-bundled-release.yml')+ const jobs = Object.values(workflow.jobs).filter(job =>+ job.steps?.some(step => step.name === 'Prepare desktop dependencies'))+ expect(jobs.length).toBeGreaterThan(0)+ for (const job of jobs) {+ const toolchain = job.steps.find(step => step.uses === './.github/actions/setup-pm')+ expect(toolchain.with['save-node-cache']).toBe(false)+ const prepareIndex = job.steps.findIndex(step => step.name === 'Prepare desktop dependencies')+ const saveIndex = job.steps.findIndex(step => step.name === 'Save warmed npm downloads')+ const buildIndex = job.steps.findIndex(step => step.name === 'Build and package')+ expect(saveIndex).toBeGreaterThan(prepareIndex)+ expect(saveIndex).toBeLessThan(buildIndex)+ expect(job.steps[saveIndex].with).toEqual({+ path: `\${{ steps.${toolchain.id}.outputs.npm-cache-path }}`,+ key: `\${{ steps.${toolchain.id}.outputs.node-cache-key }}`,+ })+ }+})diff --git a/tests/scripts/test_bundle_native.py b/tests/scripts/test_bundle_native.pyindex d4ec324552e..f758e378c2d 100644--- a/tests/scripts/test_bundle_native.py+++ b/tests/scripts/test_bundle_native.py@@ -1,6 +1,7 @@"""The native bundle pipeline publishes only after a real staged sync succeeds."""from __future__ import annotations+import hashlibimport jsonimport osimport shutil@@ -134,7 +135,44 @@ def test_bundle_stages_git_tree_and_runs_native_children_before_manifest(tmp_patnative._stage_native(SimpleNamespace(out=str(output), ref="HEAD"))-def test_staged_cache_installs_built_wheel_without_unsigned_zip(tmp_path):[email protected]("pointer, shard", [("revision.http", ""), ("revision.rev", "build-settings")])+def test_staged_cache_skips_build_inputs_before_copying(tmp_path, monkeypatch, pointer, shard):+ cache = tmp_path / "cache"+ revision = Path("sdists-v9/index/package/revision")+ wheels = revision / shard+ waste = {+ revision / "src/target/release/build.exe": b"build output",+ wheels / "cache_proof-1.0-py3-none-any.whl": b"redundant ZIP",+ }+ kept = {+ wheels / "metadata.msgpack": b"wheel metadata",+ revision.parent / pointer: b"revision pointer",+ wheels / "cache_proof-1.0-py3-none-any/src/template.whl": b"package data",+ Path("archive-v0/entry/cache_proof/src/__init__.py"): b"archive data",+ Path("other-bucket/src/keep.whl"): b"unrelated data",+ }+ for relative, data in {**waste, **kept}.items():+ path = cache / relative+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(data)+ copyfile = shutil.copyfile++ def record_copy(source, destination, **kwargs):+ assert Path(source).relative_to(cache) not in waste, "build inputs must never be copied"+ return copyfile(source, destination, **kwargs)++ shipped = tmp_path / "payload/uv-cache"+ with monkeypatch.context() as patch:+ patch.setattr(shutil, "copyfile", record_copy)+ native.stage_uv_cache(cache, shipped)+ assert all(not (shipped / relative).exists() for relative in waste)+ assert all((shipped / relative).read_bytes() == data for relative, data in kept.items())+ assert all((cache / relative).read_bytes() == data for relative, data in {**waste, **kept}.items())+++def test_staged_cache_rebuilds_venv_offline_without_build_sources_or_zips(tmp_path):+ from tests.pm._fixtures import _wheel+uv = shutil.which("uv")assert uv, "native bundle test requires uv"package = tmp_path / "package"@@ -150,49 +188,75 @@ def test_staged_cache_installs_built_wheel_without_unsigned_zip(tmp_path):archive = dist / "cache_proof-1.0.0.tar.gz"with tarfile.open(archive, "w:gz") as source:source.add(package, arcname="cache_proof-1.0.0")+ wheel = _wheel(dist, "wheel_proof")+ for name, artifact in (("cache-proof", archive), ("wheel-proof", wheel)):+ index = dist / "simple" / name+ index.mkdir(parents=True)+ digest = hashlib.sha256(artifact.read_bytes()).hexdigest()+ (index / "index.html").write_text(+ f'<a href="../../{artifact.name}#sha256={digest}">{artifact.name}</a>', encoding="utf-8",+ )+ project = tmp_path / "project"+ project.mkdir()+ (project / "pyproject.toml").write_text(+ '[project]\nname="offline-proof"\nversion="1.0"\nrequires-python=">=3.11"\n'+ 'dependencies=["cache-proof==1.0.0", "wheel-proof==1.0"]\n[tool.uv]\npackage=false\n',+ encoding="utf-8",+ )cache = tmp_path / "build-cache"env = {**os.environ, "UV_CACHE_DIR": str(cache), "UV_NO_CONFIG": "1", "UV_PYTHON_DOWNLOADS": "never"}server = ThreadingHTTPServer(("127.0.0.1", 0), partial(SimpleHTTPRequestHandler, directory=str(dist)))thread = threading.Thread(target=server.serve_forever, daemon=True)thread.start()- url = f"http://127.0.0.1:{server.server_port}/{archive.name}"+ index_url = f"http://127.0.0.1:{server.server_port}/simple"try:subprocess.run([uv, "pip", "install", "--python", sys.executable, "--target", str(tmp_path / "first"),- "--no-build-isolation", "--no-deps", url],+ "--no-build-isolation", "--no-deps", "--index-url", index_url,+ "cache-proof==1.0.0", "wheel-proof==1.0"],env=env, cwd=tmp_path, capture_output=True, text=True, check=True, timeout=60,)+ locked = subprocess.run(+ [uv, "lock", "--python", sys.executable, "--index-url", index_url, "--no-build-isolation"],+ env=env, cwd=project, capture_output=True, text=True, timeout=60,+ )+ assert locked.returncode == 0, locked.stderr+ warmed = subprocess.run(+ [uv, "sync", "--python", sys.executable, "--frozen", "--index-url", index_url],+ env=env, cwd=project, capture_output=True, text=True, timeout=60,+ )+ assert warmed.returncode == 0, warmed.stderrfinally:server.shutdown()server.server_close()thread.join(timeout=5)- assert list(cache.rglob("*.whl")), "the actual uv build must create the redundant ZIP"+ built_zips = list(cache.rglob("*.whl"))+ assert built_zips, "the actual uv build must create the redundant ZIP"+ sources = [path for bucket in cache.glob("sdists-v*") for path in bucket.rglob("src") if path.is_dir()]+ assert sources, "the actual uv build must leave its source tree in the cache"shipped = tmp_path / "payload/uv-cache"native.stage_uv_cache(cache, shipped)assert not list(shipped.rglob("*.whl"))- assert list(cache.rglob("*.whl")), "the build machine's cache must not change"-- # The stopped server and absent source trees make a fallback build impossible.- shutil.rmtree(dist)- shutil.rmtree(package)- shutil.rmtree(cache)- for source in (shipped / "sdists-v9").rglob("src"):- if source.is_dir():- shutil.rmtree(source)- installed = tmp_path / "installed"+ assert all(not (shipped / path.relative_to(cache)).exists() for path in sources)+ assert all(path.exists() for path in [*built_zips, *sources]), "the build machine's cache must not change"++ # Nothing outside the shipped cache can satisfy this fresh mutable venv.+ for directory in (dist, package, cache, tmp_path / "first", project / ".venv"):+ shutil.rmtree(directory)result = subprocess.run(- [uv, "pip", "install", "--python", sys.executable, "--target", str(installed),- "--no-deps", "--offline", url],- env={**env, "UV_CACHE_DIR": str(shipped)}, cwd=tmp_path,- capture_output=True, text=True, check=True, timeout=60,+ [uv, "sync", "--python", sys.executable, "--frozen", "--offline", "--index-url", index_url],+ env={**env, "UV_CACHE_DIR": str(shipped)}, cwd=project,+ capture_output=True, text=True, timeout=60,)+ assert result.returncode == 0, result.stderrassert "Building" not in result.stderr+ python = project / ".venv" / ("Scripts/python.exe" if os.name == "nt" else "bin/python")probe = subprocess.run(- [sys.executable, "-c", "import cache_proof; print(cache_proof.VALUE)"],- cwd=tmp_path, env={**env, "PYTHONPATH": str(installed)},- capture_output=True, text=True, check=True, timeout=30,+ [str(python), "-I", "-c",+ "import cache_proof, wheel_proof; print(cache_proof.VALUE); print(wheel_proof.__version__)"],+ cwd=tmp_path, env=env, capture_output=True, text=True, check=True, timeout=30,)- assert probe.stdout.strip() == "installed from cached wheel"+ assert probe.stdout.splitlines() == ["installed from cached wheel", "1.0"]def test_native_dispatch_reuses_pm_cache_offline(tmp_path, monkeypatch):diff --git a/tests/scripts/test_dmgbuild_diagnostics.py b/tests/scripts/test_dmgbuild_diagnostics.pyindex 9a0a176537c..f07233e0e5a 100644--- a/tests/scripts/test_dmgbuild_diagnostics.py+++ b/tests/scripts/test_dmgbuild_diagnostics.py@@ -76,6 +76,24 @@ def test_detach_diagnostics_run_before_cleanup_and_preserve_results():assert "timed out" in errors.getvalue()+def test_resize_timings_preserve_native_arguments_and_failure():+ output = io.StringIO()+ failure = (6, "")+ calls = []++ def native(command, *args, **kwargs):+ assert '[dmg-hdiutil] start resize' in output.getvalue()+ calls.append((command, args, kwargs))+ return failure++ observed = diagnostics.wrap_hdiutil(native, stream=output)+ assert observed("resize", "-quiet", "-sectors", "min", "image.dmg", plist=False) is failure+ assert calls == [("resize", ("-quiet", "-sectors", "min", "image.dmg"), {"plist": False})]+ assert "[dmg-hdiutil] end resize" in output.getvalue()+ assert "status=6" in output.getvalue()+ assert "elapsed=" in output.getvalue()++def test_diagnostic_entrypoint_preserves_cli_arguments_and_failure(tmp_path):# This package replays the supplier call contract, not a native DMG build.package = tmp_path / "dmgbuild"diff --git a/tests/scripts/test_release_r2.py b/tests/scripts/test_release_r2.pyindex 9ffe0e530e6..b4cde7358e2 100644--- a/tests/scripts/test_release_r2.py+++ b/tests/scripts/test_release_r2.py@@ -16,13 +16,20 @@from __future__ import annotationsimport base64+import hashlibimport ioimport jsonimport osimport reimport socket+import subprocess+import sysimport threadingfrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path+from types import SimpleNamespace+from urllib.parse import parse_qs, urlsplit+from xml.etree import ElementTree as ETimport pytest@@ -524,6 +531,20 @@ class _R2StubHandler(BaseHTTPRequestHandler):if self.headers.get("Transfer-Encoding", "").lower() == "chunked":data = self._read_chunked()key = self._key()+ query = parse_qs(urlsplit(self.path).query)+ if "partNumber" in query:+ state = server.multipart+ assert query["uploadId"] == ["a+/="]+ assert self.headers["x-amz-content-sha256"] == hashlib.sha256(data).hexdigest()+ number = int(query["partNumber"][0])+ state.attempts[number] = state.attempts.get(number, 0) + 1+ if state.failure == "part":+ return self._send(400, b"InvalidRequest")+ if number == 2 and state.attempts[number] == 1:+ return self._send(503, b"")+ etag = '"' + hashlib.md5(data).hexdigest() + '"'+ state.parts[number] = (data, etag)+ return self._send(200, b"", {"ETag": etag})if self.headers.get("If-None-Match") == "*" and key in server.store:self._send(412, b"Precondition Failed")return@@ -533,9 +554,45 @@ class _R2StubHandler(BaseHTTPRequestHandler):server.store[key] = (data, self.headers.get("If-Match", '"new"'))self._send(200, b"")+ def do_POST(self):+ server, state = self.server, self.server.multipart+ server.requests.append(("POST", self.path, dict(self.headers)))+ query = parse_qs(urlsplit(self.path).query, keep_blank_values=True)+ body = self.rfile.read(int(self.headers.get("Content-Length", 0)))+ assert self.headers["x-amz-content-sha256"] == hashlib.sha256(body).hexdigest()+ key = self._key()+ if "uploads" in query:+ state.created += 1+ state.parts = {}+ if state.reject_existing and key in server.store:+ return self._send(412, b"")+ return self._send(200, b'<InitiateMultipartUploadResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><UploadId>a+/=</UploadId></InitiateMultipartUploadResult>')+ assert query["uploadId"] == ["a+/="]+ state.completed += 1+ if state.failure == "complete" or (state.failure == "transient" and state.completed == 1):+ code = "InvalidPart" if state.failure == "complete" else "InternalError"+ return self._send(200, f"<Error><Code>{code}</Code></Error>")+ if state.failure == "disconnect" and state.completed == 1:+ self.close_connection = True+ return+ if self.headers.get("If-None-Match") == "*" and key in server.store:+ return self._send(412, b"")+ parts = ET.fromstring(body).findall("{*}Part")+ numbers = [int(part.findtext("{*}PartNumber", "0")) for part in parts]+ assert numbers == sorted(state.parts)+ assert [part.findtext("{*}ETag") for part in parts] == [state.parts[n][1] for n in numbers]+ server.store[key] = (b"".join(state.parts[n][0] for n in numbers), '"multipart"')+ if state.failure == "lost-response" and state.completed == 1:+ self.close_connection = True+ return+ self._send(200, b'<CompleteMultipartUploadResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><ETag>done</ETag></CompleteMultipartUploadResult>')+def do_DELETE(self):server = self.server # type: ignore[attr-defined]server.requests.append(("DELETE", self.path, dict(self.headers)))+ if "uploadId=" in self.path:+ server.multipart.aborted += 1+ return self._send(204, b"")key = self._key()server.store.pop(key, None)self._send(204, b"")@@ -567,6 +624,8 @@ def r2_server(monkeypatch):server = ThreadingHTTPServer(("127.0.0.1", 0), _R2StubHandler)server.store = {}server.requests = []+ server.multipart = SimpleNamespace(parts={}, attempts={}, failure=None, created=0,+ completed=0, aborted=0, reject_existing=False)def listing_xml():parts = ["<?xml version='1.0'?><ListBucketResult><IsTruncated>false</IsTruncated>"]@@ -590,6 +649,64 @@ def r2_server(monkeypatch):server.server_close()[email protected]("failure", [None, "part", "complete", "transient", "disconnect", "lost-response"])+def test_multipart_publication_is_atomic_and_retryable(r2_server, tmp_path, failure):+ path = tmp_path / "bundle.msixbundle"+ payload = b"a" * (5 * 1024 * 1024) + b"b" * (5 * 1024 * 1024) + b"last"+ path.write_bytes(payload)+ state = r2_server.multipart+ state.failure, state.reject_existing = failure, failure is not None+ key = "releases/stable/bundle.msixbundle"+ creds, base, bucket = r2.credentials()++ def upload():+ r2.put_object(creds, base, bucket, key, path, r2.amz_timestamp(),+ "application/msixbundle", {"If-None-Match": "*"}, multipart_part_size=5 * 1024 * 1024)++ if failure in {"part", "complete"}:+ with pytest.raises(r2.R2RequestError):+ upload()+ assert key not in r2_server.store and state.aborted == 1+ assert not any(method == "HEAD" for method, _, _ in r2_server.requests)+ return+ upload()+ assert r2_server.store[key][0] == payload+ assert state.attempts[2] >= 2+ assert state.created == (2 if failure else 1)+ for method, _, headers in r2_server.requests:+ assert headers["authorization"].startswith("AWS4-HMAC-SHA256 ")+ if method == "POST":+ assert headers["If-None-Match"] == "*"+ metadata = next(headers for method, url, headers in r2_server.requests if "uploads=" in url)+ assert metadata["Content-Type"] == "application/msixbundle" and metadata["Cache-Control"] == "no-store"+ upload()+ path.write_bytes(payload[:-1] + b"!")+ with pytest.raises(ValueError, match="checksum mismatch"):+ upload()+ assert r2_server.store[key][0] == payload+++def test_cli_reuses_an_immutable_multipart_object(r2_server, tmp_path):+ path = tmp_path / "bundle.msixbundle"+ payload = b"x" * (64 * 1024 * 1024 + 1)+ path.write_bytes(payload)+ r2_server.store["releases/tag/v1.0.0/bundle.msixbundle"] = (payload, '"existing"')+ r2_server.multipart.reject_existing = True+ # Redirect only sockets: CLI and sibling imports must keep one exception identity.+ script = (+ "import http.client, runpy, sys\n"+ f"http.client.HTTPSConnection = lambda *a, **k: http.client.HTTPConnection('127.0.0.1', {r2_server.server_port})\n"+ "sys.argv = ['r2', *sys.argv[1:]]\n"+ "runpy.run_module('scripts.releases.r2', run_name='__main__')\n"+ )+ result = subprocess.run(+ [sys.executable, "-c", script, "put", "--tag", "v1.0.0", "--key", path.name, "--file", str(path), "--immutable"],+ cwd=Path(__file__).resolve().parents[2], env=os.environ, capture_output=True, text=True, timeout=60,+ )+ assert result.returncode == 0, result.stdout + result.stderr+ assert [method for method, _, _ in r2_server.requests] == ["POST", "GET", "HEAD"]++def test_put_streams_a_file_and_verifies_size(r2_server):import tempfilediff --git a/tests/scripts/test_termux_build_driver.py b/tests/scripts/test_termux_build_driver.pyindex 68be12c351e..c967431dcec 100644--- a/tests/scripts/test_termux_build_driver.py+++ b/tests/scripts/test_termux_build_driver.py@@ -181,3 +181,41 @@ def test_release_workflow_runs_the_shared_sequence(build_fixture, identity):assert calls[-1]["args"][-2:] == list(identity)assert (repo / "termux-build/deb/assembly-received-product").read_text() == str(repo / ".build/termux/tui")++[email protected]("changed_input", ["Dockerfile", "base"])+def test_builder_image_identity_covers_all_inputs(tmp_path, changed_input):+ repo = tmp_path / "source with spaces"+ scripts = repo / "scripts/termux"+ scripts.mkdir(parents=True)+ for name in ("build_builder_image.sh", "termux-builder.Dockerfile"):+ shutil.copy2(ROOT / "scripts/termux" / name, scripts / name)+ shutil.copytree(ROOT / "pm", repo / "pm", ignore=shutil.ignore_patterns("__pycache__"))+ tools = tmp_path / "tools"+ tools.mkdir()+ (tools / "python3").symlink_to(sys.executable)+ # Only inspect an already-published image; any build/push call is a failure.+ command = 'docker() { [[ "$1 $2" == "manifest inspect" ]]; }; export -f docker; bash "$1"'+ env = {**os.environ, "PATH": f"{tools}{os.pathsep}{os.environ['PATH']}",+ "GITHUB_REPOSITORY_OWNER": "fixture"}++ def image():+ result = subprocess.run(["bash", "-c", command, "fixture", str(scripts / "build_builder_image.sh")],+ env=env, capture_output=True, text=True, timeout=30)+ assert result.returncode == 0, result.stderr+ return result.stdout.splitlines()[-1]++ original = image()+ assert image() == original+ changed = scripts / "termux-builder.Dockerfile" if changed_input == "Dockerfile" else repo / "pm/lock.json"+ before = changed.read_bytes()+ if changed_input == "Dockerfile":+ changed.write_bytes(before + b"\nRUN apt install -y git\n")+ else:+ pin = json.loads(before)+ digest = pin["packages"]["termux-docker"]["version"]+ pin["packages"]["termux-docker"]["version"] = digest[:-1] + ("a" if digest[-1] != "a" else "b")+ changed.write_text(json.dumps(pin))+ assert image() != original+ changed.write_bytes(before)+ assert image() == original