From 0bc64147296b8094445be2c093ee99fd8b332ac8 Mon Sep 17 00:00:00 2001 From: knqiufan Date: Thu, 5 Nov 2026 01:00:40 +0800 Subject: [PATCH 1/8] build(desktop): assemble versioned release candidates --- .github/workflows/desktop-candidate.yml | 216 +++++++++ .../development/desktop-candidate-assembly.md | 46 ++ .../development/desktop-candidate-assembly.md | 46 ++ scripts/desktop_candidate.py | 437 ++++++++++++++++++ tests/test_desktop_candidate.py | 250 ++++++++++ 5 files changed, 995 insertions(+) create mode 100644 .github/workflows/desktop-candidate.yml create mode 100644 docs/en/development/desktop-candidate-assembly.md create mode 100644 docs/zh/development/desktop-candidate-assembly.md create mode 100644 scripts/desktop_candidate.py create mode 100644 tests/test_desktop_candidate.py diff --git a/.github/workflows/desktop-candidate.yml b/.github/workflows/desktop-candidate.yml new file mode 100644 index 0000000000..58e617841b --- /dev/null +++ b/.github/workflows/desktop-candidate.yml @@ -0,0 +1,216 @@ +name: Desktop candidate assembly + +on: + pull_request: + paths: + - '.github/workflows/desktop-candidate.yml' + - 'scripts/desktop_candidate.py' + - 'tests/test_desktop_candidate.py' + workflow_dispatch: + inputs: + version: + description: 'Desktop version (X.Y.Z); derives desktop-vX.Y.Z' + required: true + type: string + server_version: + description: 'Exact canonical Python Server package version to build' + required: true + type: string + source_sha: + description: 'Full Desktop commit SHA; must match the selected master revision' + required: true + type: string + server_source_sha: + description: 'Full Server source commit SHA; may be an earlier qualified revision' + required: true + type: string + +permissions: + contents: read + +run-name: Desktop candidate ${{ inputs.version || 'validation' }} · ${{ inputs.source_sha || github.sha }} + +jobs: + contract: + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + - uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2 + with: + version: '0.13.5' + - run: uv sync --locked --no-dev --group resource-build --python 3.12 + - name: Verify candidate handoff + run: | + uv run --no-sync ruff check scripts/desktop_candidate.py tests/test_desktop_candidate.py + uv run --no-sync ruff format --check scripts/desktop_candidate.py tests/test_desktop_candidate.py + uv run --no-sync ty check scripts/desktop_candidate.py tests/test_desktop_candidate.py + uv run --no-sync pytest -q tests/test_desktop_candidate.py + + native: + if: github.event_name == 'workflow_dispatch' && github.repository == 'oceanbase/powercontext' && github.ref == 'refs/heads/master' + needs: contract + name: Build candidate for ${{ matrix.target }} + strategy: + fail-fast: false + max-parallel: 2 + matrix: + include: + - target: windows-x86_64 + runner: windows-2025 + triple: x86_64-pc-windows-msvc + - target: macos-arm64 + runner: macos-15 + triple: aarch64-apple-darwin + - target: macos-x86_64 + runner: macos-15-intel + triple: x86_64-apple-darwin + runs-on: ${{ matrix.runner }} + timeout-minutes: 120 + defaults: + run: + shell: bash + env: + DESKTOP_VERSION: ${{ inputs.version }} + SERVER_VERSION: ${{ inputs.server_version }} + SOURCE_SHA: ${{ inputs.source_sha }} + SERVER_SOURCE_SHA: ${{ inputs.server_source_sha }} + RESOURCE_TARGET: ${{ matrix.target }} + RUST_TARGET: ${{ matrix.triple }} + # Producer provenance hashes the checked-out scripts as bytes on Windows too. + GIT_CONFIG_COUNT: '1' + GIT_CONFIG_KEY_0: core.autocrlf + GIT_CONFIG_VALUE_0: 'false' + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + fetch-depth: 0 + persist-credentials: false + - uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2 + with: + version: '0.13.5' + enable-cache: true + - name: Verify exact source and version before building + run: | + uv sync --locked --no-dev --group resource-build --python 3.12 --no-build-package cryptography --no-build-package jieba + uv run --no-sync python scripts/desktop_candidate.py identity \ + --version "$DESKTOP_VERSION" --server-version "$SERVER_VERSION" --source-sha "$SOURCE_SHA" --server-source-sha "$SERVER_SOURCE_SHA" + - name: Select pinned compiler for Intel resource production + if: matrix.target == 'macos-x86_64' + run: echo 'DEVELOPER_DIR=/Applications/Xcode_16.4.app/Contents/Developer' >> "$GITHUB_ENV" + - name: Produce and smoke-test the pinned 09-C resources + run: | + uv run --no-sync python scripts/prepare_managed_resources.py \ + --target "$RESOURCE_TARGET" --source-ref "$SERVER_SOURCE_SHA" --server-version "$SERVER_VERSION" \ + --output build/resource-inputs --download-cache build/resource-downloads + inputs_sha="$(uv run --no-sync python -c 'import hashlib; from pathlib import Path; print(hashlib.sha256(Path("build/resource-inputs/inputs.json").read_bytes()).hexdigest())')" + uv run --no-sync python scripts/produce_managed_resources.py \ + --inputs build/resource-inputs --inputs-sha256 "$inputs_sha" \ + --server-url "https://candidate.invalid/$RESOURCE_TARGET/server.tar.gz" --output build/resources + # The Ops child writes a separate diagnostic line before the final smoke receipt. + set -o pipefail + uv run --no-sync python scripts/ci_managed_resource_smoke.py \ + --candidate build/resources --serve --evidence-dir build/resource-evidence | tail -n 1 > build/resource-smoke.json + - name: Prepare exact catalog and provision pins for the Desktop build + run: | + uv run --no-sync python scripts/desktop_candidate.py prepare --resources build/resources \ + --version "$DESKTOP_VERSION" --server-version "$SERVER_VERSION" --source-sha "$SOURCE_SHA" --server-source-sha "$SERVER_SOURCE_SHA" + - uses: jdx/mise-action@8418fedb1110381a0d3ba51a7a415d7c1b884550 # v5.2.2 + with: + working_directory: desktop + - name: Install pinned Rust target + run: rustup toolchain install "1.95.0-$RUST_TARGET" --profile minimal + - name: Build the unsigned product configuration + working-directory: desktop + run: | + pnpm install --frozen-lockfile + # Fresh target directory, default product features and no signing secrets or updater artifacts. + test ! -e src-tauri/target + pnpm tauri build --target "$RUST_TARGET" --ci --no-sign \ + --config src-tauri/tauri.ops.conf.json --config .artifacts/candidate.conf.json -- --locked + - name: Collect the normal package and exact producer outputs + run: | + uv run --no-sync python scripts/desktop_candidate.py stage \ + --version "$DESKTOP_VERSION" --server-version "$SERVER_VERSION" --source-sha "$SOURCE_SHA" --server-source-sha "$SERVER_SOURCE_SHA" \ + --target "$RESOURCE_TARGET" --bundles "desktop/src-tauri/target/$RUST_TARGET/release/bundle" \ + --inputs build/resource-inputs --resources build/resources --smoke build/resource-smoke.json \ + --output "build/legs/$RESOURCE_TARGET" + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: desktop-candidate-leg-${{ matrix.target }} + path: build/legs/${{ matrix.target }}/ + if-no-files-found: error + compression-level: 0 + retention-days: 7 + - name: Retain native smoke failure evidence + if: failure() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: desktop-candidate-diagnostics-${{ matrix.target }} + path: build/resource-evidence/ + if-no-files-found: ignore + retention-days: 7 + + assemble: + needs: native + runs-on: ubuntu-24.04 + timeout-minutes: 20 + env: + DESKTOP_VERSION: ${{ inputs.version }} + SERVER_VERSION: ${{ inputs.server_version }} + SOURCE_SHA: ${{ inputs.source_sha }} + SERVER_SOURCE_SHA: ${{ inputs.server_source_sha }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + fetch-depth: 0 + persist-credentials: false + - uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2 + with: + version: '0.13.5' + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + name: desktop-candidate-leg-windows-x86_64 + path: build/desktop-candidate/windows-x86_64 + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + name: desktop-candidate-leg-macos-arm64 + path: build/desktop-candidate/macos-arm64 + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + name: desktop-candidate-leg-macos-x86_64 + path: build/desktop-candidate/macos-x86_64 + - name: Validate required targets and freeze manifest + run: | + set -o pipefail + uv sync --locked --no-dev --group resource-build --python 3.12 + uv run --no-sync python scripts/desktop_candidate.py assemble \ + --version "$DESKTOP_VERSION" --server-version "$SERVER_VERSION" --source-sha "$SOURCE_SHA" --server-source-sha "$SERVER_SOURCE_SHA" \ + --root build/desktop-candidate | tee -a "$GITHUB_STEP_SUMMARY" + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + id: upload-candidate + with: + name: desktop-candidate-${{ inputs.version }}-${{ inputs.source_sha }} + path: build/desktop-candidate/ + if-no-files-found: error + compression-level: 0 + retention-days: 14 + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + id: upload-manifest + with: + name: desktop-candidate-manifest-${{ inputs.version }}-${{ inputs.source_sha }} + path: build/desktop-candidate/desktop-release-candidate.json + if-no-files-found: error + retention-days: 14 + - name: Record exact Actions artifact identities + env: + CANDIDATE_ARTIFACT_ID: ${{ steps.upload-candidate.outputs.artifact-id }} + MANIFEST_ARTIFACT_ID: ${{ steps.upload-manifest.outputs.artifact-id }} + run: | + { + echo "candidate_run_id=$GITHUB_RUN_ID" + echo "candidate_full_artifact_id=$CANDIDATE_ARTIFACT_ID" + echo "candidate_manifest_artifact_id=$MANIFEST_ARTIFACT_ID" + } >> "$GITHUB_STEP_SUMMARY" diff --git a/docs/en/development/desktop-candidate-assembly.md b/docs/en/development/desktop-candidate-assembly.md new file mode 100644 index 0000000000..f85ae46256 --- /dev/null +++ b/docs/en/development/desktop-candidate-assembly.md @@ -0,0 +1,46 @@ +--- +title: Desktop candidate assembly +description: Assemble exact, unqualified Desktop and managed resource candidates for Windows x64 and both macOS architectures. +--- + +# Desktop candidate assembly + +[Issue #2112](https://github.com/oceanbase/powercontext/issues/2112) separates candidate assembly, managed resource production, and publication. The **Desktop candidate assembly** workflow builds normal product packages and reuses the [managed resource producer](managed-resource-production.md). Its outputs are unsigned Actions artifacts for validation and handoff. They cannot be released or treated as installed qualification. + +## Build identity + +A release owner explicitly selects the upstream `master` revision and dispatches `desktop-candidate.yml` with: + +- `version`: exact Desktop `X.Y.Z`. The prospective tag is `desktop-vX.Y.Z`, independent of the Python release tag. The app package identity is `com.powercontext.desktop`. +- `server_version`: exact canonical Python Server package version (e.g. `1.5.1.dev25+g63e9665c6`), built from the pinned Server commit with the producer's locked runtime inputs. This version is independent of Desktop's version and is never inferred from a package index. +- `source_sha`: full Git commit, which must equal the workflow checkout. An existing Desktop tag may only refer to that same commit. Candidate assembly never creates a tag. +- `server_source_sha`: full Server commit. It can point to an earlier qualified Server revision. The wheel and its dependency lock come from that source; the Desktop build and the producer tools are still bound to `source_sha`. + +Desktop version parts are integers from 0 to 65535, without leading zeros. The workflow uses a fresh release build without `ci-fixtures`, with the producer's exact catalog and Ops pins. It requires Windows x64 (NSIS), macOS arm64 (DMG), and macOS x64 (DMG). Linux is omitted. A later opt-in Linux release needs separately qualified assets from [#2111](https://github.com/oceanbase/powercontext/issues/2111); no Linux job can hold this required aggregate. + +## Candidate handoff + +Download the single successful run's `desktop-candidate--` artifact. The required target jobs produce same-run inputs; the aggregate never accepts uploads from preview builds, fixture manifests, or another run. Output names are `powercontext-desktop--.exe` or `.dmg` under their respective target directory. Server and Ops archives, catalog, provision descriptor, input locks, producer manifests, the actual project wheel, and smoke evidence accompany each package. Target identifiers are `windows-x86_64`, `macos-arm64`, and `macos-x86_64`. + +`desktop-release-candidate.json` has `schema_version: 1`, `kind: desktop-product-candidate`, `version`, `release_tag`, `source_sha`, `server_source_sha`, `server_version`, `status: unqualified_candidate`, and `publishable: false`. `contract` records the exact Desktop HTTP contract digest and operation set, and the bundled operation and compatibility files. `targets` maps each target to `build_kind: product`, `assets`, `provenance`, `qualification`, and `runtime`. The four release roles in `assets` are `desktop`, `server_archive`, `server_catalog`, and `ops_archive`. Each file entry has a root-relative `name`, byte `size`, and lowercase `sha256`. Ops provision and bundle manifest files are in `provenance` with unique basenames per target. `qualification.producer_ref` is always an unqualified producer reference. `matching_product_records` lists only bundled records matching the actual Server wheel, source, contract and operation set; an empty list leaves product protocol qualification outstanding. Even a matching record does not qualify an installer. + +For publication handoff, select `desktop-candidate-manifest--`, which contains only the exact same `desktop-release-candidate.json`. The run summary records `candidate_run_id`, `candidate_full_artifact_id`, `candidate_manifest_artifact_id`, and `candidate_manifest_sha256`. Record the manifest artifact ID (as `candidate_artifact_id` in the publication handoff) so publication can retrieve the single file without downloading the large archives. Both Actions artifacts have a 14-day retention. + +To check the complete candidate, take the manifest SHA-256 from the trusted run summary and verify the downloaded files: + +```sh +uv run --locked --no-dev --group resource-build python scripts/desktop_candidate.py verify --root \ + --version --server-version --source-sha \ + --server-source-sha \ + --manifest-sha256 +``` + +The checksum binds the exact manifest and asset bytes. Trust still comes from selecting a successful run of this workflow on the intended upstream source. Record its run and artifact identity; a rerun can produce different bytes under the same human-readable name and cannot silently replace an accepted set. Candidate artifacts expire after 14 days; they are not an availability channel for installed clients. + +## Qualification before publication + +CI consumes the real catalog and archive, launches a disposable SQLite Server with bundled Python, and inspects local state with the independent Ops entry. This does not exercise a real HTTP download or register a service. The candidate catalog deliberately uses `candidate.invalid`. + +The final platform packagers own signed Windows x64 and signed/notarized macOS arm64/x64 builds and install the approved independent Ops helper at the [fixed current-user location](../docs/operate/local-server-ops.md#provisioning-the-bridge). Desktop removal must preserve the independent helper, service state, and user data. Windows must retain both `pythonw.exe` for the Server service and `python.exe` for console use. The candidate packages embed pins but do not install the independent helper. Provisioning the helper, clean-machine installation and repair, reboot/login and native service lifecycle are part of [#2108](https://github.com/oceanbase/powercontext/issues/2108) and [#2109](https://github.com/oceanbase/powercontext/issues/2109). + +When building the platform release, use the approved immutable resource URL and regenerate any affected inventory, archive, catalog, and provision digest after signing changes nested code. Embed the final pins before signing the outer Desktop package. Preserve the candidate manifest digest and record the separately qualified final package and resource digests; candidate bytes and signed bytes need not be identical. Final acceptance requires the same Desktop/Server combination to demonstrate identity, Scope and Memory, statistics, Runtime observation, and local setup through to the default Scope. Do not substitute a rebuilt wheel or a fixture for [#2101](https://github.com/oceanbase/powercontext/issues/2101) qualification. Publication and re-download verification consume the exact final signed and tested bytes. diff --git a/docs/zh/development/desktop-candidate-assembly.md b/docs/zh/development/desktop-candidate-assembly.md new file mode 100644 index 0000000000..0dcc7f62a1 --- /dev/null +++ b/docs/zh/development/desktop-candidate-assembly.md @@ -0,0 +1,46 @@ +--- +title: 桌面端候选组装 +description: 为 Windows x64 和两种 macOS 架构组装身份固定、尚未取得发布资格的桌面端和受管资源候选。 +--- + +# 桌面端候选组装 + +[Issue #2112](https://github.com/oceanbase/powercontext/issues/2112) 将候选组装、受管资源生产和发布拆开。**Desktop candidate assembly** 工作流使用正常产品配置打包,并复用[受管资源生产器](managed-resource-production.md)。输出是供检查和交接的未签名 Actions 构件,不能作为正式发布件,也不能证明已通过安装验收。 + +## 构建身份 + +发布负责人在上游明确选择 `master` 提交,手动触发 `desktop-candidate.yml`,并提供: + +- `version`:桌面端的精确 `X.Y.Z` 版本。计划使用独立于 Python 发布的 `desktop-vX.Y.Z` 标签,应用标识为 `com.powercontext.desktop`。 +- `server_version`:Server 的精确 Python 包版本(例如 `1.5.1.dev25+g63e9665c6`)。生产器从指定的 Server 提交按锁定输入构建,版本可与桌面端不同,构建过程不会从包索引推断版本。 +- `source_sha`:完整 Git 提交,必须与工作流实际检出的提交一致。如果标签已经存在,它必须指向同一提交。候选组装不会创建标签。 +- `server_source_sha`:完整 Server 提交,可选用较早且已有资格记录的版本。wheel 及依赖锁来自该提交,Desktop 打包及生产器工具仍绑定 `source_sha`。 + +桌面端版本各段为 0 至 65535 的整数,且无前导零。工作流从干净目录构建 release 包,不启用 `ci-fixtures`,并嵌入生产器的精确目录和 Ops 摘要。Windows x64(NSIS)、macOS arm64(DMG)和 macOS x64(DMG)均为必需。候选不包含 Linux。以后如需发布 Linux,由 [#2111](https://github.com/oceanbase/powercontext/issues/2111) 提供独立验收过的构件,不影响三个必需目标的组装。 + +## 候选交接 + +从同一次成功运行下载 `desktop-candidate--`。汇总任务只接收同一次运行中指定平台任务的产物,不接收内部预览包、测试资格清单或其他运行的上传件。每个目标目录下的安装包为 `powercontext-desktop--.exe` 或 `.dmg`。同目录还包含 Server 和 Ops 归档、资源目录、配置描述、输入锁文件、生产清单、实际 Server wheel 和烟测记录。目标标识为 `windows-x86_64`、`macos-arm64` 和 `macos-x86_64`。 + +`desktop-release-candidate.json` 包含 `schema_version: 1`、`version`、`tag`、`source_sha`、`server_source_sha`、`server_version`、`status: unqualified_candidate` 和 `publishable: false`。`contract` 记录桌面端 HTTP 契约摘要、操作集,以及随候选交接的操作与兼容性文件。`targets` 中每个目标有 `package`、`resources`、`provenance`、`qualification` 和 `runtime`。`assets` 中的四种发布角色为 `desktop`、`server_archive`、`server_catalog` 和 `ops_archive`。文件条目包含相对候选根目录的 `name`、字节数 `size` 和小写 `sha256`。Ops 配置描述和 bundle 清单位于 `provenance`,文件名按目标区分。`qualification.producer_ref` 始终指向未取得资格的生产记录。`matching_product_records` 只列出与实际 wheel、源码、契约及操作集匹配的内置资格记录;空列表表示仍需补产品协议资格。即使有匹配记录,也不能视为安装包通过验收。 + +交接发布时选择 `desktop-candidate-manifest--`,其中只有字节完全相同的 `desktop-release-candidate.json`。运行摘要列出 `candidate_run_id`、`candidate_full_artifact_id`、`candidate_manifest_artifact_id` 和 `candidate_manifest_sha256`。在发布交接中用清单构件 ID 填写 `candidate_artifact_id`,发布流程即可单独取清单,无需下载大型归档。两种 Actions 构件均保留 14 天。 + +如需检查完整候选,从可信运行的摘要取得候选清单 SHA-256,再校验下载件: + +```sh +uv run --locked --no-dev --group resource-build python scripts/desktop_candidate.py verify --root <下载目录> \ + --version <桌面版本> --server-version --source-sha <桌面提交> \ + --server-source-sha \ + --manifest-sha256 <运行摘要中的SHA-256> +``` + +摘要绑定清单和构件的实际字节。信任仍来自对应上游提交的这条工作流及其成功运行,应记录运行和构件身份。同名重跑的字节可能不同,不能悄悄替换已经接受的候选。Actions 候选保留 14 天,不能作为已安装客户端的资源下载渠道。 + +## 发布前验收 + +CI 消费实际目录和归档,用随附 Python 启动一次性的 SQLite Server,并通过独立 Ops 入口检查本机状态。这不包括真实 HTTP 下载或注册服务。候选资源目录特意指向 `candidate.invalid`。 + +最终平台打包负责人负责 Windows x64 签名和 macOS 双架构签名、公证,将获准的独立 Ops helper 安装到[当前用户固定位置](../docs/operate/local-server-ops.md#provisioning-the-bridge)。卸载 Desktop 必须保留独立 helper、服务状态和用户数据。Windows 保留供 Server 服务使用的 `pythonw.exe` 及用于控制台的 `python.exe`。候选包嵌入资源摘要但不安装独立 helper。helper 配置、干净机安装修复、重启或登录、原生服务生命周期由 [#2108](https://github.com/oceanbase/powercontext/issues/2108) 和 [#2109](https://github.com/oceanbase/powercontext/issues/2109) 负责验收。 + +最终平台构建应使用经批准的不可变资源 URL;签名改变嵌套代码字节后,重新生成受影响的文件清单、归档、资源目录和配置摘要。把最终摘要嵌入 Desktop 后再签外层包。记录候选清单摘要,并单独记录经过验收的最终包与资源摘要;候选与签名件的字节可以不同。最终验收须在同一 Desktop 和 Server 组合上覆盖身份、Scope 与 Memory、统计、运行观察,以及本机设置直到默认 Scope。不得用重建 wheel 或测试专用构件替代 [#2101](https://github.com/oceanbase/powercontext/issues/2101) 资格。发布和回下载使用同一批最终签名并通过验收的字节。 diff --git a/scripts/desktop_candidate.py b/scripts/desktop_candidate.py new file mode 100644 index 0000000000..f3c91b2ece --- /dev/null +++ b/scripts/desktop_candidate.py @@ -0,0 +1,437 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed 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. + +"""Assemble and verify the read-only Desktop candidate handoff for #2112.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import re +import shutil +import subprocess +from pathlib import Path +from typing import Any + +from packaging.version import Version + +ROOT = Path(__file__).resolve().parents[1] +TARGETS = { + "windows-x86_64": ("windows", "x86_64", "nsis", "x64-setup.exe"), + "macos-arm64": ("macos", "arm64", "dmg", "aarch64.dmg"), + "macos-x86_64": ("macos", "x86_64", "dmg", "x64.dmg"), +} +CONTRACT_FILES = { + "operations.json": "desktop/src-tauri/src/transport/operations.json", + "compatibility.json": "desktop/src-tauri/src/connections/compatibility.json", +} +PRODUCT_NAME = "PowerContext Desktop" +PRODUCT_ID = "com.powercontext.desktop" +UNQUALIFIED = "unqualified_candidate" +MANIFEST = "desktop-release-candidate.json" + + +def require(condition: bool, message: str) -> None: + if not condition: + raise ValueError(message) + + +def version(value: str) -> bool: + return bool(re.fullmatch(r"(?:0|[1-9][0-9]{0,4})(?:\.(?:0|[1-9][0-9]{0,4})){2}", value)) and all( + int(part) <= 65535 for part in value.split(".") + ) + + +def identity(desktop_version: str, server_version: str, source_sha: str, server_source_sha: str) -> dict[str, str]: + require(version(desktop_version), "expected exact X.Y.Z Desktop version (0-65535 per part)") + require( + len(server_version) <= 100 and str(Version(server_version)) == server_version, + "expected an exact canonical Python Server version", + ) + for label, sha in (("source_sha", source_sha), ("server_source_sha", server_source_sha)): + require(bool(re.fullmatch(r"[0-9a-f]{40}", sha)), f"{label} must be a full lowercase Git commit") + return { + "version": desktop_version, + "release_tag": f"desktop-v{desktop_version}", + "source_sha": source_sha, + "server_source_sha": server_source_sha, + "server_version": server_version, + } + + +def git(*args: str) -> bytes: + return subprocess.check_output(["git", "-C", str(ROOT), *args]) # noqa: S603, S607 - fixed Git commands + + +def check_checkout(release: dict[str, str]) -> None: + require(git("rev-parse", "HEAD").decode().strip() == release["source_sha"], "checkout differs from source_sha") + require(git("cat-file", "-t", release["server_source_sha"]).strip() == b"commit", "Server source must be a commit") + require(not git("status", "--porcelain", "--untracked-files=normal"), "candidate requires a clean checkout") + ref = f"refs/tags/{release['release_tag']}" + if git("tag", "--list", release["release_tag"]): + require( + git("rev-parse", f"{ref}^{{commit}}").decode().strip() == release["source_sha"], + "Desktop tag already points to a different commit", + ) + + +def regular(path: Path) -> Path: + # Do not follow a link, including a Windows junction, anywhere inside a handoff. + require( + not path.is_symlink() and not getattr(path, "is_junction", lambda: False)() and path.is_file(), + f"missing or unsafe file: {path.name}", + ) + return path + + +def directory(path: Path) -> None: + require( + not path.is_symlink() and not getattr(path, "is_junction", lambda: False)() and path.is_dir(), + f"missing or unsafe directory: {path.name}", + ) + + +def expect_entries(path: Path, names: set[str]) -> None: + directory(path) + require({p.name for p in path.iterdir()} == names, f"unexpected or missing entries in {path.name}") + + +def read(path: Path) -> Any: + return json.loads(regular(path).read_bytes()) + + +def digest(path: Path) -> str: + with regular(path).open("rb") as stream: + return hashlib.file_digest(stream, "sha256").hexdigest() + + +def asset(root: Path, path: Path) -> dict[str, Any]: + return { + "name": path.relative_to(root).as_posix(), + "size": path.stat().st_size, + "sha256": digest(path), + } + + +def json_bytes(value: object) -> bytes: + return (json.dumps(value, ensure_ascii=False, sort_keys=True, indent=2) + "\n").encode() + + +def create(path: Path, content: bytes) -> None: + with path.open("xb") as stream: + stream.write(content) + + +def package_name(release: dict[str, str], target: str) -> str: + ext = "exe" if target.startswith("windows-") else "dmg" + return f"powercontext-desktop-{release['version']}-{target}.{ext}" + + +def resource_names(release: dict[str, str], target: str) -> dict[str, str]: + suffix = f"{release['version']}-{target}" + return { + "server_archive": f"powercontext-server-{suffix}.tar.gz", + "server_catalog": f"powercontext-server-{suffix}.json", + "ops_archive": f"powercontext-ops-{suffix}.tar.gz", + "ops_provision": f"powercontext-ops-provision-{suffix}.json", + "ops_bundle_manifest": f"powercontext-ops-bundle-{suffix}.json", + } + + +def server_url(target: str) -> str: + return f"https://candidate.invalid/{target}/server.tar.gz" + + +def prepare_desktop(candidate: Path, desktop: Path, release: dict[str, str]) -> None: + """Pin the producer metadata in the app using the existing Tauri resource mapping.""" + staging = desktop / ".artifacts/ops-resource" + (staging / "server").mkdir(parents=True) + for name in ("ops-provision.json", "server/catalog.json"): + create(staging / name, regular(candidate / name).read_bytes()) + create( + desktop / ".artifacts/candidate.conf.json", + json_bytes({ + "productName": PRODUCT_NAME, + "identifier": PRODUCT_ID, + "version": release["version"], + "bundle": {"shortDescription": "PowerContext Desktop candidate"}, + }), + ) + + +def project_wheel(inputs: dict[str, Any]) -> dict[str, Any]: + [wheel] = [item for item in inputs["wheels"] if item["name"] == "powercontext"] + require( + bool(re.fullmatch(r"powercontext-[a-zA-Z0-9_.+!-]+\.whl", wheel["filename"])), + "unexpected Server wheel name", + ) + return wheel + + +def stage_target( + output: Path, bundles: Path, resources: Path, inputs: Path, smoke: Path, release: dict[str, str], target: str +) -> None: + """Collect one fresh product build; internal/preview package names are never accepted.""" + _, _, bundle_dir, suffix = TARGETS[target] + expected = f"{PRODUCT_NAME}_{release['version']}_{suffix}" + bundle_folder = bundles / bundle_dir + directory(bundle_folder) + require( + [p.name for p in bundle_folder.glob(f"*.{suffix.rsplit('.', 1)[1]}")] == [expected], + f"expected exactly one normal product bundle: {expected}", + ) + output.mkdir(parents=True) + wheel = project_wheel(read(inputs / "inputs.json"))["filename"] + names = resource_names(release, target) + files = { + package_name(release, target): bundle_folder / expected, + names["server_archive"]: resources / "server/server.tar.gz", + names["ops_archive"]: resources / "ops.tar.gz", + names["server_catalog"]: resources / "server/catalog.json", + names["ops_provision"]: resources / "ops-provision.json", + names["ops_bundle_manifest"]: resources / "ops/bundle.json", + "server-resource.json": resources / "server/resource.json", + "ops-resource.json": resources / "ops-resource.json", + "producer-candidate.json": resources / "candidate.json", + "inputs.json": inputs / "inputs.json", + "requirements.lock": inputs / "requirements.lock", + "upstream-requirements.lock": inputs / "upstream-requirements.lock", + "resource-smoke.json": smoke, + wheel: inputs / "wheels" / wheel, + } + for name, source in files.items(): + shutil.copyfile(regular(source), output / name) + # Confirm the exact resource pins passed to the builder were the ones staged for handoff. + for path, name in ( + ("ops-provision.json", names["ops_provision"]), + ("server/catalog.json", names["server_catalog"]), + ): + require( + digest(ROOT / "desktop/.artifacts/ops-resource" / path) == digest(output / name), + f"{target}: bundle input differs from collected {name}", + ) + + +def validate_target( + root: Path, target: str, release: dict[str, str], contract: dict[str, Any], profiles: list[dict[str, Any]] +) -> dict[str, Any]: + path = root / target + directory(path) + inputs = read(path / "inputs.json") + wheel = project_wheel(inputs) + names = { + "desktop": package_name(release, target), + **resource_names(release, target), + "server_wheel": wheel["filename"], + "producer_candidate": "producer-candidate.json", + "server_resource": "server-resource.json", + "ops_resource": "ops-resource.json", + "inputs": "inputs.json", + "requirements": "requirements.lock", + "upstream_requirements": "upstream-requirements.lock", + "resource_smoke": "resource-smoke.json", + } + expect_entries(path, set(names.values())) + assets = {key: asset(root, path / name) for key, name in names.items()} + hashes = {key: item["sha256"] for key, item in assets.items()} + require(all(item["size"] > 0 for item in assets.values()), f"{target}: empty asset") + producer = read(path / names["producer_candidate"]) + binding = producer["binding"] + platform, architecture, _, _ = TARGETS[target] + source_sha = release["source_sha"] + require( + inputs["format_version"] == 1 + and inputs["target"] == target + and inputs["source"]["commit"] == binding["source_commit"] == release["server_source_sha"] + and inputs["server_version"] == binding["server_version"] == wheel["version"] == release["server_version"] + and inputs["interpreter"]["platform"] == platform + and inputs["interpreter"]["architecture"] == architecture + and inputs["interpreter"]["sha256"] == binding["python_source_sha256"] + and inputs["requirements_sha256"] == hashes["requirements"] + and inputs["upstream_requirements_sha256"] == hashes["upstream_requirements"] + and all( + p["git_commit"] == source_sha and p["matches_committed_files"] is True + for p in (inputs["preparer"], binding["producer"]) + ), + f"{target}: producer source, target or locked inputs mismatch", + ) + expected_ref = "unqualified-candidate:sha256:" + hashlib.sha256(json_bytes(binding)).hexdigest() + require( + producer["format_version"] == 1 + and producer["status"] == UNQUALIFIED + and producer["signing"] + == producer["notarization"] + == producer["clean_machine_qualification"] + == "not_performed" + and producer["qualification_ref"] == expected_ref + and producer["catalog_sha256"] == hashes["server_catalog"] + and producer["ops_archive_sha256"] == binding["ops_archive_sha256"] == hashes["ops_archive"] + and binding["inputs_sha256"] == hashes["inputs"] + and binding["server_archive_sha256"] == hashes["server_archive"] + and binding["ops_bundle_manifest_sha256"] == hashes["ops_bundle_manifest"] + and binding["server_wheel_sha256"] == wheel["sha256"] == hashes["server_wheel"], + f"{target}: producer digest or candidate status mismatch", + ) + catalog = read(path / names["server_catalog"]) + [server] = catalog["resources"] + descriptor = read(path / names["ops_provision"]) + server_resource = read(path / names["server_resource"]) + ops_resource = read(path / names["ops_resource"]) + require( + catalog["format_version"] == 1 + and server["platform"] == platform + and server["architecture"] == architecture + and server["server_version"] == release["server_version"] + and server["python_version"] == inputs["interpreter"]["python_version"] + and server["qualification_ref"] == expected_ref + and server["url"] == server_url(target) + and server["archive_sha256"] == hashes["server_archive"] + and server["archive_size"] == assets["server_archive"]["size"] + and server["python_relative"] == inputs["interpreter"]["server_python_relative"] + and (platform != "windows" or server["python_relative"] == "pythonw.exe") + and descriptor + == { + "format_version": 1, + "binding_mode": "managed_catalog", + "bundle_manifest_sha256": hashes["ops_bundle_manifest"], + "catalog_sha256": hashes["server_catalog"], + } + and server_resource["resource"] == server + and server_resource["inputs"] == inputs + and ops_resource["archive_sha256"] == hashes["ops_archive"] + and ops_resource["archive_size"] == assets["ops_archive"]["size"] + and all( + r["format_version"] == 1 and r["status"] == UNQUALIFIED and r["inputs_sha256"] == hashes["inputs"] + for r in (server_resource, ops_resource) + ), + f"{target}: resource metadata or Desktop provision pin mismatch", + ) + smoke = read(path / names["resource_smoke"]) + require( + smoke["status"] == "candidate_smoke_passed" + and smoke["qualified"] is False + and smoke["archive_sha256"] == hashes["server_archive"] + and smoke["catalog_sha256"] == hashes["server_catalog"] + and smoke["ops"] == "independent_inspection_passed" + and smoke["server"]["launcher"] == "passed", + f"{target}: native resource smoke missing or mismatched", + ) + records = [ + {"id": profile["id"], "evidence": profile["evidence"]} + for profile in profiles + if not profile["id"].startswith("ci-") + and profile["serverCommit"] == release["server_source_sha"] + and profile["artifactSha256"] == hashes["server_wheel"] + and profile["contractSha256"] == contract["contractSha256"] + and set(contract["operations"]).issubset(profile["operations"]) + ] + return { + "build_kind": "product", + "assets": {key: assets.pop(key) for key in ("desktop", "server_archive", "server_catalog", "ops_archive")}, + "provenance": assets, + "qualification": {"producer_ref": expected_ref, "matching_product_records": records, "status": UNQUALIFIED}, + "runtime": { + "server_version": server["server_version"], + "python_version": server["python_version"], + "ops_protocol_min": server["ops_protocol_min"], + "ops_protocol_max": server["ops_protocol_max"], + }, + } + + +def manifest(root: Path, release: dict[str, str], *, verifying: bool) -> dict[str, Any]: + expect_entries(root, {*TARGETS, "contract"} | ({MANIFEST} if verifying else set())) + contract_path = root / "contract" + expect_entries(contract_path, set(CONTRACT_FILES)) + operations = read(contract_path / "operations.json") + profiles = read(contract_path / "compatibility.json") + return { + "schema_version": 1, + "kind": "desktop-product-candidate", + **release, + "status": UNQUALIFIED, + "publishable": False, + "contract": { + "sha256": operations["contractSha256"], + "operations": sorted(operations["operations"]), + "assets": {name: asset(root, contract_path / name) for name in CONTRACT_FILES}, + }, + "targets": {target: validate_target(root, target, release, operations, profiles) for target in TARGETS}, + } + + +def assemble(root: Path, release: dict[str, str]) -> None: + expect_entries(root, set(TARGETS)) + path = root / "contract" + path.mkdir() + for name, source in CONTRACT_FILES.items(): + create(path / name, git("show", f"{release['source_sha']}:{source}")) + create(root / MANIFEST, json_bytes(manifest(root, release, verifying=False))) + + +def verify(root: Path, release: dict[str, str], manifest_sha256: str) -> None: + directory(root) + require(digest(root / MANIFEST) == manifest_sha256, "candidate manifest digest mismatch") + require( + read(root / MANIFEST) == manifest(root, release, verifying=True), "candidate manifest does not match assets" + ) + + +def argument_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + for command in ("identity", "prepare", "stage", "assemble", "verify"): + sub = commands.add_parser(command) + sub.add_argument("--version", required=True) + sub.add_argument("--server-version", required=True) + sub.add_argument("--source-sha", required=True) + sub.add_argument("--server-source-sha", required=True) + if command in {"assemble", "verify"}: + sub.add_argument("--root", type=Path, required=True) + if command in {"prepare", "stage"}: + sub.add_argument("--resources", type=Path, required=True) + if command == "stage": + for name in ("output", "bundles", "inputs", "smoke"): + sub.add_argument(f"--{name}", type=Path, required=True) + sub.add_argument("--target", choices=TARGETS, required=True) + if command == "verify": + sub.add_argument("--manifest-sha256", required=True) + return parser + + +def main() -> None: + parser = argument_parser() + args = parser.parse_args() + try: + release = identity(args.version, args.server_version, args.source_sha, args.server_source_sha) + if args.command == "verify": + verify(args.root, release, args.manifest_sha256) + else: + check_checkout(release) + if args.command == "identity": + print(json_bytes(release).decode(), end="") + elif args.command == "prepare": + prepare_desktop(args.resources, ROOT / "desktop", release) + elif args.command == "stage": + stage_target(args.output, args.bundles, args.resources, args.inputs, args.smoke, release, args.target) + else: + assemble(args.root, release) + print(f"candidate_manifest_sha256={digest(args.root / MANIFEST)}") + except (OSError, ValueError, KeyError, TypeError, subprocess.CalledProcessError) as exc: + parser.exit(1, f"Desktop candidate rejected: {exc}\n") + + +if __name__ == "__main__": + main() diff --git a/tests/test_desktop_candidate.py b/tests/test_desktop_candidate.py new file mode 100644 index 0000000000..3dd0d84632 --- /dev/null +++ b/tests/test_desktop_candidate.py @@ -0,0 +1,250 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed 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. + +"""Exercise the candidate handoff without pretending to qualify a native package.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from desktop_candidate import ( + MANIFEST, + TARGETS, + UNQUALIFIED, + assemble, + digest, + identity, + json_bytes, + package_name, + resource_names, + server_url, + stage_target, + verify, +) + +SOURCE = "a" * 40 +SERVER_SOURCE = "e" * 40 +RELEASE = identity("1.0.0", "1.5.1.dev25+g63e9665c6", SOURCE, SERVER_SOURCE) +OPERATIONS = {"contractSha256": "b" * 64, "operations": {"get_stats": {}, "remember_memory": {}}} + + +def write(path: Path, value: object) -> str: + path.write_bytes(json_bytes(value)) + return digest(path) + + +def synthetic_target(root: Path, target: str) -> str: + platform, architecture, _, _ = TARGETS[target] + path = root / target + path.mkdir() + names = resource_names(RELEASE, target) + wheel = f"powercontext-{RELEASE['server_version']}-py3-none-any.whl" + for name in (package_name(RELEASE, target), wheel, names["server_archive"], names["ops_archive"]): + (path / name).write_bytes(name.encode()) + producer = {"git_commit": SOURCE, "matches_committed_files": True} + interpreter = { + "platform": platform, + "architecture": architecture, + "python_version": "3.12.16", + "sha256": "c" * 64, + "server_python_relative": "pythonw.exe" if platform == "windows" else "bin/python3", + } + ops_manifest = write(path / names["ops_bundle_manifest"], {"target": target}) + wheel_sha = digest(path / wheel) + inputs = { + "format_version": 1, + "target": target, + "source": {"commit": SERVER_SOURCE}, + "server_version": RELEASE["server_version"], + "interpreter": interpreter, + "requirements_sha256": write(path / "requirements.lock", {"local": "lock"}), + "upstream_requirements_sha256": write(path / "upstream-requirements.lock", {"upstream": "lock"}), + "preparer": producer, + "wheels": [ + {"name": "powercontext", "version": RELEASE["server_version"], "filename": wheel, "sha256": wheel_sha} + ], + } + inputs_sha = write(path / "inputs.json", inputs) + binding = { + "producer": producer, + "source_commit": SERVER_SOURCE, + "server_version": RELEASE["server_version"], + "python_source_sha256": interpreter["sha256"], + "inputs_sha256": inputs_sha, + "server_archive_sha256": digest(path / names["server_archive"]), + "ops_archive_sha256": digest(path / names["ops_archive"]), + "ops_bundle_manifest_sha256": ops_manifest, + "server_wheel_sha256": wheel_sha, + } + binding_sha = write(path / "binding.tmp", binding) + (path / "binding.tmp").unlink() + ref = f"unqualified-candidate:sha256:{binding_sha}" + server = { + "platform": platform, + "architecture": architecture, + "server_version": RELEASE["server_version"], + "python_version": interpreter["python_version"], + "python_relative": interpreter["server_python_relative"], + "ops_protocol_min": 1, + "ops_protocol_max": 1, + "url": server_url(target), + "qualification_ref": ref, + "archive_sha256": binding["server_archive_sha256"], + "archive_size": (path / names["server_archive"]).stat().st_size, + } + catalog_sha = write(path / names["server_catalog"], {"format_version": 1, "resources": [server]}) + status = {"format_version": 1, "status": UNQUALIFIED, "inputs_sha256": inputs_sha} + write(path / "server-resource.json", {**status, "inputs": inputs, "resource": server}) + write( + path / "ops-resource.json", + { + **status, + "archive_sha256": binding["ops_archive_sha256"], + "archive_size": (path / names["ops_archive"]).stat().st_size, + }, + ) + write( + path / names["ops_provision"], + { + "format_version": 1, + "binding_mode": "managed_catalog", + "bundle_manifest_sha256": ops_manifest, + "catalog_sha256": catalog_sha, + }, + ) + write( + path / "producer-candidate.json", + { + "format_version": 1, + "status": UNQUALIFIED, + "binding": binding, + "catalog_sha256": catalog_sha, + "ops_archive_sha256": binding["ops_archive_sha256"], + "qualification_ref": ref, + "signing": "not_performed", + "notarization": "not_performed", + "clean_machine_qualification": "not_performed", + }, + ) + write( + path / "resource-smoke.json", + { + "status": "candidate_smoke_passed", + "qualified": False, + "archive_sha256": binding["server_archive_sha256"], + "catalog_sha256": catalog_sha, + "ops": "independent_inspection_passed", + "server": {"launcher": "passed"}, + }, + ) + return wheel_sha + + +@pytest.fixture +def legs(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + wheel_shas = {synthetic_target(tmp_path, target) for target in TARGETS} + [wheel_sha] = wheel_shas + matching = { + "id": "matching", + "serverCommit": SERVER_SOURCE, + "contractSha256": OPERATIONS["contractSha256"], + "artifactSha256": wheel_sha, + "operations": list(OPERATIONS["operations"]), + "evidence": "desktop/VALIDATION.md", + } + profiles = [ + matching, + {**matching, "id": "wrong-wheel", "artifactSha256": "d" * 64}, + {**matching, "id": "desktop-source", "serverCommit": SOURCE}, + {**matching, "id": "old-operation-set", "operations": ["remember_memory"]}, + {**matching, "id": "ci-fixture"}, + ] + + def read_commit(command: str, object_name: str) -> bytes: + assert command == "show" + return json_bytes(OPERATIONS if object_name.endswith("/operations.json") else profiles) + + monkeypatch.setattr("desktop_candidate.git", read_commit) + return tmp_path + + +def test_assemble_without_linux_and_never_promote_a_candidate(legs: Path) -> None: + assemble(legs, RELEASE) + path = legs / MANIFEST + manifest = json.loads(path.read_bytes()) + verify(legs, RELEASE, digest(path)) + assert manifest["release_tag"] == "desktop-v1.0.0" + assert manifest["source_sha"] == SOURCE + assert manifest["server_source_sha"] == SERVER_SOURCE + assert manifest["publishable"] is False + assert set(manifest["targets"]) == {"windows-x86_64", "macos-arm64", "macos-x86_64"} + target = manifest["targets"]["macos-arm64"] + assert target["qualification"]["matching_product_records"] == [ + {"id": "matching", "evidence": "desktop/VALIDATION.md"} + ] + assert target["assets"]["desktop"]["name"] == "macos-arm64/powercontext-desktop-1.0.0-macos-arm64.dmg" + + +@pytest.mark.parametrize( + "wrong_leg", ["missing-intel", "internal", "wrong-wheel", "wrong-pin", "wrong-source", "wrong-target"] +) +def test_assembly_rejects_incomplete_or_unbound_required_outputs(legs: Path, wrong_leg: str) -> None: + target = legs / "windows-x86_64" + if wrong_leg == "missing-intel": + (legs / "macos-x86_64").rename(legs / "linux-x86_64") + elif wrong_leg == "internal": + (target / "ci-compatibility.json").write_text("{}", encoding="utf-8") + elif wrong_leg == "wrong-wheel": + next(target.glob("*.whl")).write_bytes(b"wrong") + elif wrong_leg == "wrong-pin": + windows_pin = resource_names(RELEASE, "windows-x86_64")["ops_provision"] + arm_pin = resource_names(RELEASE, "macos-arm64")["ops_provision"] + (target / windows_pin).write_bytes((legs / "macos-arm64" / arm_pin).read_bytes()) + else: + inputs = json.loads((target / "inputs.json").read_bytes()) + if wrong_leg == "wrong-source": + inputs["source"]["commit"] = "f" * 40 + else: + inputs["target"] = "macos-arm64" + write(target / "inputs.json", inputs) + with pytest.raises(ValueError): + assemble(legs, RELEASE) + assert not (legs / MANIFEST).exists() + + +def test_rejects_preview_bundle_before_staging(tmp_path: Path) -> None: + nsis = tmp_path / "nsis" + nsis.mkdir() + (nsis / "PowerContext Desktop Preview_0.1.0_x64-setup.exe").write_bytes(b"internal") + with pytest.raises(ValueError, match="normal product bundle"): + stage_target(tmp_path / "output", tmp_path, tmp_path, tmp_path, tmp_path, RELEASE, "windows-x86_64") + + +def test_verification_rejects_tampered_package_or_manifest(legs: Path) -> None: + assemble(legs, RELEASE) + original = digest(legs / MANIFEST) + with pytest.raises(ValueError, match="manifest digest"): + verify(legs, RELEASE, "a" * 64) + path = legs / "macos-arm64" / package_name(RELEASE, "macos-arm64") + path.write_bytes(b"changed") + with pytest.raises(ValueError, match="does not match assets"): + verify(legs, RELEASE, original) + + +@pytest.mark.parametrize("value", ["v1.0.0", "65536.0.0", "1.2.03", "1.2.3-rc.1", "1.2.3\npath"]) +def test_rejects_ambiguous_or_unsafe_version(value: str) -> None: + with pytest.raises(ValueError, match=r"exact X\.Y\.Z"): + identity(value, "1.2.3", SOURCE, SERVER_SOURCE) From c7056d2b86326840769e2911ea88b76f8702b654 Mon Sep 17 00:00:00 2001 From: knqiufan Date: Thu, 5 Nov 2026 08:24:07 +0800 Subject: [PATCH 2/8] fix(ci): run desktop candidate checks through Main --- .github/ci-paths.toml | 4 ++++ .github/workflows/desktop-candidate.yml | 5 ----- .github/workflows/master.yml | 3 ++- docs/zh/development/desktop-candidate-assembly.md | 2 +- tests/test_ci_changes.py | 5 +++++ 5 files changed, 12 insertions(+), 7 deletions(-) diff --git a/.github/ci-paths.toml b/.github/ci-paths.toml index e6b355ae31..3aa02d33cb 100644 --- a/.github/ci-paths.toml +++ b/.github/ci-paths.toml @@ -29,6 +29,10 @@ tests = [ "scripts/run_atomic_memory_clean_migration.py", "scripts/scan_e2e_evidence.sh", "scripts/check_atomic_memory_migration_shards.py", "scripts/ci_role_smoke.py", "scripts/ci_installation_roles.py", + # Release tooling is covered by unit tests; the packaging and publication workflows are manual. + ".github/workflows/desktop-candidate.yml", "scripts/desktop_candidate.py", + ".github/workflows/desktop-release.yml", "scripts/desktop_publication_manifest.py", + "scripts/publish_desktop_release.py", # These evaluator suites still live under the root tests/ directory. "evaluation/memory/locomo/**", "evaluation/memory/locomo_plus/**", "evaluation/memory/write_gate/**", "evaluation/performance/input_encoding/**", diff --git a/.github/workflows/desktop-candidate.yml b/.github/workflows/desktop-candidate.yml index 58e617841b..cac0912561 100644 --- a/.github/workflows/desktop-candidate.yml +++ b/.github/workflows/desktop-candidate.yml @@ -1,11 +1,6 @@ name: Desktop candidate assembly on: - pull_request: - paths: - - '.github/workflows/desktop-candidate.yml' - - 'scripts/desktop_candidate.py' - - 'tests/test_desktop_candidate.py' workflow_dispatch: inputs: version: diff --git a/.github/workflows/master.yml b/.github/workflows/master.yml index 789be62309..df943a1a14 100644 --- a/.github/workflows/master.yml +++ b/.github/workflows/master.yml @@ -231,7 +231,8 @@ jobs: name: tests (${{ matrix.python-version }}, ${{ matrix.suite }}) needs: [quality] if: ${{ !cancelled() && needs.quality.result == 'success' && (fromJSON(needs.quality.outputs.suites || '{}').tests) }} - timeout-minutes: 40 + # Allow the Python 3.14 end-to-end suite's subprocess tail to finish. + timeout-minutes: ${{ matrix.suite == 'e2e' && matrix.python-version == '3.14' && 55 || 40 }} runs-on: ubuntu-latest strategy: fail-fast: true diff --git a/docs/zh/development/desktop-candidate-assembly.md b/docs/zh/development/desktop-candidate-assembly.md index 0dcc7f62a1..5dcc434957 100644 --- a/docs/zh/development/desktop-candidate-assembly.md +++ b/docs/zh/development/desktop-candidate-assembly.md @@ -41,6 +41,6 @@ uv run --locked --no-dev --group resource-build python scripts/desktop_candidate CI 消费实际目录和归档,用随附 Python 启动一次性的 SQLite Server,并通过独立 Ops 入口检查本机状态。这不包括真实 HTTP 下载或注册服务。候选资源目录特意指向 `candidate.invalid`。 -最终平台打包负责人负责 Windows x64 签名和 macOS 双架构签名、公证,将获准的独立 Ops helper 安装到[当前用户固定位置](../docs/operate/local-server-ops.md#provisioning-the-bridge)。卸载 Desktop 必须保留独立 helper、服务状态和用户数据。Windows 保留供 Server 服务使用的 `pythonw.exe` 及用于控制台的 `python.exe`。候选包嵌入资源摘要但不安装独立 helper。helper 配置、干净机安装修复、重启或登录、原生服务生命周期由 [#2108](https://github.com/oceanbase/powercontext/issues/2108) 和 [#2109](https://github.com/oceanbase/powercontext/issues/2109) 负责验收。 +最终平台打包负责人负责 Windows x64 签名和 macOS 双架构签名、公证,将获准的独立 Ops helper 安装到[当前用户固定位置](../docs/operate/local-server-ops.md#配置桥接资源)。卸载 Desktop 必须保留独立 helper、服务状态和用户数据。Windows 保留供 Server 服务使用的 `pythonw.exe` 及用于控制台的 `python.exe`。候选包嵌入资源摘要但不安装独立 helper。helper 配置、干净机安装修复、重启或登录、原生服务生命周期由 [#2108](https://github.com/oceanbase/powercontext/issues/2108) 和 [#2109](https://github.com/oceanbase/powercontext/issues/2109) 负责验收。 最终平台构建应使用经批准的不可变资源 URL;签名改变嵌套代码字节后,重新生成受影响的文件清单、归档、资源目录和配置摘要。把最终摘要嵌入 Desktop 后再签外层包。记录候选清单摘要,并单独记录经过验收的最终包与资源摘要;候选与签名件的字节可以不同。最终验收须在同一 Desktop 和 Server 组合上覆盖身份、Scope 与 Memory、统计、运行观察,以及本机设置直到默认 Scope。不得用重建 wheel 或测试专用构件替代 [#2101](https://github.com/oceanbase/powercontext/issues/2101) 资格。发布和回下载使用同一批最终签名并通过验收的字节。 diff --git a/tests/test_ci_changes.py b/tests/test_ci_changes.py index f63ccc3e7a..fc58175294 100644 --- a/tests/test_ci_changes.py +++ b/tests/test_ci_changes.py @@ -64,6 +64,11 @@ (["desktop/ui/src/app/App.tsx"], {"desktop"}), (["release/upgrade-support.json"], {"upgrade", "packaging"}), ([".github/workflows/desktop.yml"], {"desktop"}), + ([".github/workflows/desktop-candidate.yml"], {"tests"}), + ([".github/workflows/desktop-release.yml"], {"tests"}), + (["scripts/desktop_candidate.py"], {"tests"}), + (["scripts/desktop_publication_manifest.py"], {"tests"}), + (["scripts/publish_desktop_release.py"], {"tests"}), ([".github/workflows/managed-resource-candidates.yml"], {"managed_resources"}), (["scripts/produce_managed_resources.py"], {"managed_resources"}), (["scripts/build_intel_managed_wheel.py"], {"managed_resources"}), From 103e33d99ae8503938909ee3d22a6a65d396ebfa Mon Sep 17 00:00:00 2001 From: knqiufan Date: Thu, 5 Nov 2026 09:04:54 +0800 Subject: [PATCH 3/8] fix(tests): wait for collector receipts after scope restoration --- tests/e2e/test_source_collect.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/tests/e2e/test_source_collect.py b/tests/e2e/test_source_collect.py index f0641a9764..39eafcd366 100644 --- a/tests/e2e/test_source_collect.py +++ b/tests/e2e/test_source_collect.py @@ -285,8 +285,14 @@ async def _scope_shrink_and_discovery(directory): await set_enabled(admin, "scope-review", True) restored = await received(admin, scopes[1], targets[scopes[1]], 3, namespace="scope-review") assert restored["target_id"] == targets[scopes[1]] - receipts = [json.loads(line) for line in (plugin / "receipts.jsonl").read_text().splitlines()] - assert any(r["scope_id"] == scopes[1] and r["source"] in restored["source_refs"] for r in receipts) + # The server reports the submission before the collector completes the batch and appends its receipt. + receipts_path = plugin / "receipts.jsonl" + async with asyncio.timeout(40): + while True: + receipts = map(json.loads, receipts_path.read_text(encoding="utf-8").splitlines()) + if any(r["scope_id"] == scopes[1] and r["source"] in restored["source_refs"] for r in receipts): + break + await asyncio.sleep(0.1) async with Client(url + "/mcp", auth=TOKENS["deployer"]) as host: query = {"scope_id": scopes[0], "instance_id": "scope-review"} From 99d6b62265d64f76cde72890fcbb0b1f68826db6 Mon Sep 17 00:00:00 2001 From: knqiufan Date: Thu, 5 Nov 2026 10:20:09 +0800 Subject: [PATCH 4/8] fix(ci): isolate ZCode deadlines and recover Windows downloads --- .github/workflows/master.yml | 9 +++- scripts/prepare_managed_resources.py | 57 +++++++++++++++---------- tests/test_managed_resource_producer.py | 33 ++++++++++++++ 3 files changed, 75 insertions(+), 24 deletions(-) diff --git a/.github/workflows/master.yml b/.github/workflows/master.yml index df943a1a14..bc303aae0b 100644 --- a/.github/workflows/master.yml +++ b/.github/workflows/master.yml @@ -280,8 +280,15 @@ jobs: PYTEST_ADDOPTS: --require-dsh-config-runtime --require-claude-code-python-floor run: make unit-test - - name: Run end-to-end tests + - name: Run the ZCode service chain with native Hook deadlines if: matrix.suite == 'e2e' + # Preserve the real Hook deadlines without competing with xdist workers. + run: uv run python -m pytest -n 0 tests/e2e/test_zcode_service_chain.py + + - name: Run remaining end-to-end tests + if: matrix.suite == 'e2e' + env: + PYTEST_ADDOPTS: --ignore=tests/e2e/test_zcode_service_chain.py run: make e2e-test isolated-installations: diff --git a/scripts/prepare_managed_resources.py b/scripts/prepare_managed_resources.py index 405ed7df8f..c5f51390ee 100644 --- a/scripts/prepare_managed_resources.py +++ b/scripts/prepare_managed_resources.py @@ -51,6 +51,7 @@ _INTERPRETERS = _SCRIPTS / "managed_resource_interpreters.json" _BUILD_TOOLS = _SCRIPTS / "managed_resource_build_tools.json" _SOURCE_REPOSITORY = "https://github.com/oceanbase/powercontext" +_WINDOWS_ACCESS_VIOLATION = 0xC0000005 def json_bytes(value: object) -> bytes: @@ -104,6 +105,38 @@ def target_spec(target: str, *, native: bool = True) -> dict[str, Any]: return spec +def _download(url: str, partial: Path) -> None: + command = [ + "curl", + "--fail", + "--silent", + "--show-error", + "--location", + "--proto", + "=https", + "--proto-redir", + "=https", + "--retry", + "2", + "--max-time", + "1800", + "--output", + str(partial), + url, + ] + env = environment() + for attempt in range(2): + try: + subprocess.run(command, check=True, env=env, timeout=1900) + except subprocess.CalledProcessError as error: + # curl's own retry cannot recover from a process crash on the Windows runner. + if attempt or error.returncode != _WINDOWS_ACCESS_VIOLATION: + raise + partial.unlink(missing_ok=True) + else: + return + + def acquire(item: dict[str, Any], destination: Path, cache: Path | None = None) -> None: """Download fixed HTTPS bytes; incomplete and corrupt files cannot be reused.""" if destination.exists(): @@ -123,29 +156,7 @@ def acquire(item: dict[str, Any], destination: Path, cache: Path | None = None) partial = destination.with_name(destination.name + ".partial") if partial.exists(): raise ValueError("An incomplete input exists; inspect it before retrying") - subprocess.run( - [ - "curl", - "--fail", - "--silent", - "--show-error", - "--location", - "--proto", - "=https", - "--proto-redir", - "=https", - "--retry", - "2", - "--max-time", - "1800", - "--output", - str(partial), - item["url"], - ], - check=True, - env=environment(), - timeout=1900, - ) + _download(item["url"], partial) if sha256(partial) != item["sha256"] or ("size" in item and partial.stat().st_size != item["size"]): raise ValueError("Downloaded input does not match its locked digest and size") partial.rename(destination) diff --git a/tests/test_managed_resource_producer.py b/tests/test_managed_resource_producer.py index 3665c294e8..43f8b25c21 100644 --- a/tests/test_managed_resource_producer.py +++ b/tests/test_managed_resource_producer.py @@ -213,6 +213,39 @@ def test_corrupt_cached_interpreter_is_rejected_without_network(tmp_path: Path) assert artifact.read_bytes() == b"bad existing input" +@pytest.mark.parametrize("retry_succeeds", [True, False]) +def test_acquire_retries_windows_curl_crash_with_fresh_partial( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, retry_succeeds: bool +) -> None: + content = b"locked candidate bytes" + item = { + "url": "https://candidate.invalid/wheel.whl", + "sha256": hashlib.sha256(content).hexdigest(), + "size": len(content), + } + results = iter((False, retry_succeeds)) + + def download(command: list[str], **_options: Any) -> None: + succeeded = next(results) + partial = Path(command[command.index("--output") + 1]) + with partial.open("xb") as stream: + stream.write(content if succeeded else b"incomplete") + if not succeeded: + raise subprocess.CalledProcessError(0xC0000005, command) + + monkeypatch.setattr(subprocess, "run", download) + artifact = tmp_path / "wheel.whl" + if retry_succeeds: + acquire(item, artifact, tmp_path / "cache") + assert artifact.read_bytes() == content + else: + with pytest.raises(subprocess.CalledProcessError) as error: + acquire(item, artifact, tmp_path / "cache") + assert error.value.returncode == 0xC0000005 + assert not artifact.exists() + assert next(results, None) is None + + def test_windows_layout_requires_console_and_windowless_interpreters(tmp_path: Path) -> None: source = tmp_path / "python.tar.gz" _runtime_archive(source) From dfb807087c045b56edc62d26c427c7b5950af1bd Mon Sep 17 00:00:00 2001 From: knqiufan Date: Thu, 5 Nov 2026 13:47:27 +0800 Subject: [PATCH 5/8] fix(ci): budget cold OceanBase metrics acceptance --- .github/workflows/e2e-harness.yml | 6 +++-- scripts/run_atomic_memory_clean_migration.py | 13 +++++++--- tests/test_atomic_memory_migration_shards.py | 26 ++++++++++++++++++++ 3 files changed, 39 insertions(+), 6 deletions(-) diff --git a/.github/workflows/e2e-harness.yml b/.github/workflows/e2e-harness.yml index 6583227073..db729dd73d 100644 --- a/.github/workflows/e2e-harness.yml +++ b/.github/workflows/e2e-harness.yml @@ -429,10 +429,12 @@ jobs: tests/e2e/test_scope_search_migration.py - name: Test background listener lifecycle without skips - timeout-minutes: 5 + # Cold Server schema/index creation consumed 165s before the lifecycle checks. + # Keep the CLI startup/stop deadlines and give only this combined case 300s. + timeout-minutes: 10 run: | uv run --locked --extra server python scripts/run_atomic_memory_clean_migration.py \ - oceanbase --shard "${{ matrix.shard }}/3" --output "$MIGRATION_REPORTS/background-metrics" --tests \ + oceanbase --case-timeout 300 --shard "${{ matrix.shard }}/3" --output "$MIGRATION_REPORTS/background-metrics" --tests \ tests/e2e/test_background_metrics.py - name: Run clean migration evidence, grants and vectors without skips diff --git a/scripts/run_atomic_memory_clean_migration.py b/scripts/run_atomic_memory_clean_migration.py index 539ac8292a..c2456b2999 100644 --- a/scripts/run_atomic_memory_clean_migration.py +++ b/scripts/run_atomic_memory_clean_migration.py @@ -42,13 +42,13 @@ def parse_shard(value: str) -> tuple[int, int]: raise argparse.ArgumentTypeError(message) -def run_pytest(arguments: list[str], log: Path) -> int: +def run_pytest(arguments: list[str], log: Path, *, timeout_seconds: int = 180) -> int: # GNU timeout also terminates native child processes; never retry a failed node. command = [ "timeout", "--signal=TERM", "--kill-after=10s", - "180s", + f"{timeout_seconds}s", sys.executable, "-m", "pytest", @@ -59,7 +59,7 @@ def run_pytest(arguments: list[str], log: Path) -> int: return subprocess.run(command, stdout=output, stderr=subprocess.STDOUT, check=False).returncode # noqa: S603 -def run_node(node: str, directory: Path) -> bool: +def run_node(node: str, directory: Path, *, timeout_seconds: int = 180) -> bool: directory.mkdir() (directory / "node.txt").write_text(node + "\n") report = directory / "junit.xml" @@ -81,6 +81,7 @@ def run_node(node: str, directory: Path) -> bool: node, ], log, + timeout_seconds=timeout_seconds, ) passed = False try: @@ -105,11 +106,14 @@ def main() -> int: parser.add_argument("backend", choices=("seekdb", "oceanbase")) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--collect-only", action="store_true") + parser.add_argument("--case-timeout", type=int, default=180, help="Positive per-case process deadline in seconds") parser.add_argument( "--shard", type=parse_shard, default=(0, 1), help="Run zero-based shard INDEX/COUNT (default: 0/1)" ) parser.add_argument("--tests", nargs="+", default=SUITES, help="Pytest files to run instead of clean migration") args = parser.parse_args() + if args.case_timeout <= 0: + parser.error("case-timeout must be positive") output = args.output.resolve() output.mkdir(parents=True, exist_ok=False) shard_index, shard_count = args.shard @@ -118,6 +122,7 @@ def main() -> int: "backend": args.backend, "shard_index": shard_index, "shard_count": shard_count, + "case_timeout_seconds": args.case_timeout, "collected_nodes": [], "passed_nodes": passed_nodes, "complete": False, @@ -150,7 +155,7 @@ def main() -> int: # their schema creation and cleanup separate from other test cases. try: for index, node in enumerate(selected, 1): - if not run_node(node, output / f"{index:03d}"): + if not run_node(node, output / f"{index:03d}", timeout_seconds=args.case_timeout): return 1 passed_nodes.append(node) summary["complete"] = True diff --git a/tests/test_atomic_memory_migration_shards.py b/tests/test_atomic_memory_migration_shards.py index 633eb1a6bd..381ed20d09 100644 --- a/tests/test_atomic_memory_migration_shards.py +++ b/tests/test_atomic_memory_migration_shards.py @@ -184,6 +184,32 @@ def test_collect_only_does_not_claim_execution(tmp_path: Path) -> None: assert not (tmp_path / "executed.txt").exists() +def test_case_deadline_does_not_count_a_timed_out_test_as_passed(tmp_path: Path) -> None: + (tmp_path / "test_cases.py").write_text( + "import time\ndef test_oceanbase_slow():\n time.sleep(30)\n", + encoding="utf-8", + ) + output = tmp_path / "timed-out" + result = run_runner(tmp_path, output, "--case-timeout", "2") + + assert result.returncode == 1, result.stdout + result.stderr + report = json.loads((output / "summary.json").read_text()) + assert report["case_timeout_seconds"] == 2 + assert report["complete"] is False + assert report["passed_nodes"] == [] + assert "FAIL exit=124" in (output / "001/result.txt").read_text() + + +@pytest.mark.parametrize("deadline", ["0", "-1"]) +def test_invalid_case_deadline_is_rejected_before_collection(tmp_path: Path, deadline: str) -> None: + output = tmp_path / "invalid-deadline" + result = run_runner(tmp_path, output, f"--case-timeout={deadline}") + + assert result.returncode == 2 + assert "case-timeout must be positive" in result.stderr + assert not output.exists() + + @pytest.mark.parametrize("outcome", ["fail", "skip", "interrupt"]) def test_unsuccessful_case_is_not_counted_as_passed_and_is_not_retried(tmp_path: Path, outcome: str) -> None: write_suite(tmp_path, 3, outcome=outcome) From 40356cba6ae53ee1c51a8499ec654fdd7806c725 Mon Sep 17 00:00:00 2001 From: knqiufan Date: Thu, 5 Nov 2026 14:03:32 +0800 Subject: [PATCH 6/8] fix(ci): account for OceanBase acceptance setup and replay --- .github/workflows/e2e-harness.yml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/.github/workflows/e2e-harness.yml b/.github/workflows/e2e-harness.yml index db729dd73d..4d33ef7e5a 100644 --- a/.github/workflows/e2e-harness.yml +++ b/.github/workflows/e2e-harness.yml @@ -544,8 +544,8 @@ jobs: # Main supplies scope, so the detector ancestor is intentionally skipped. if: ${{ !cancelled() && needs.validate.result == 'success' }} runs-on: ubuntu-latest - # OceanBase regressions can take 32 minutes before the separate replay scenarios. - timeout-minutes: ${{ matrix.database == 'oceanbase' && 60 || 40 }} + # Reserve 50m for OceanBase regressions, 15m for replay, and 10m for setup/evidence/cleanup. + timeout-minutes: ${{ matrix.database == 'oceanbase' && 75 || 40 }} strategy: fail-fast: false matrix: @@ -564,7 +564,8 @@ jobs: version: ${{ env.UV_VERSION }} - name: Verify OceanBase Atomic Memory, HTTP and archive regressions - timeout-minutes: 40 + # The 22 tests alone took 39m; this step also starts the database and installs dependencies. + timeout-minutes: 50 if: matrix.database == 'oceanbase' env: COMPOSE_PROJECT_NAME: powercontext-e2e-oceanbase From 9f5e9a8285356288b4821b1661220a3053996527 Mon Sep 17 00:00:00 2001 From: knqiufan Date: Thu, 5 Nov 2026 16:56:33 +0800 Subject: [PATCH 7/8] fix(desktop): report candidate version from runtime package --- desktop/src-tauri/src/ipc.rs | 3 ++- desktop/src-tauri/tests/ipc.rs | 39 +++++++++++++++++++++++++++++++++- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/desktop/src-tauri/src/ipc.rs b/desktop/src-tauri/src/ipc.rs index 2bdfc10551..a48fab787f 100644 --- a/desktop/src-tauri/src/ipc.rs +++ b/desktop/src-tauri/src/ipc.rs @@ -16,6 +16,7 @@ use crate::error::SafeError; use serde::Serialize; +use tauri::Manager; use ts_rs::TS; #[derive(Serialize, TS)] @@ -41,7 +42,7 @@ pub fn foundation_info( ) -> Result { authorize_window(window.label())?; Ok(FoundationInfo { - version: env!("CARGO_PKG_VERSION").into(), + version: window.package_info().version.to_string(), phase: "S3".into(), credential_backend: credential_backend(current_target_os()).into(), server_connected: false, diff --git a/desktop/src-tauri/tests/ipc.rs b/desktop/src-tauri/tests/ipc.rs index bc294269e3..fc211d9eca 100644 --- a/desktop/src-tauri/tests/ipc.rs +++ b/desktop/src-tauri/tests/ipc.rs @@ -16,7 +16,7 @@ use powercontext_desktop::ipc::allowed_navigation; use tauri::{ - ipc::{CallbackFn, InvokeBody}, + ipc::{CallbackFn, InvokeBody, InvokeResponseBody}, test::{INVOKE_KEY, get_ipc_response, mock_builder}, webview::InvokeRequest, }; @@ -33,6 +33,43 @@ fn test_context() -> tauri::Context { tauri::generate_context!() } +#[test] +fn foundation_info_reports_the_runtime_candidate_version() { + use tauri::Manager; + + let mut context = test_context(); + context.package_info_mut().version = "1.2.3".parse().unwrap(); + let app = mock_builder() + .invoke_handler(tauri::generate_handler![ + powercontext_desktop::ipc::foundation_info + ]) + .build(context) + .unwrap(); + let window = app.get_webview_window("main").unwrap_or_else(|| { + tauri::WebviewWindowBuilder::new(&app, "main", Default::default()) + .build() + .unwrap() + }); + let response = get_ipc_response( + &window, + InvokeRequest { + cmd: "foundation_info".into(), + callback: CallbackFn(0), + error: CallbackFn(1), + url: LOCAL_ORIGIN.parse().unwrap(), + body: InvokeBody::default(), + headers: Default::default(), + invoke_key: INVOKE_KEY.into(), + }, + ) + .unwrap(); + let InvokeResponseBody::Json(body) = response else { + panic!("foundation_info must return JSON"); + }; + let value: serde_json::Value = serde_json::from_str(&body).unwrap(); + assert_eq!(value["version"], "1.2.3"); +} + #[test] fn permissions_reject_untrusted_window_origin_and_arbitrary_commands() { let dir = tempfile::tempdir().unwrap(); From 97fe797676a0d04ba89eeabdcf82c36a710108ed Mon Sep 17 00:00:00 2001 From: knqiufan Date: Thu, 5 Nov 2026 16:56:33 +0800 Subject: [PATCH 8/8] test(release): bind cleanup checks to process identity --- tests/test_upgrade_release_gate.py | 34 +++++++++++++++++++++--------- 1 file changed, 24 insertions(+), 10 deletions(-) diff --git a/tests/test_upgrade_release_gate.py b/tests/test_upgrade_release_gate.py index 0bf96eeb91..e0296dec1a 100644 --- a/tests/test_upgrade_release_gate.py +++ b/tests/test_upgrade_release_gate.py @@ -911,14 +911,18 @@ def test_upgrade_command_owner_finishes_cleanup_after_gate_cancellation(tmp_path sentinel = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"]) with (report / "owner.log").open("w") as log: owner = subprocess.Popen([sys.executable, str(owner_script)], stdout=log, stderr=subprocess.STDOUT) - pids = [] + processes = [] try: deadline = time.monotonic() + 15 while not (report / "engine.pid").exists(): assert owner.poll() is None, (report / "owner.log").read_text() assert time.monotonic() < deadline, "Controlled processes did not become ready" time.sleep(0.02) - pids = [int((report / f"{role}.pid").read_text()) for role in ("root", "server", "engine")] + for role in ("root", "server", "engine"): + pid = int((report / f"{role}.pid").read_text()) + identity = _process_identity(pid) + assert identity is not None, f"{role} exited before cancellation" + processes.append((pid, identity)) work = Path((report / "workspace").read_text()) owner.send_signal(signal.SIGTERM if cancellation == "parent-term" else signal.SIGINT) if cancellation == "repeat-interrupt": @@ -929,12 +933,12 @@ def test_upgrade_command_owner_finishes_cleanup_after_gate_cancellation(tmp_path if cancellation == "parent-term": # The dead gate cannot await its owner; PDEATHSIG initiates cleanup. deadline = time.monotonic() + 10 - while any(_process_exists(pid) for pid in pids): + while any(_process_exists(pid, identity) for pid, identity in processes): assert time.monotonic() < deadline, "Detached descendants survived gate termination" time.sleep(0.02) else: # The second interrupt must not delete the workspace early. - assert not any(_process_exists(pid) for pid in pids) + assert not any(_process_exists(pid, identity) for pid, identity in processes) assert not work.exists() assert sentinel.poll() is None finally: @@ -944,16 +948,26 @@ def test_upgrade_command_owner_finishes_cleanup_after_gate_cancellation(tmp_path owner.wait(timeout=5) sentinel.terminate() sentinel.wait(timeout=5) - if cancellation == "parent-term" and pids and not any(_process_exists(pid) for pid in pids): + if ( + cancellation == "parent-term" + and processes + and not any(_process_exists(pid, identity) for pid, identity in processes) + ): shutil.rmtree(Path((report / "workspace").read_text()), ignore_errors=True) -def _process_exists(pid): +def _process_identity(pid: int) -> str | None: + # PID reuse during the parallel suite must not look like a surviving descendant. try: - os.kill(pid, 0) - except ProcessLookupError: - return False - return True + stat = Path(f"/proc/{pid}/stat").read_text() + except FileNotFoundError: + return None + fields = stat[stat.rfind(")") + 2 :].split() + return fields[19] if len(fields) > 19 else None + + +def _process_exists(pid: int, identity: str) -> bool: + return _process_identity(pid) == identity @pytest.fixture