The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(termux): link native Python wheels to the shipped interpreter
ethernet5b64b060f479
diff --git a/.github/workflows/termux-verify.yml b/.github/workflows/termux-verify.ymlindex c32e871d1e2..8f2df7f1e02 100644--- a/.github/workflows/termux-verify.yml+++ b/.github/workflows/termux-verify.yml@@ -12,12 +12,35 @@ on:permissions:contents: read+ actions: readconcurrency:group: termux-verify-${{ github.ref }}cancel-in-progress: truejobs:+ contracts:+ name: Termux packaging contracts on Linux+ runs-on: ubuntu-24.04+ timeout-minutes: 15+ steps:+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ with:+ persist-credentials: false+ - uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0+ with:+ version: '0.12.3'+ enable-cache: false+ - name: Install the locked test environment+ run: |+ sudo apt-get update+ sudo apt-get install -y patchelf+ uv venv --python 3.11 .venv+ uv export --frozen --extra dev --no-emit-project --no-hashes -o "$RUNNER_TEMP/requirements.txt"+ uv pip install --python .venv/bin/python -r "$RUNNER_TEMP/requirements.txt"+ - name: Run the native linker and wheel contracts+ run: bash scripts/run_tests.sh -j 2 tests/test_termux_python_linkage.py tests/test_termux_retag_wheel.py+native-linkage:name: Reproduce and verify bionic Python linkageruns-on: ubuntu-24.04-arm@@ -35,6 +58,13 @@ jobs:bash scripts/termux/build_cpython.sh termux-build/payloadbash scripts/termux/build_uv.sh termux-build/payloadpython3 scripts/termux/stage_runtime_libs.py termux-build/payload+ - name: Download the wheel from the confirmed failing build+ uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4+ with:+ github-token: ${{ github.token }}+ run-id: 34044387547+ name: termux-linkage-842e3b0eed0eafbfb3d7f219ea465bd92d055cc2+ path: termux-build/baseline- name: Run the native reproductionrun: |image=ghcr.io/ethernet8023/hermes-termux-builder:c14ffb703abf@@ -52,7 +82,8 @@ jobs:export LD_LIBRARY_PATH="/payload/python$PREFIX/lib:/payload/runtime-libs/lib:$PREFIX/lib"exec "/payload/python$PREFIX/bin/python3.11" \/repo/scripts/termux/probe_python_linkage.py \- --repo /repo --payload /payload --output /evidence+ --repo /repo --payload /payload --output /evidence \+ --built-wheel /repo/termux-build/baseline/firecrawl_anydoc-0.2.4-cp310-abi3-android_24_arm64_v8a.whl'- name: Preserve the built wheel and linker evidenceif: always()diff --git a/scripts/termux/build_wheels.py b/scripts/termux/build_wheels.pyindex 11cef3992c4..1b964a6c467 100644--- a/scripts/termux/build_wheels.py+++ b/scripts/termux/build_wheels.py@@ -19,6 +19,7 @@ import argparseimport osimport subprocessimport sys+import sysconfigimport tarfileimport tempfileimport shutil@@ -387,6 +388,15 @@ def main() -> int:build_wheels(build_set, specs, wheelhouse)fetch_pure_wheels(build_set, specs, wheelhouse, Path(args.resolved))retag_all(wheelhouse, Path(args.retag), args.platform_tag)+ from python_linkage import repair_wheel++ library = Path(sys.base_prefix) / "lib" / sysconfig.get_config_var("LDLIBRARY")+ if not library.is_file():+ raise RuntimeError(f"payload libpython missing: {library}")+ for wheel in sorted(wheelhouse.glob("*.whl")):+ repaired = repair_wheel(wheel, library)+ if repaired:+ print(f" linked {repaired} native extensions to {library.name}: {wheel.name}")wheelhouse_gates(resolved, wheelhouse, build_set)print(f"wheelhouse complete: {len(list(wheelhouse.glob('*.whl')))} wheels in {wheelhouse}")return 0diff --git a/scripts/termux/probe_python_linkage.py b/scripts/termux/probe_python_linkage.pyindex d8d0fa02ccd..1f3492d4982 100644--- a/scripts/termux/probe_python_linkage.py+++ b/scripts/termux/probe_python_linkage.py@@ -39,6 +39,7 @@ def main() -> int:ap.add_argument("--repo", type=Path, required=True)ap.add_argument("--payload", type=Path, required=True)ap.add_argument("--output", type=Path, required=True)+ ap.add_argument("--built-wheel", type=Path)args = ap.parse_args()prefix = Path("/data/data/com.termux/files/usr")python = args.payload / "python" / prefix.relative_to("/") / "bin/python3.11"@@ -63,10 +64,13 @@ def main() -> int:"RUSTFLAGS": f"-L{pylib}","LDFLAGS": f"-L{pylib}",}- run([- str(vp), "-m", "pip", "wheel", "--no-deps", "--no-cache-dir",- "--no-binary", ":all:", "-w", str(args.output), requirement,- ], env=build_env)+ if args.built_wheel:+ shutil.copy2(args.built_wheel, args.output / args.built_wheel.name)+ else:+ run([+ str(vp), "-m", "pip", "wheel", "--no-deps", "--no-cache-dir",+ "--no-binary", ":all:", "-w", str(args.output), requirement,+ ], env=build_env)wheels = sorted(args.output.glob("firecrawl_anydoc-*.whl"))if len(wheels) != 1:raise RuntimeError(f"expected one anydoc wheel, found {wheels}")@@ -86,8 +90,14 @@ def main() -> int:print(baseline.stdout, baseline.stderr, flush=True)soname = subprocess.run(["patchelf", "--print-soname", str(library)], check=True, capture_output=True, text=True).stdout.strip()needed = subprocess.run(["patchelf", "--print-needed", str(extension)], check=True, capture_output=True, text=True).stdout.splitlines()- if soname not in needed:- run(["patchelf", "--add-needed", soname, str(extension)])+ from python_linkage import repair_wheel++ repaired = repair_wheel(wheels[0], library)+ if repaired == 0:+ raise RuntimeError("production wheel repair did not change the failing extension")+ shutil.rmtree(site)+ with zipfile.ZipFile(wheels[0]) as wheel:+ wheel.extractall(site)explicit = import_anydoc(vp, site, env)print("EXPLICIT_LINK_EXIT", explicit.returncode, flush=True)print(explicit.stdout, explicit.stderr, flush=True)diff --git a/scripts/termux/python_linkage.py b/scripts/termux/python_linkage.pynew file mode 100644index 00000000000..7b7c81295e1--- /dev/null+++ b/scripts/termux/python_linkage.py@@ -0,0 +1,84 @@+"""Link Python extensions explicitly for bionic's local symbol lookup."""+from __future__ import annotations++import csv+import io+import os+from pathlib import Path+import shutil+import subprocess+import tempfile+import zipfile++try:+ from .retag_wheel import record_hash+except ImportError:+ from retag_wheel import record_hash+++def link_extension(extension: Path, library: Path) -> bool:+ reader = shutil.which("llvm-readelf") or shutil.which("readelf")+ if reader is None:+ raise RuntimeError("a native ELF reader is required for Python linkage verification")+ symbols = subprocess.check_output(+ [reader, "--dyn-syms", "--wide", str(extension)], text=True,+ )+ if not any(+ " UND " in line and line.split()[-1].startswith(("Py", "_Py"))+ for line in symbols.splitlines()+ ):+ return False+ needed = subprocess.check_output(+ ["patchelf", "--print-needed", str(extension)], text=True,+ ).splitlines()+ soname = subprocess.check_output(+ ["patchelf", "--print-soname", str(library)], text=True,+ ).strip()+ if not soname:+ raise RuntimeError(f"libpython has no SONAME: {library}")+ foreign = [name for name in needed if name.startswith("libpython") and name != soname]+ if foreign:+ raise RuntimeError(f"{extension.name} links a different interpreter: {foreign}")+ if soname in needed:+ return False+ subprocess.run(["patchelf", "--add-needed", soname, str(extension)], check=True)+ return True+++def repair_wheel(wheel: Path, library: Path, *, repair=link_extension) -> int:+ """Repair native members without extracting untrusted archive paths."""+ with tempfile.TemporaryDirectory(prefix="hermes-wheel-link-") as tmp:+ native = Path(tmp) / "extension.so"+ with zipfile.ZipFile(wheel) as archive:+ members = [(info, archive.read(info)) for info in archive.infolist() if not info.is_dir()]+ records = [info.filename for info, _ in members if info.filename.endswith(".dist-info/RECORD")]+ if len(records) != 1:+ raise RuntimeError(f"expected one wheel RECORD: {wheel.name}")+ changed = 0+ updated = []+ for info, data in members:+ if info.filename.endswith(".so"):+ native.write_bytes(data)+ if repair(native, library):+ data = native.read_bytes()+ changed += 1+ updated.append((info, data))+ if not changed:+ return 0+ rows = [+ (info.filename, record_hash(data), str(len(data)))+ for info, data in updated if info.filename != records[0]+ ]+ rows.append((records[0], "", ""))+ record = io.StringIO()+ csv.writer(record, lineterminator="\n").writerows(rows)+ fd, staged = tempfile.mkstemp(prefix=".linked-", suffix=".whl", dir=wheel.parent)+ os.close(fd)+ try:+ with zipfile.ZipFile(staged, "w", zipfile.ZIP_DEFLATED) as archive:+ for info, data in updated:+ archive.writestr(info, record.getvalue().encode() if info.filename == records[0] else data)+ os.replace(staged, wheel)+ finally:+ Path(staged).unlink(missing_ok=True)+ return changeddiff --git a/tests/test_termux_python_linkage.py b/tests/test_termux_python_linkage.pynew file mode 100644index 00000000000..00de9bbbaba--- /dev/null+++ b/tests/test_termux_python_linkage.py@@ -0,0 +1,68 @@+"""Exercise the linker repair against a real native extension on Linux."""+from __future__ import annotations++import shutil+import subprocess+import sys+import sysconfig+from pathlib import Path++import pytest++from scripts.termux import python_linkage++[email protected]("linux")+def test_python_symbols_gain_an_explicit_library_dependency(tmp_path):+ from ctypes import _endian+ import _ctypes++ library = Path(sysconfig.get_config_var("LIBDIR")) / sysconfig.get_config_var("LDLIBRARY")+ extension = tmp_path / Path(_ctypes.__file__).name+ shutil.copy2(_ctypes.__file__, extension)+ original = subprocess.check_output(["patchelf", "--print-needed", str(extension)], text=True).splitlines()+ for name in original:+ if name.startswith("libpython"):+ subprocess.run(["patchelf", "--remove-needed", name, str(extension)], check=True)+ assert python_linkage.link_extension(extension, library)+ needed = subprocess.check_output(["patchelf", "--print-needed", str(extension)], text=True).splitlines()+ soname = subprocess.check_output(["patchelf", "--print-soname", str(library)], text=True).strip()+ assert soname in needed+ assert not python_linkage.link_extension(extension, library), "a second pass must not edit a correct extension"+ subprocess.run(+ [sys.executable, "-c", "import _ctypes; print(_ctypes.__file__)"],+ cwd=tmp_path, check=True,+ )+++def test_wheel_rewrite_regenerates_record_for_changed_member(tmp_path):+ import base64+ import csv+ import hashlib+ import io+ import zipfile++ wheel = tmp_path / "sample-1.0-cp311-cp311-linux_aarch64.whl"+ record = "sample-1.0.dist-info/RECORD"+ with zipfile.ZipFile(wheel, "w") as archive:+ archive.writestr("sample/_native.so", b"unrepaired native bytes")+ archive.writestr("sample/__init__.py", b"")+ archive.writestr("sample-1.0.dist-info/WHEEL", "Wheel-Version: 1.0\nTag: cp311-cp311-linux_aarch64\n")+ archive.writestr(record, "")++ def repair(path, library):+ assert library == tmp_path / "libpython.so"+ path.write_bytes(b"repaired native bytes")+ return True++ python_linkage.repair_wheel(wheel, tmp_path / "libpython.so", repair=repair)+ with zipfile.ZipFile(wheel) as archive:+ assert archive.read("sample/_native.so") == b"repaired native bytes"+ rows = {r[0]: r[1:] for r in csv.reader(io.StringIO(archive.read(record).decode()))}+ for name in archive.namelist():+ if name == record:+ assert rows[name] == ["", ""]+ continue+ data = archive.read(name)+ digest = base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode()+ assert rows[name] == ["sha256=" + digest, str(len(data))]