fix(build): invalidate native objects when the Qt SDK changes

Fingerprint Qt SDK headers for C++ cache inputs and share bounded debug/release startup gates between local tooling and CI.

cx
This commit is contained in:
vicrodh committed 2026-09-06 03:53:05 -06:00
1 parent 088fac93c6
commit 6794e15257
13 files changed
+489 -65

No files matched your search

+2 -2
View File
@@ -141,7 +141,7 @@ jobs:
uses: Swatinem/rust-cache@v2
with:
workspaces: crates -> target
shared-key: qt-linux-${{ inputs.arch }}
shared-key: qt-linux-${{ inputs.arch }}-${{ env.QT_VERSION }}
cache-on-failure: true
save-if: ${{ github.ref == 'refs/heads/main' || github.ref == 'refs/heads/pre-release' }}
@@ -168,7 +168,7 @@ jobs:
"$QT_ROOT_DIR/libexec/moc" --version || true
"$QT_ROOT_DIR/libexec/qmlcachegen" --version || true
"$QMAKE" -query QT_VERSION
cargo build --release --manifest-path crates/Cargo.toml -p qbz-qt
python3 scripts/qt-cargo.py build --release --manifest-path crates/Cargo.toml -p qbz-qt
cp crates/target/release/qbz qbz-unstripped
strip -o qbz crates/target/release/qbz
ls -la qbz qbz-unstripped
+3 -3
View File
@@ -114,7 +114,7 @@ jobs:
uses: Swatinem/rust-cache@v2
with:
workspaces: crates -> target
shared-key: qt-gate-windows
shared-key: qt-gate-windows-${{ env.QT_VERSION }}
cache-on-failure: true
# Tags and the trusted integration branch may seed the cache. A
# manual dispatch on any feature/fork ref remains read-only.
@@ -154,8 +154,8 @@ jobs:
shell: bash
run: |
set -euo pipefail
cargo test --manifest-path crates/Cargo.toml -j 4 -p qbz-qt --no-fail-fast
cargo build --manifest-path crates/Cargo.toml -j 4 -p qbz-qt
python3 scripts/qt-cargo.py test --manifest-path crates/Cargo.toml -j 4 -p qbz-qt --no-fail-fast
python3 scripts/qt-cargo.py build --manifest-path crates/Cargo.toml -j 4 -p qbz-qt
# The Linux gate isolates with private XDG dirs and a private session
# bus. Windows needs neither a bus (the single instance is a named mutex)
+2 -2
View File
@@ -132,7 +132,7 @@ jobs:
uses: Swatinem/rust-cache@v2
with:
workspaces: crates -> target
shared-key: qt-macos-${{ matrix.target }}
shared-key: qt-macos-${{ matrix.target }}-${{ env.QT_VERSION }}
cache-on-failure: true
save-if: ${{ github.ref == 'refs/heads/main' || github.ref == 'refs/heads/pre-release' }}
@@ -145,7 +145,7 @@ jobs:
CXXFLAGS: ${{ matrix.cxxflags }}
MACOSX_DEPLOYMENT_TARGET: "12.0"
run: |
cargo build --release --manifest-path crates/Cargo.toml \
python3 scripts/qt-cargo.py build --release --manifest-path crates/Cargo.toml \
-p qbz-qt --target ${{ matrix.target }}
otool -l "crates/target/${{ matrix.target }}/release/qbz" | grep -A4 LC_BUILD_VERSION | grep minos
+2 -2
View File
@@ -240,7 +240,7 @@ jobs:
uses: Swatinem/rust-cache@v2
with:
workspaces: crates -> target
shared-key: qt-windows-x86_64
shared-key: qt-windows-x86_64-${{ env.QT_VERSION }}
cache-on-failure: true
save-if: ${{ github.ref == 'refs/heads/main' || github.ref == 'refs/heads/pre-release' }}
@@ -260,7 +260,7 @@ jobs:
# the link and let the PDB carry them.
CARGO_PROFILE_RELEASE_STRIP: "none"
run: |
cargo build --release --manifest-path crates/Cargo.toml \
python3 scripts/qt-cargo.py build --release --manifest-path crates/Cargo.toml \
-p qbz-qt --target "$TARGET"
ls -la "crates/target/$TARGET/release/qbz.exe" "crates/target/$TARGET/release/qbz.pdb"
+14 -19
View File
@@ -14,14 +14,16 @@
# consecutive-log repetition regression checks. ~5 min cold.
# qt-gate — the Qt frontend: the five static QML audits, `cargo test -p
# qbz-qt`, the Slint-free dep-graph gate, and an OFFSCREEN BOOT of
# the debug binary. This is the thing `cargo check` cannot give:
# debug AND release binaries (including process liveness).
# This is the thing `cargo check` cannot give:
# a missing QML component or a call to a bridge member that does
# not exist compiles clean and throws when the user opens the
# view. Qt comes from aqt — ubuntu-24.04's own Qt is 6.4.2 and has
# no QtQuick.Effects module.
#
# Rewritten 2026-08-25 for the Slint -> Qt frontend switch. Release builds stay
# tag/dispatch-only; this is the one workflow that runs on pre-release
# Rewritten 2026-08-25 for the Slint -> Qt frontend switch. Release packaging
# stays tag/dispatch-only; this workflow also tests optimized startup on
# pre-release
# integration so regressions land before a release cut.
name: test-crates
@@ -34,6 +36,9 @@ on:
paths:
- "crates/**"
- "scripts/cargo-test.sh"
- "scripts/qt-*.py"
- "scripts/qt-*.sh"
- "scripts/test_qt_build_gates.py"
- "scripts/qml-audits/**"
- ".github/workflows/test-crates.yml"
push:
@@ -42,6 +47,9 @@ on:
paths:
- "crates/**"
- "scripts/cargo-test.sh"
- "scripts/qt-*.py"
- "scripts/qt-*.sh"
- "scripts/test_qt_build_gates.py"
- "scripts/qml-audits/**"
- ".github/workflows/test-crates.yml"
workflow_dispatch:
@@ -181,14 +189,14 @@ jobs:
uses: Swatinem/rust-cache@v2
with:
workspaces: crates -> target
shared-key: qt-gate
shared-key: qt-gate-${{ env.QT_VERSION }}
cache-on-failure: true
save-if: ${{ github.ref == 'refs/heads/pre-release' }}
# The exact QT=1 half of scripts/cargo-test.sh, minus its `test` job
# (already run above) and its shader gate (the shader-gate job, so qsb
# is never on PATH while cargo runs here): dep-graph gate, cargo test
# -p qbz-qt, offscreen boot. Kept in the script so local == CI.
# -p qbz-qt, debug/release offscreen boot. One shared runtime script.
- name: qt gates (scripts/cargo-test.sh QT=1, without the workspace test)
env:
CARGO_TERM_COLOR: always
@@ -199,17 +207,4 @@ jobs:
hits=$(cargo tree --manifest-path crates/Cargo.toml -p qbz-qt -e normal \
| grep -E '\b(slint|qbz-ui|qbz-slint-common|qbz-dac-wizard) v' || true)
[ -z "$hits" ] || { echo "::error::qbz-qt graph resolves Slint crates:"; echo "$hits"; exit 1; }
cargo test --manifest-path crates/Cargo.toml -p qbz-qt --no-fail-fast
cargo build --manifest-path crates/Cargo.toml -p qbz-qt
# Same isolation as scripts/cargo-test.sh: private XDG dirs + a
# private session bus (the single-instance lock is a D-Bus name).
iso="$(mktemp -d)"
XDG_CONFIG_HOME="$iso/config" XDG_DATA_HOME="$iso/data" XDG_CACHE_HOME="$iso/cache" XDG_STATE_HOME="$iso/state" \
QT_QPA_PLATFORM=offscreen RUST_LOG=info dbus-run-session -- timeout 75 ./crates/target/debug/qbz > smoke.log 2>&1 || true
lines=$(wc -l < smoke.log); echo "smoke log: $lines lines"
if (( lines < 10 )); then cat smoke.log; echo "::error::the app did not start"; exit 1; fi
pat='is not a type|unavailable|ReferenceError|TypeError|Cannot read|Unable to assign|Cannot open|no such method|non-existent property|failed to load component|is not installed'
errs=$(grep -av 'propertyCache' smoke.log | grep -aciE "$pat" || true)
if (( errs > 0 )); then grep -av 'propertyCache' smoke.log | grep -aiE "$pat" | head -20; echo "::error::$errs QML complaint(s)"; exit 1; fi
grep -aq 'QbzCore initialized' smoke.log || { tail -20 smoke.log; echo "::error::never reached QbzCore init"; exit 1; }
echo "smoke OK (0 QML complaints, core initialized)"
bash scripts/qt-runtime-gate.sh
+12 -2
View File
@@ -502,6 +502,7 @@ crate is `qbz-qt`, which builds a binary called `qbz`.
- **Qt 6.8 or newer**, including its development headers *and* the private
headers (`<rhi/qrhi.h>` lives in Qt's private tree and the custom scene-graph
items need it).
- **Python 3**, for the Qt SDK cache guard and QML audits.
- Linux or macOS with audio support.
- No Node.js/npm required.
@@ -510,7 +511,7 @@ crate is `qbz-qt`, which builds a binary called `qbz`.
**Debian / Ubuntu:**
```bash
sudo apt install build-essential pkg-config cmake clang libclang-dev nasm \
sudo apt install build-essential pkg-config cmake clang libclang-dev nasm python3 \
qt6-base-dev qt6-base-private-dev \
qt6-declarative-dev qt6-declarative-private-dev \
qt6-shadertools-dev \
@@ -536,7 +537,7 @@ without any `PATH` fiddling.
```bash
git clone https://github.com/vicrodh/qbz.git && cd qbz
cargo build --release --manifest-path crates/Cargo.toml -p qbz-qt
NORUN=1 ./scripts/qt-run.sh
./crates/target/release/qbz
```
@@ -564,6 +565,15 @@ JOBS=4 ./scripts/qt-run.sh # cargo build jobs
It works on Linux and macOS.
Qt builds use `scripts/qt-cargo.py` to include the installed SDK's header
contents in the native build cache. This prevents mixing stale C++ objects
with new Qt headers after a system update, without deleting `target/` or
changing Rust optimization flags. For custom Cargo commands, use
`python3 scripts/qt-cargo.py build --release --manifest-path crates/Cargo.toml -p qbz-qt`
(or `test` instead of `build`). On Linux, the smoke uses an isolated profile
and private D-Bus session, and fails on early exits, including segmentation
faults. The CI runtime gate checks both debug and release.
### Nix / NixOS
`flake.nix` builds the same binary via `rustPlatform.buildRustPackage` with the
+2 -2
View File
@@ -47,7 +47,7 @@ die() { say "ERROR: $*" >&2; exit 1; }
# Build deps for the Qt `qbz` binary — the same list as build-qt-linux.yml
# minus what aqt provides there (here the distro's Qt provides it).
DEPS=(
build-essential pkg-config cmake clang libclang-dev nasm curl
build-essential pkg-config cmake clang libclang-dev nasm curl python3
libasound2-dev libjack-jackd2-dev libdbus-1-dev libssl-dev
libgl1-mesa-dev libegl1-mesa-dev libxkbcommon-dev
qt6-base-dev qt6-base-private-dev
@@ -89,7 +89,7 @@ case "$arch" in
else jobs="$(nproc)"; fi
say "RAM ${mem_mb} MB -> CARGO_BUILD_JOBS=${jobs}"
# No RUSTFLAGS, no mold, stable: same cache rule as qt-run.sh.
( cd crates && CARGO_BUILD_JOBS="$jobs" CARGO_INCREMENTAL=0 cargo build --release -p qbz-qt )
CARGO_BUILD_JOBS="$jobs" CARGO_INCREMENTAL=0 python3 scripts/qt-cargo.py build --release --manifest-path crates/Cargo.toml -p qbz-qt
install -Dm755 "crates/target/release/qbz" "$OUT"
;;
x86_64 | amd64)
+8 -29
View File
@@ -30,9 +30,9 @@
# 2. the shader bake gate with the qsb on PATH (CI: the pinned aqt qsb)
# 3. the Slint-free dep-graph gate for qbz-qt
# 4. cargo test -p qbz-qt (debug)
# 5. an offscreen boot of the debug binary: >= 10 log lines, zero QML
# complaints, QbzCore initialized (the login screen; `home published`
# needs a session CI does not have)
# 5. offscreen boots of BOTH debug and release: zero QML complaints,
# QbzCore initialized, and process still alive at the deadline.
# Native Qt SDK content participates in the C++ dependency cache.
#
# Usage:
# ./scripts/cargo-test.sh # job `test`
@@ -45,6 +45,9 @@ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"
say() { printf '[cargo-test] %s\n' "$*"; }
say "gate: native Qt SDK cache and crash-aware smoke regressions"
python3 scripts/test_qt_build_gates.py
say "gate: all eight gettext catalogs"
for locale in en es de fr pt ru ja nl; do
msgfmt --check --output-file=/dev/null "crates/qbz-i18n/translations/$locale/LC_MESSAGES/qbz-ui.po"
@@ -129,30 +132,6 @@ hits=$(cargo tree --manifest-path crates/Cargo.toml -p qbz-qt -e normal \
| grep -E '\b(slint|qbz-ui|qbz-slint-common|qbz-dac-wizard) v' || true)
[[ -z "$hits" ]] || { echo "qbz-qt graph resolves Slint crates:"; echo "$hits"; exit 1; }
say "qt gate 4/5: cargo test -p qbz-qt (debug)"
# Match qt-gate: shader_bake_gate above proves compilation independently;
# the binary embeds the committed packs without mtime-driven rewrites.
export QBZ_PREBUILT_SHADERS=1
cargo test --manifest-path crates/Cargo.toml -p qbz-qt --no-fail-fast
say "qt gate 5/5: offscreen boot of the debug binary"
cargo build --manifest-path crates/Cargo.toml -p qbz-qt
target_dir="${CARGO_TARGET_DIR:-$ROOT/crates/target}"
log="$(mktemp "${TMPDIR:-/tmp}/qbz-test-smoke-XXXXXX")"
# Isolated: its own XDG dirs (never the developer's config/session) and a
# PRIVATE session bus — the single-instance lock is a D-Bus well-known name,
# so a running QBZ would otherwise make this instance present-and-exit with
# one log line. CI has no other instance; the same command keeps both equal.
iso="$(mktemp -d "${TMPDIR:-/tmp}/qbz-test-xdg-XXXXXX")"
bus=(); command -v dbus-run-session >/dev/null && bus=(dbus-run-session --)
XDG_CONFIG_HOME="$iso/config" XDG_DATA_HOME="$iso/data" XDG_CACHE_HOME="$iso/cache" XDG_STATE_HOME="$iso/state" \
QT_QPA_PLATFORM=offscreen RUST_LOG=info "${bus[@]}" timeout 75 "$target_dir/debug/qbz" > "$log" 2>&1 || true
rm -rf "$iso"
lines=$(wc -l < "$log")
(( lines >= 10 )) || { cat "$log"; echo "smoke: the app did not start ($lines lines)"; exit 1; }
pat='is not a type|unavailable|ReferenceError|TypeError|Cannot read|Unable to assign|Cannot open|no such method|non-existent property|failed to load component|is not installed'
errs=$(grep -av 'propertyCache' "$log" | grep -aciE "$pat" || true)
if (( errs > 0 )); then grep -av 'propertyCache' "$log" | grep -aiE "$pat" | head -20; echo "smoke: $errs QML complaint(s) — $log"; exit 1; fi
grep -aq 'QbzCore initialized' "$log" || { tail -20 "$log"; echo "smoke: never reached QbzCore init — $log"; exit 1; }
say "smoke OK (0 QML complaints, core initialized)"
say "qt gates 4/5 + 5/5: tests and debug/release startup liveness"
bash scripts/qt-runtime-gate.sh
say "done"
+129
View File
@@ -0,0 +1,129 @@
#!/usr/bin/env python3
"""Run Cargo with the *native* Qt SDK included in cc-rs's cache inputs.
Cargo does not discover changes to system C++ headers. In particular, an
in-place Qt update can leave cxx-qt-lib built with old inline templates while
qbz-qt uses new ones. The linker coalesces their identically named symbols;
this caused the QList<float> startup SIGSEGV on 2026-09-06.
Use this entry point for Qt builds/tests, including direct Cargo invocations:
python3 scripts/qt-cargo.py build --release --manifest-path crates/Cargo.toml -p qbz-qt
No target cleanup, profile changes, or RUSTFLAGS: a content-derived, unused
C++ define invalidates cc-rs consumers when the SDK changes, in either profile
and with any Rust toolchain. Existing CXXFLAGS (including MSVC flags) survive.
"""
import hashlib
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
def query(qmake, name):
return subprocess.check_output(
[qmake, "-query", name], text=True, stderr=subprocess.PIPE, timeout=15
).strip()
def find_qmake(env):
explicit = env.get("QMAKE")
candidates = [explicit] if explicit else ["qmake6", "qmake"]
for candidate in candidates:
executable = shutil.which(candidate, path=env.get("PATH"))
if executable:
version = query(executable, "QT_VERSION")
if re.fullmatch(r"6\.\d+\.\d+(?:[-+].*)?", version):
# Keep argv[0]: qmake may be a qtchooser symlink.
return os.path.abspath(executable), version
raise RuntimeError("Qt 6 qmake not found; set QMAKE to the intended SDK's qmake")
def header_files(root, modules_only=False):
# Homebrew SDKs can expose headers through directory symlinks. Follow
# them, but visit each real directory once so a cyclic link cannot hang.
seen = set()
for directory, dirs, files in os.walk(root, followlinks=True, onerror=raise_error):
if modules_only and Path(directory) == root:
# Homebrew can report /opt/homebrew/include, not a Qt-only root.
dirs[:] = [name for name in dirs if name.startswith("Qt")]
files = [name for name in files if name.startswith("Qt")]
real = Path(directory).resolve()
if real in seen:
dirs[:] = []
continue
seen.add(real)
dirs.sort()
for name in sorted(files):
yield Path(directory) / name
def raise_error(error):
raise error
def sdk_fingerprint(qmake, version):
headers = Path(query(qmake, "QT_INSTALL_HEADERS"))
libraries = Path(query(qmake, "QT_INSTALL_LIBS"))
digest = hashlib.sha256()
# Paths are intentional: switching SDK roots must also rebuild native
# archives and their recorded linker search paths.
for value in ("qbz-qt-sdk-v1", qmake, version, str(headers.resolve()),
str(libraries)):
digest.update(value.encode() + b"\0")
count = 0
def sdk_headers():
if headers.is_dir():
for path in header_files(headers, modules_only=True):
yield str(path.relative_to(headers)), path
# cxx-qt-build also consumes these. Homebrew's qmake may point at a
# shared include root with NO QtCore subdir; its real headers live in
# QT_INSTALL_LIBS/QtCore.framework/Headers instead.
for framework in sorted(libraries.glob("Qt*.framework")):
root = framework / "Headers"
if root.is_dir():
for path in header_files(root):
yield f"frameworks/{framework.name}/Headers/{path.relative_to(root)}", path
for name, path in sdk_headers():
digest.update(name.encode() + b"\0")
content = path.read_bytes()
digest.update(len(content).to_bytes(8, "big"))
digest.update(content)
count += 1
if not count:
raise RuntimeError(f"Qt headers are missing or empty: {headers}, {libraries}")
return digest.hexdigest()[:32]
def cargo_environment(env):
result = dict(env)
qmake, version = find_qmake(result)
fingerprint = sdk_fingerprint(qmake, version)
# cc-rs tracks and appends CXXFLAGS even with target-specific flags.
# Remove only our own previous marker, making nested invocations stable.
flags = re.sub(r"(?:^|\s)-DQBZ_QT_SDK_[0-9a-f]{32}=1(?=\s|$)", "",
result.get("CXXFLAGS", "")).strip()
result["CXXFLAGS"] = f"{flags} -DQBZ_QT_SDK_{fingerprint}=1".strip()
result["QMAKE"] = qmake
return result, version, fingerprint
def main():
if len(sys.argv) < 2:
raise RuntimeError("usage: qt-cargo.py <cargo subcommand> [arguments...]")
env, version, fingerprint = cargo_environment(os.environ)
print(f"[qt-cargo] Qt {version}, SDK {fingerprint}, qmake={env['QMAKE']}",
file=sys.stderr, flush=True)
os.execvpe("cargo", ["cargo", *sys.argv[1:]], env)
if __name__ == "__main__":
try:
main()
except (OSError, RuntimeError, subprocess.SubprocessError) as error:
print(f"[qt-cargo] {error}", file=sys.stderr)
sys.exit(1)
+9 -4
View File
@@ -127,7 +127,7 @@ if [[ "${DEBUG:-0}" == 1 ]]; then
else
PROFILE=release; PROFILE_ARGS=(--release)
fi
BIN="crates/target/${PROFILE}/qbz"
BIN="${CARGO_TARGET_DIR:-crates/target}/${PROFILE}/qbz"
# --- ONE BUILD AT A TIME, BOX-WIDE ------------------------------------------
# Not paranoia: a Slint `qbz-ui` rustc in another worktree peaks 20-30 GB on a
@@ -230,7 +230,7 @@ if [[ "${NO_TICKER:-0}" != 1 ]] && [[ -t 2 ]]; then
fi
# --- The build ---------------------------------------------------------------
cargo build "${PROFILE_ARGS[@]}" --manifest-path crates/Cargo.toml -p qbz-qt
python3 scripts/qt-cargo.py build "${PROFILE_ARGS[@]}" --manifest-path crates/Cargo.toml -p qbz-qt
# --- Stop the ticker, record the duration, print the final banner ------------
[[ -n "${tick_pid}" ]] && { kill "${tick_pid}" 2>/dev/null || true; wait "${tick_pid}" 2>/dev/null || true; }
@@ -243,7 +243,7 @@ printf '%s[qt-run] ✔ build finished %s · took %s (%s)%s\n' \
# --- Tests (opt-in) ----------------------------------------------------------
if [[ "${TEST:-0}" == 1 ]]; then
say "running cargo test -p qbz-qt"
cargo test --manifest-path crates/Cargo.toml -p qbz-qt
python3 scripts/qt-cargo.py test --manifest-path crates/Cargo.toml -p qbz-qt
fi
# --- Offscreen smoke gate (opt-in) -------------------------------------------
@@ -251,6 +251,11 @@ fi
# and prove the QML tree actually resolves. A lazily-resolved type error only
# ever shows up here or in front of the owner.
if [[ "${SMOKE:-0}" == 1 ]]; then
if [[ "${UNAME_S}" == "Linux" ]]; then
log="$(mktemp "${TMPDIR:-/tmp}/qbz-qt-smoke-XXXXXX")"
python3 scripts/qt-smoke.py "${BIN}" --log "${log}"
exit 0
fi
# BSD mktemp -t takes a bare prefix, GNU takes a template; give both a full
# template path so the two agree.
log="$(mktemp "${TMPDIR:-/tmp}/qbz-qt-smoke-XXXXXX")"
@@ -288,4 +293,4 @@ fi
# exec the binary directly — no `cargo run`, so no CARGO_* env / cargo context,
# so process monitors show `qbz-qt` rather than `cargo`.
exec "./${BIN}" "$@"
exec "${BIN}" "$@"
+15
View File
@@ -0,0 +1,15 @@
#!/usr/bin/env bash
# Shared Linux CI/local runtime gate. Serial builds, no personal profile.
set -euo pipefail
cd "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/.."
export QBZ_PREBUILT_SHADERS=1
python3 scripts/qt-cargo.py test --manifest-path crates/Cargo.toml -p qbz-qt --no-fail-fast
target_dir="${CARGO_TARGET_DIR:-$PWD/crates/target}"
logs="$(mktemp -d "${TMPDIR:-/tmp}/qbz-qt-gate-XXXXXX")"
printf '[qt-gate] startup logs: %s\n' "$logs"
for profile in debug release; do
args=()
[[ "$profile" == release ]] && args=(--release)
python3 scripts/qt-cargo.py build "${args[@]}" --manifest-path crates/Cargo.toml -p qbz-qt
python3 scripts/qt-smoke.py "$target_dir/$profile/qbz" --log "$logs/$profile.log"
done
+123
View File
@@ -0,0 +1,123 @@
#!/usr/bin/env python3
"""Bounded, isolated startup gate; surviving until the deadline is required.
The process must both initialize QbzCore and remain alive for the observation
window. Never turn a SIGSEGV (or a single-instance early exit) into a green
gate just because the log contains a success marker.
"""
import argparse
import os
from pathlib import Path
import re
import shutil
import signal
import subprocess
import sys
import tempfile
QML_ERROR = re.compile(
r"is not a type|unavailable|ReferenceError|TypeError|Cannot read|"
r"Unable to assign|Cannot open|no such method|non-existent property|"
r"failed to load component|is not installed", re.IGNORECASE
)
def check_result(output, survived, returncode):
if not survived:
raise RuntimeError(f"process exited before the smoke deadline (status {returncode})")
# A child may fault just as its dbus-run-session parent reaches the
# timeout. Do not accept a reported crash as our intentional shutdown.
if returncode not in (0, -signal.SIGTERM, 128 + signal.SIGTERM,
-signal.SIGKILL, 128 + signal.SIGKILL):
raise RuntimeError(f"unexpected process exit status {returncode}")
lines = output.splitlines()
if len(lines) < 10:
raise RuntimeError(f"app produced only {len(lines)} log lines")
complaints = [line for line in lines if "propertyCache" not in line and QML_ERROR.search(line)]
if complaints:
raise RuntimeError("QML complaints:\n" + "\n".join(complaints[:20]))
if "QbzCore initialized" not in output:
raise RuntimeError("app never reached QbzCore initialization")
def smoke(binary, seconds, log):
if seconds <= 0:
raise RuntimeError("observation window must be positive")
command = [str(Path(binary).resolve())]
if sys.platform.startswith("linux"):
bus = shutil.which("dbus-run-session")
if not bus:
raise RuntimeError("dbus-run-session is required for an isolated Linux smoke")
command = [bus, "--", *command]
with tempfile.TemporaryDirectory(prefix="qbz-smoke-") as directory:
root = Path(directory)
env = dict(os.environ)
# Do not inherit the developer's renderer overrides or session bus.
for name in ("DISPLAY", "WAYLAND_DISPLAY", "DBUS_SESSION_BUS_ADDRESS",
"DBUS_SESSION_BUS_PID", "QBZ_RENDERER", "QT_QUICK_BACKEND",
"QSG_RHI_BACKEND"):
env.pop(name, None)
for name, folder in (("XDG_CONFIG_HOME", "config"), ("XDG_DATA_HOME", "data"),
("XDG_CACHE_HOME", "cache"), ("XDG_STATE_HOME", "state"),
("XDG_RUNTIME_DIR", "run")):
path = root / folder
path.mkdir(mode=0o700)
env[name] = str(path)
env.update(QT_QPA_PLATFORM="offscreen", RUST_LOG="info")
# dirs::data_dir ignores XDG on macOS/Windows. This helper deliberately
# refuses there until native profile isolation is implemented.
if not sys.platform.startswith("linux"):
raise RuntimeError("isolated qt-smoke.py currently supports Linux only")
# A deliberately crashing regression binary must not leave a huge
# core dump in the checkout. This limit is private to the helper and
# its children, not a system setting.
import resource
resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
with open(log, "wb") as output:
process = subprocess.Popen(command, env=env, stdout=output,
stderr=subprocess.STDOUT, start_new_session=True)
survived = False
try:
process.wait(timeout=seconds)
except subprocess.TimeoutExpired:
survived = process.poll() is None
finally:
# Kill/reap the entire *private* session, including D-Bus.
try:
os.killpg(process.pid, signal.SIGTERM)
except ProcessLookupError:
pass
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL)
process.wait(timeout=5)
check_result(Path(log).read_text(errors="replace"), survived, process.returncode)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("binary")
# Keep the existing CI's 75s budget: first-run bundle discovery is async
# network work and can legitimately outlast 30s before core init logs.
parser.add_argument("--seconds", type=float, default=75)
parser.add_argument("--log", required=True)
args = parser.parse_args()
try:
smoke(args.binary, args.seconds, args.log)
except (OSError, RuntimeError, subprocess.SubprocessError):
if Path(args.log).is_file():
print(f"Last startup messages — {args.log}:", file=sys.stderr)
print("\n".join(Path(args.log).read_text(errors="replace").splitlines()[-30:]),
file=sys.stderr)
raise
print(f"smoke OK: core initialized, process survived {args.seconds:g}s — {args.log}")
if __name__ == "__main__":
try:
main()
except (OSError, RuntimeError, subprocess.SubprocessError) as error:
print(f"smoke FAILED: {error}", file=sys.stderr)
sys.exit(1)
+168
View File
@@ -0,0 +1,168 @@
#!/usr/bin/env python3
"""SDK-cache and crash-aware smoke regressions; no Qt or Cargo build needed."""
import importlib.util
import os
from pathlib import Path
import tempfile
import unittest
import sys
from unittest.mock import patch
sys.dont_write_bytecode = True
def load(name, filename):
spec = importlib.util.spec_from_file_location(name, Path(__file__).with_name(filename))
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
qt = load("qt_cargo", "qt-cargo.py")
smoke = load("qt_smoke", "qt-smoke.py")
class SdkTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.headers = self.root / "include" / "QtCore"
self.headers.mkdir(parents=True)
self.header = self.headers / "qarraydataops.h"
self.header.write_text("old-layout")
self.answers = {"QT_VERSION": "6.11.2", "QT_INSTALL_HEADERS": str(self.headers.parent),
"QT_INSTALL_LIBS": str(self.root / "lib")}
mock = patch.object(qt, "query", side_effect=lambda _, key: self.answers[key])
mock.start()
self.addCleanup(mock.stop)
def fingerprint(self):
return qt.sdk_fingerprint("/sdk/bin/qmake", self.answers["QT_VERSION"])
def test_identical_headers_are_stable_after_touch(self):
before = self.fingerprint()
os.utime(self.header, None)
self.assertEqual(before, self.fingerprint())
def test_header_change_invalidates_even_with_same_version_size_and_mtime(self):
before = self.fingerprint()
stat = self.header.stat()
self.header.write_text("new-layout")
os.utime(self.header, ns=(stat.st_atime_ns, stat.st_mtime_ns))
self.assertNotEqual(before, self.fingerprint())
def test_patch_version_invalidates(self):
before = self.fingerprint()
self.answers["QT_VERSION"] = "6.11.3"
self.assertNotEqual(before, self.fingerprint())
def test_library_root_invalidates(self):
before = self.fingerprint()
self.answers["QT_INSTALL_LIBS"] = "/other-sdk/lib"
self.assertNotEqual(before, self.fingerprint())
def test_added_and_removed_headers_invalidate(self):
before = self.fingerprint()
extra = self.headers / "qnew.h"
extra.write_text("new type")
self.assertNotEqual(before, self.fingerprint())
extra.unlink()
self.assertEqual(before, self.fingerprint())
@unittest.skipIf(os.name == "nt", "unprivileged Windows symlinks may be unavailable")
def test_framework_symlink_and_cycle_are_bounded(self):
framework = self.root / "framework"
framework.mkdir()
header = framework / "qframework.h"
header.write_text("old")
(self.headers / "framework").symlink_to(framework, target_is_directory=True)
(framework / "cycle").symlink_to(self.headers, target_is_directory=True)
before = self.fingerprint()
header.write_text("new")
self.assertNotEqual(before, self.fingerprint())
def test_missing_sdk_fails_closed(self):
self.answers["QT_INSTALL_HEADERS"] = str(self.root / "missing")
with self.assertRaisesRegex(RuntimeError, "missing"):
self.fingerprint()
def test_empty_sdk_fails_closed(self):
self.header.unlink()
with self.assertRaisesRegex(RuntimeError, "empty"):
self.fingerprint()
def test_homebrew_framework_only_headers_are_hashed(self):
self.header.unlink()
headers = self.root / "lib" / "QtCore.framework" / "Headers"
headers.mkdir(parents=True)
header = headers / "qarraydataops.h"
header.write_text("old")
before = self.fingerprint()
header.write_text("new")
self.assertNotEqual(before, self.fingerprint())
def test_shared_include_root_ignores_non_qt_packages(self):
before = self.fingerprint()
unrelated = self.headers.parent / "other-package"
unrelated.mkdir()
(unrelated / "other.h").write_text("not part of Qt")
self.assertEqual(before, self.fingerprint())
def test_existing_flags_survive_and_nested_calls_are_stable(self):
original = {"CXXFLAGS": "/Zc:__cplusplus /permissive- -include arm_acle.h",
"RUSTFLAGS": "-C link-arg=-fuse-ld=lld", "CARGO_TARGET_DIR": "/cache"}
with patch.object(qt, "find_qmake", return_value=("/sdk/bin/qmake", "6.11.2")):
env, _, _ = qt.cargo_environment(original)
again, _, _ = qt.cargo_environment(env)
self.assertEqual(env, again)
self.assertTrue(env["CXXFLAGS"].startswith(original["CXXFLAGS"] + " "))
self.assertEqual(env["RUSTFLAGS"], original["RUSTFLAGS"])
self.assertEqual(env["CARGO_TARGET_DIR"], "/cache")
self.assertNotIn("QMAKE", original)
def test_broken_explicit_qmake_does_not_fall_back(self):
with patch.object(qt.shutil, "which", return_value=None) as which:
with self.assertRaises(RuntimeError):
qt.find_qmake({"QMAKE": "/missing/sdk/qmake"})
which.assert_called_once_with("/missing/sdk/qmake", path=None)
class SmokeTests(unittest.TestCase):
output = "QbzCore initialized\n" + "normal startup log\n" * 10
def test_success_requires_liveness(self):
smoke.check_result(self.output, True, -15)
def test_early_exit_is_never_green_even_after_success_marker(self):
for status in (0, 1, 139, -11, -6):
with self.subTest(status=status), self.assertRaisesRegex(RuntimeError, "exited"):
smoke.check_result(self.output, False, status)
def test_crash_at_deadline_is_not_our_intentional_shutdown(self):
for status in (139, -11, 134, -6, 1):
with self.subTest(status=status), self.assertRaisesRegex(RuntimeError, "status"):
smoke.check_result(self.output, True, status)
def test_silent_hang_is_not_startup(self):
with self.assertRaises(RuntimeError):
smoke.check_result("", True, -15)
def test_missing_core_marker_fails(self):
with self.assertRaisesRegex(RuntimeError, "initialization"):
smoke.check_result("log\n" * 12, True, -15)
def test_qml_error_after_init_fails(self):
with self.assertRaisesRegex(RuntimeError, "QML complaints"):
smoke.check_result(self.output + "ReferenceError: missing binding", True, -15)
def test_known_property_cache_warning_does_not_hide_real_error(self):
warning = "qt.qml.propertyCache: has no property\n"
smoke.check_result(self.output + warning, True, -15)
with self.assertRaises(RuntimeError):
smoke.check_result(self.output + warning + "TypeError: broken", True, -15)
if __name__ == "__main__":
unittest.main()