gemini-code-assist[bot] commented on code in PR #19641:
URL: https://github.com/apache/tvm/pull/19641#discussion_r3326468002


##########
ci/scripts/package/rewrite_wheel.py:
##########
@@ -0,0 +1,399 @@
+#!/usr/bin/env python3
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Rewrite TVM wheel metadata and inject extra runtime files."""
+
+from __future__ import annotations
+
+import argparse
+import base64
+import csv
+import hashlib
+import io
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+import zipfile
+from email.parser import Parser
+from pathlib import Path
+
+
+def _wheel_escape_distribution(value: str) -> str:
+    """Escape a distribution component for wheel filenames and dist-info 
dirs."""
+
+    return re.sub(r"[^\w\d.]+", "_", value).lower()
+
+
+def _wheel_escape_version(value: str) -> str:
+    """Escape a version component while preserving PEP 440 local version 
markers."""
+
+    return re.sub(r"[^\w\d.!+]+", "_", value).lower()
+
+
+def _hash_record(data: bytes) -> tuple[str, str]:
+    digest = hashlib.sha256(data).digest()
+    encoded = base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
+    return f"sha256={encoded}", str(len(data))
+
+
+def _copy_info(info: zipfile.ZipInfo, filename: str) -> zipfile.ZipInfo:
+    copied = zipfile.ZipInfo(filename=filename, date_time=info.date_time)
+    copied.compress_type = info.compress_type
+    copied.comment = info.comment
+    copied.extra = info.extra
+    copied.internal_attr = info.internal_attr
+    copied.external_attr = info.external_attr
+    return copied

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   The `_copy_info` function does not copy the `create_system` attribute from 
the original `ZipInfo` object. This can cause the rewritten wheel to lose its 
original system platform metadata (e.g., defaulting to Windows/MS-DOS `0` 
instead of Unix `3`), which can affect file permissions when the wheel is 
unpacked and makes the build non-reproducible depending on the host OS running 
the script.
   
   ```suggestion
   def _copy_info(info: zipfile.ZipInfo, filename: str) -> zipfile.ZipInfo:
       copied = zipfile.ZipInfo(filename=filename, date_time=info.date_time)
       copied.create_system = info.create_system
       copied.compress_type = info.compress_type
       copied.comment = info.comment
       copied.extra = info.extra
       copied.internal_attr = info.internal_attr
       copied.external_attr = info.external_attr
       return copied
   ```



##########
ci/scripts/package/verify_tvm_install.py:
##########
@@ -0,0 +1,275 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Verify an installed TVM wheel imports and ships the expected runtime DSO."""
+
+from __future__ import annotations
+
+import faulthandler
+import os
+from pathlib import Path
+import signal
+import sys
+
+faulthandler.enable(all_threads=True)
+if hasattr(sys.stdout, "reconfigure"):
+    sys.stdout.reconfigure(line_buffering=True)
+
+import numpy as np
+
+
+def log(*args: object) -> None:
+    print(*args, flush=True)
+
+
+def _enable_python_fault_handler() -> None:
+    """Install Python's signal handler after native libraries may install 
theirs."""
+    faulthandler.enable(all_threads=True)
+    try:
+        faulthandler.register(signal.SIGUSR1, all_threads=True)
+    except (AttributeError, RuntimeError, ValueError):
+        pass
+
+
+def expect_bool(name: str) -> bool | None:
+    value = os.environ.get(name)
+    if value is None or value == "":
+        return None
+    normalized = value.strip().lower()
+    if normalized in {"1", "true", "yes", "on"}:
+        return True
+    if normalized in {"0", "false", "no", "off"}:
+        return False
+    raise RuntimeError(f"{name} must be a boolean value, got {value!r}")
+
+
+def _clear_external_library_overrides() -> None:
+    for name in ("TVM_LIBRARY_PATH", "LD_LIBRARY_PATH", "DYLD_LIBRARY_PATH"):
+        if name in os.environ:
+            log(f"clearing {name} before importing tvm")
+            os.environ.pop(name, None)
+
+
+def _first_existing(candidates: list[Path]) -> Path:
+    for candidate in candidates:
+        if candidate.exists():
+            return candidate
+    return candidates[0]
+
+
+def _assert_loaded_runtime_from_wheel(libdir: Path, runtime_candidates: 
list[Path]) -> None:
+    import tvm.base as tvm_base  # pylint: disable=import-outside-toplevel
+
+    loaded_runtime = Path(tvm_base._LIB_RUNTIME._name).resolve()  # pylint: 
disable=protected-access

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   To prevent potential `AttributeError` or `TypeError` if the TVM runtime 
library fails to load or is initialized as `None`, add a defensive check before 
accessing `_LIB_RUNTIME._name`. This aligns with the defensive checks used 
elsewhere in the file (e.g., `_log_tvm_ffi_details`).
   
   ```suggestion
       if tvm_base._LIB_RUNTIME is None or not hasattr(tvm_base._LIB_RUNTIME, 
"_name"):
           raise RuntimeError("TVM runtime library was not loaded correctly or 
is missing '_name' attribute")
       loaded_runtime = Path(tvm_base._LIB_RUNTIME._name).resolve()  # pylint: 
disable=protected-access
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to