diff --git a/.github/ci-paths.toml b/.github/ci-paths.toml index cb73f0fda2..394ce03480 100644 --- a/.github/ci-paths.toml +++ b/.github/ci-paths.toml @@ -33,7 +33,7 @@ tests = [ # 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", + "scripts/publish_desktop_release.py", "scripts/prepare_desktop_product.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.yml b/.github/workflows/desktop.yml index 06c2240dbe..992ab36126 100644 --- a/.github/workflows/desktop.yml +++ b/.github/workflows/desktop.yml @@ -201,6 +201,20 @@ jobs: - run: cargo clippy --locked --manifest-path src-tauri/Cargo.toml --all-targets -- -D warnings - run: cargo test --locked --manifest-path src-tauri/Cargo.toml - run: pnpm ipc:check + - name: Set up Python for product resource bundle regression + if: matrix.runner == 'macos-15' + uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2 + with: + version: '0.13.5' + enable-cache: true + - name: Verify full-size product resources with the real Tauri CLI + if: matrix.runner == 'macos-15' + working-directory: . + env: + POWERCONTEXT_TEST_TAURI_PRODUCT_BUNDLE: '1' + run: | + uv sync --locked --no-dev --group resource-build --python 3.12 + uv run --no-sync python -m pytest tests/test_desktop_product.py::test_tauri_cli_bundles_the_complete_helper_inventory -q - name: Verify native Keychain across processes run: cargo run --locked --manifest-path src-tauri/Cargo.toml --example credential_probe - name: Build unsigned macOS app and DMG diff --git a/.github/workflows/skill-guidance.yml b/.github/workflows/skill-guidance.yml index 9e47c1e16b..163478a936 100644 --- a/.github/workflows/skill-guidance.yml +++ b/.github/workflows/skill-guidance.yml @@ -36,10 +36,14 @@ jobs: - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7 with: python-version: '3.11' - cache: pip - cache-dependency-path: evaluation/skills/skill-up/requirements-dev.txt + - uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2 + with: + version: "0.10.12" - name: Install validation dependencies - run: python -m pip install -r evaluation/skills/skill-up/requirements-dev.txt + run: | + uv venv --python "$(command -v python)" "$RUNNER_TEMP/skill-guidance" + uv pip sync --python "$RUNNER_TEMP/skill-guidance/bin/python" evaluation/skills/skill-up/requirements-dev.txt + echo "$RUNNER_TEMP/skill-guidance/bin" >> "$GITHUB_PATH" - name: Install checksum-pinned skill-up shell: bash run: | diff --git a/desktop/src-tauri/src/ops_bridge/tests.rs b/desktop/src-tauri/src/ops_bridge/tests.rs index 66dc16c675..df5f201d1b 100644 --- a/desktop/src-tauri/src/ops_bridge/tests.rs +++ b/desktop/src-tauri/src/ops_bridge/tests.rs @@ -470,6 +470,81 @@ fn bundle_and_packaged_pins_reject_tampering_and_extra_files() { Some(OpsBridgeError::IntegrityFailure) ); } + +#[test] +fn packaged_ops_runs_without_a_user_provisioned_bundle_and_rejects_damage() { + let f = Fixture::new(); + fs::rename(f.support.join("bundle"), f.resources.join("ops")).unwrap(); + let host = f.host(); + assert_eq!(host.inspect().outcome, OpsOutcome::Succeeded); + assert!(!f.support.join("bundle").exists()); + fs::write(f.resources.join("ops/entry.py"), b"corrupt").unwrap(); + assert_eq!( + host.inspect().bridge_error, + Some(OpsBridgeError::IntegrityFailure) + ); +} + +#[test] +fn damaged_packaged_ops_never_falls_back_to_a_user_bundle() { + let f = Fixture::new(); + fs::create_dir(f.resources.join("ops")).unwrap(); + assert!(f.host().inspect().bridge_error.is_some()); + fs::remove_dir(f.resources.join("ops")).unwrap(); + assert_eq!(f.host().inspect().outcome, OpsOutcome::Succeeded); +} + +#[test] +fn packaged_ops_repairs_only_its_cache_and_preserves_it_when_app_resources_are_removed() { + let f = Fixture::new(); + let original = fs::read(f.support.join("bundle/entry.py")).unwrap(); + fs::rename(f.support.join("bundle"), f.resources.join("ops")).unwrap(); + let provision: serde_json::Value = + serde_json::from_slice(&fs::read(f.resources.join("ops-provision.json")).unwrap()).unwrap(); + let cache = f + .support + .join("bundles") + .join(provision["bundle_manifest_sha256"].as_str().unwrap()); + assert_eq!(f.host().inspect().outcome, OpsOutcome::Succeeded); + assert_eq!(fs::read(cache.join("entry.py")).unwrap(), original); + let journal = f.support.join("operator-journal"); + fs::write(&journal, b"preserve").unwrap(); + fs::write(cache.join("entry.py"), b"damaged").unwrap(); + assert_eq!(f.host().inspect().outcome, OpsOutcome::Succeeded); + assert_eq!(fs::read(cache.join("entry.py")).unwrap(), original); + let damaged = fs::read_dir(f.support.join("bundles")) + .unwrap() + .map(|entry| entry.unwrap().path()) + .find(|path| { + path.file_name() + .unwrap() + .to_string_lossy() + .starts_with("damaged-") + }) + .unwrap(); + assert_eq!(fs::read(damaged.join("entry.py")).unwrap(), b"damaged"); + fs::remove_dir_all(&f.resources).unwrap(); + assert_eq!(fs::read(cache.join("entry.py")).unwrap(), original); + assert_eq!(fs::read(journal).unwrap(), b"preserve"); +} + +#[test] +fn concurrent_packaged_provisioning_returns_busy_and_can_retry() { + let f = Fixture::new(); + fs::rename(f.support.join("bundle"), f.resources.join("ops")).unwrap(); + let host = f.host(); + assert_eq!(host.inspect().outcome, OpsOutcome::Succeeded); + let lock = fs::OpenOptions::new() + .read(true) + .write(true) + .open(f.support.join("bundles/provision.lock")) + .unwrap(); + lock.lock().unwrap(); + assert_eq!(host.inspect().bridge_error, Some(OpsBridgeError::Busy)); + drop(lock); + assert_eq!(host.inspect().outcome, OpsOutcome::Succeeded); +} + fn child( script: &str, deadline: Duration, @@ -929,8 +1004,8 @@ fn actual_independent_bundle_runs_through_native_trust_and_read_only_bridge() { .expect("set externally approved manifest pin"); assert!(trust::is_digest(&pin)); let f = Fixture::new(); - let bundle = f.support.join("bundle"); - fs::remove_dir_all(&bundle).unwrap(); + fs::remove_dir_all(f.support.join("bundle")).unwrap(); + let bundle = f.resources.join("ops"); copy(&source, &bundle); fs::write( f.resources.join("ops-provision.json"), diff --git a/desktop/src-tauri/src/ops_bridge/trust.rs b/desktop/src-tauri/src/ops_bridge/trust.rs index 10f934514a..b9d77aa2cb 100644 --- a/desktop/src-tauri/src/ops_bridge/trust.rs +++ b/desktop/src-tauri/src/ops_bridge/trust.rs @@ -166,7 +166,16 @@ impl Trust { let p = self.provision.as_ref().map_err(|e| *e)?; let support = self.support.as_ref().ok_or(Error::Unavailable)?; private_directory(support, true)?; - let root = support.join("bundle"); + let packaged = self + .resources + .as_ref() + .ok_or(Error::Unavailable)? + .join("ops"); + let root = match fs::symlink_metadata(&packaged) { + Ok(_) => provision_bundle(&packaged, support, &p.bundle_manifest_sha256)?, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => support.join("bundle"), + Err(_) => return Err(Error::Unavailable), + }; let executable = verify_bundle(&root, &p.bundle_manifest_sha256)?; // Digest-named copies remain immutable across concurrent operations and catalog updates. let mode = if p.binding_mode == Mode::TargetFile { @@ -282,6 +291,60 @@ struct Manifest { installed_bytes: u64, files_sha256: BTreeMap, } +// Only the application's pinned helper is copied here; Server installation and +// service mutation remain approved Ops operations. Never overwrite the legacy +// user-provisioned bundle, journals, configuration or Server data. +fn provision_bundle(source: &Path, support: &Path, pin: &str) -> Result { + verify_bundle(source, pin)?; + let bundles = support.join("bundles"); + private_directory(&bundles, true)?; + let lock_path = bundles.join("provision.lock"); + no_links(&lock_path)?; + let lock = fs::OpenOptions::new() + .create(true) + .truncate(false) + .read(true) + .write(true) + .open(&lock_path) + .map_err(|_| Error::Storage)?; + security::restrict(&lock_path, false)?; + lock.try_lock().map_err(|error| match error { + std::fs::TryLockError::WouldBlock => Error::Busy, + std::fs::TryLockError::Error(_) => Error::Storage, + })?; + let destination = bundles.join(pin); + if verify_bundle(&destination, pin).is_ok() { + return Ok(destination); + } + let temporary = tempfile::Builder::new() + .prefix("prepare-") + .tempdir_in(&bundles) + .map_err(|_| Error::Storage)?; + security::restrict(temporary.path(), true)?; + let mut files = BTreeSet::new(); + inventory(source, source, &mut files)?; + for name in files { + let target = temporary.path().join(relative(&name)?); + if let Some(parent) = target.parent() { + fs::create_dir_all(parent).map_err(|_| Error::Storage)?; + } + fs::copy(source.join(&name), &target).map_err(|_| Error::Storage)?; + } + verify_bundle(temporary.path(), pin)?; + // A broken cache is preserved for diagnosis. A failed copy leaves it intact; + // only a completely verified replacement can move it aside. + if fs::symlink_metadata(&destination).is_ok() { + no_links(&destination)?; + fs::rename( + &destination, + bundles.join(format!("damaged-{}", uuid::Uuid::new_v4())), + ) + .map_err(|_| Error::Storage)?; + } + fs::rename(temporary.path(), &destination).map_err(|_| Error::Storage)?; + Ok(destination) +} + fn verify_bundle(root: &Path, pin: &str) -> Result { no_links(root)?; let manifest_bytes = read(&root.join("bundle.json"), MAX_MANIFEST)?; diff --git a/docs/en/development/desktop-candidate-assembly.md b/docs/en/development/desktop-candidate-assembly.md index f85ae46256..69087680af 100644 --- a/docs/en/development/desktop-candidate-assembly.md +++ b/docs/en/development/desktop-candidate-assembly.md @@ -41,6 +41,6 @@ The checksum binds the exact manifest and asset bytes. Trust still comes from se 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). +Product packagers use [Desktop product resources](desktop-product-resources.md) to embed the independent helper and an approved durable Server catalog. Native code deploys the helper to a private current-user digest directory on first use, preserving it across Desktop removal. The candidate workflow still embeds only pins and requires external provisioning. Windows must retain both `pythonw.exe` for the Server service and `python.exe` for console use. Windows x64 and macOS arm64/x64 signing, clean-machine installation and repair, reboot/login, and native service lifecycle remain acceptance work in [#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/en/development/desktop-product-resources.md b/docs/en/development/desktop-product-resources.md new file mode 100644 index 0000000000..eac18a3545 --- /dev/null +++ b/docs/en/development/desktop-product-resources.md @@ -0,0 +1,52 @@ +--- +title: Desktop product resources +description: Prepare pinned, redistributable Ops resources and a durable Server download catalog for a product build. +--- + +# Desktop product resources + +The [candidate workflow](desktop-candidate-assembly.md) produces unqualified build artifacts. Product packaging additionally needs an embedded independent Ops runtime and a Server catalog pointing at approved durable downloads. `scripts/prepare_desktop_product.py` prepares these inputs without publishing assets, installing a Server, or claiming platform acceptance. + +## Prepare the exact inputs + +Use the native target's complete [resource producer output](managed-resource-production.md): `candidate.json`, `server/catalog.json`, `server/server.tar.gz`, and the expanded `ops/` tree. This is the producer's output directory, not the renamed aggregate Desktop artifact. Preserve its provenance and obtain the SHA-256 of `candidate.json` from the trusted producer run. A checksum found beside an untrusted download is not an independent trust source. + +Choose a non-`ci-` record already checked into `desktop/src-tauri/src/connections/compatibility.json`. Its Server commit, actual wheel digest, HTTP contract digest, and covered operations must match these resources and the Desktop checkout. If none matches, qualify that exact Server build through [#2101](https://github.com/oceanbase/powercontext/issues/2101) before preparing a product; do not copy a fixture record or relabel an unqualified candidate. + +Publish the exact Server archive to an approved immutable HTTPS asset URL before distributed clients use it. Allowlist the initial origin and any approved redirect origins. Temporary signed query URLs, placeholder hosts, Actions artifact downloads, and mutable `latest` routes are unsuitable. The script rejects query URLs and reserved placeholder hosts; release owners still approve the URL's immutability, origin policy, retention, and actual availability. It makes no network request. Ops retains the existing archive size/hash/inventory checks and interrupted-download recovery. + +On each native build host, from the repository root: + +```sh +uv run --locked --no-dev --group resource-build python scripts/prepare_desktop_product.py \ + --resources /absolute/producer-output \ + --candidate-sha256 \ + --output /absolute/product-resources \ + --version \ + --server-url \ + --allowed-origin \ + --qualification +``` + +Repeat `--allowed-origin` for redirects. Use a fresh output directory each time. The script verifies producer bindings, actual Server archive bytes, the complete Ops tree and executable, target identity, and the exact product qualification. It copies the helper, updates the catalog URL and qualification reference, pins the resulting catalog and Ops manifest, and atomically publishes the staging directory only after verification. Inputs remain unchanged. It emits: + +- `ops/`, `server/catalog.json`, and `ops-provision.json` for the application resource directory. +- `tauri.product.conf.json`, with product identity `com.powercontext.desktop`, the selected Desktop version, and a directory mapping that preserves the complete Ops tree, including dotfiles. Keep the staging directory at its original absolute location through the build. +- `product-resources.json`, which records producer/resource bindings and the selected qualification. Signing and installed acceptance are explicitly `not_performed`; this is not a publication manifest. + +From `desktop/`, build without `ci-fixtures` or preview features: + +```sh +pnpm install --frozen-lockfile +pnpm tauri build --config /absolute/product-resources/tauri.product.conf.json --ci --no-sign -- --locked +``` + +Tauri automatically applies the checked-in macOS platform configuration. Windows uses the checked-in current-user NSIS configuration. Do not also merge `tauri.ops.conf.json`, which stages only pins for the legacy externally provisioned helper. An unsigned build checks assembly; it does not establish clean-machine installation, service lifecycle, or release qualification. Signing nested code changes hashes: regenerate producer inventories and bindings, stage final resources again, then sign the outer application. [#2108](https://github.com/oceanbase/powercontext/issues/2108) and [#2109](https://github.com/oceanbase/powercontext/issues/2109) own platform acceptance and signing; [#2112](https://github.com/oceanbase/powercontext/issues/2112) owns publication of final tested bytes. + +## Runtime deployment and recovery + +On first Ops use, native code verifies the application's `ops/` against its packaged manifest pin, then copies it into `PowerContext/Ops/bundles/` under the OS current-user local data directory. It uses a private temporary directory and a cross-process lock, verifies the completed copy, and renames it into place. Concurrent provisioning returns `busy` for retry. The interpreter comes from that verified directory; no globally installed Python or `uv` is needed. Server installation and service changes still require the existing plan/approval flow and installation UI. + +A valid matching cache is reused. A damaged cache is moved to `damaged-` only after a replacement has passed verification. A damaged packaged resource fails closed, even if an older helper exists: reinstall a trusted Desktop package to repair the source. A package with no `ops/` retains the legacy `PowerContext/Ops/bundle` behavior. An empty or invalid `ops/` never selects that fallback. + +Desktop removal must leave the independent helper copies, operation references/journals, Server registration, and user data intact. Old digest directories and damaged copies are retained; this implementation performs no automatic cleanup and does not authorize removal of potentially active versions. This costs one copy per distinct helper version plus any quarantined copies. Every launch reads complete resource inventories, including the packaged source and deployed helper; no startup performance budget or clean-machine qualification is claimed. Existing Ops download, repair, status, cancellation, and resume contracts remain unchanged. diff --git a/docs/en/docs/operate/local-server-ops.md b/docs/en/docs/operate/local-server-ops.md index a2b7edf708..f30ef51858 100644 --- a/docs/en/docs/operate/local-server-ops.md +++ b/docs/en/docs/operate/local-server-ops.md @@ -220,6 +220,8 @@ validated before exposure. No raw stderr, provider exception, configuration cont ### Provisioning the bridge +Product builds can embed the helper and deploy it automatically to `PowerContext/Ops/bundles/` using [Desktop product resources](../../development/desktop-product-resources.md). The following fixed `bundle` directory is the legacy fallback for packages that omit `ops/`; invalid packaged resources never select it. Both layouts preserve Ops independently of Desktop removal. + A trusted native installer/packager publishes the independent Ops bundle at the fixed current-user location: - Windows: `%LOCALAPPDATA%\PowerContext\Ops\bundle`. diff --git a/docs/zh/development/desktop-candidate-assembly.md b/docs/zh/development/desktop-candidate-assembly.md index 5dcc434957..0979201c4c 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#配置桥接资源)。卸载 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) 负责验收。 +产品打包使用[桌面端产品资源](desktop-product-resources.md)流程,嵌入独立 helper 和获准的长期 Server 下载目录。原生代码在首次使用时把 helper 部署到当前用户私有的摘要目录,卸载 Desktop 时保留。候选工作流仍只嵌入摘要,需要外部配置 helper。Windows 保留服务使用的 `pythonw.exe` 和控制台使用的 `python.exe`。Windows x64、macOS 双架构的签名、干净机安装修复、重启/登录和原生服务生命周期仍由 [#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/docs/zh/development/desktop-product-resources.md b/docs/zh/development/desktop-product-resources.md new file mode 100644 index 0000000000..9ca6e6a3f2 --- /dev/null +++ b/docs/zh/development/desktop-product-resources.md @@ -0,0 +1,52 @@ +--- +title: 桌面端产品资源 +description: 为产品构建准备固定摘要的独立 Ops 运行时和长期可下载的 Server 资源目录。 +--- + +# 桌面端产品资源 + +[候选工作流](desktop-candidate-assembly.md) 产出未取得发布资格的构件。产品打包还需要随应用携带独立 Ops 运行时,并让 Server 资源目录指向获准的长期下载地址。`scripts/prepare_desktop_product.py` 准备这些输入,不发布资源、不安装 Server,也不将组装结果视为平台验收。 + +## 准备精确输入 + +使用目标原生平台的完整[资源生产器输出](managed-resource-production.md):`candidate.json`、`server/catalog.json`、`server/server.tar.gz` 和展开的 `ops/`。这里要求生产器的原始输出目录,不是文件已重命名的桌面端汇总构件。保留生产证据,并从可信生产运行取得 `candidate.json` 的 SHA-256;与不可信下载一起取得的校验文件不能独立建立信任。 + +从 `desktop/src-tauri/src/connections/compatibility.json` 选择已纳入仓库、ID 不以 `ci-` 开头的资格记录。Server 提交、实际 wheel 摘要、HTTP 契约摘要和操作覆盖范围必须与资源及 Desktop 检出版本匹配。没有匹配记录时,先按 [#2101](https://github.com/oceanbase/powercontext/issues/2101) 对该精确 Server 构建取得资格,不能复制测试记录或直接修改未验收候选的标签。 + +在客户端使用前,将准确的 Server 归档发布到获准的不可变 HTTPS 构件地址。允许列表应包含初始来源和经过批准的重定向来源。带签名查询参数的临时地址、占位域名、Actions 构件下载和可变的 `latest` 路径不适用。脚本拒绝查询参数和保留的占位域名;地址的不可变性、来源策略、保留期及实际可下载性仍由发布负责人确认。脚本不发网络请求。Ops 继续使用现有归档大小、摘要、文件清单检查和中断下载恢复能力。 + +在每个原生构建平台,从仓库根目录执行: + +```sh +uv run --locked --no-dev --group resource-build python scripts/prepare_desktop_product.py \ + --resources /absolute/producer-output \ + --candidate-sha256 <可信生产运行的candidate摘要> \ + --output /absolute/product-resources \ + --version <桌面端X.Y.Z> \ + --server-url <已批准的不可变Server归档HTTPS地址> \ + --allowed-origin <获准的HTTPS来源> \ + --qualification <内置产品资格记录ID> +``` + +重定向来源通过重复 `--allowed-origin` 提供。每次使用全新输出目录。脚本验证生产绑定、实际 Server 归档字节、完整 Ops 文件及可执行入口、目标身份和精确产品资格;复制 helper,更新目录的 URL 和资格引用,固定新目录及 Ops 清单摘要,全部验证后才原子发布暂存目录。输入保持不变。输出包括: + +- 应用资源目录所需的 `ops/`、`server/catalog.json` 和 `ops-provision.json`。 +- `tauri.product.conf.json`,包含产品标识 `com.powercontext.desktop`、选定的 Desktop 版本,以及保留完整 Ops 树(含隐藏文件)的目录映射。构建结束前保持暂存目录的绝对位置不变。 +- `product-resources.json`,记录生产和资源绑定及选定资格。签名和安装验收明确标记为 `not_performed`;它不是正式发布清单。 + +从 `desktop/` 执行,不启用 `ci-fixtures` 或预览特性: + +```sh +pnpm install --frozen-lockfile +pnpm tauri build --config /absolute/product-resources/tauri.product.conf.json --ci --no-sign -- --locked +``` + +Tauri 自动应用仓库中的 macOS 平台配置;Windows 使用仓库中的当前用户 NSIS 配置。不要同时合并 `tauri.ops.conf.json`,后者仅为旧的外部预配置 helper 暂存摘要。未签名构建只能检查组装,不能证明干净机安装、服务生命周期或发布资格。签名改变嵌套代码字节时,应重新生成生产清单与绑定、重新准备最终资源,再签外层应用。[#2108](https://github.com/oceanbase/powercontext/issues/2108) 和 [#2109](https://github.com/oceanbase/powercontext/issues/2109) 负责平台验收与签名;[#2112](https://github.com/oceanbase/powercontext/issues/2112) 负责发布最终验收过的字节。 + +## 运行时部署和恢复 + +首次使用 Ops 时,原生代码先按应用固定摘要验证随包 `ops/`,再复制到操作系统当前用户本地数据目录下的 `PowerContext/Ops/bundles/<清单SHA-256>`。使用私有临时目录和跨进程锁,完成复制和校验后才重命名到位。并发部署返回 `busy`,可以重试。解释器来自验证后的目录,用户不需要全局安装 Python 或 `uv`。Server 安装和服务变更仍通过现有安装 UI 及计划/批准流程执行。 + +匹配且完整的缓存会直接复用。缓存损坏时,只有完整替换副本通过校验,旧副本才移到 `damaged-`。随包资源损坏时,即使旧 helper 存在也拒绝执行,应重新安装可信 Desktop 包修复来源。不含 `ops/` 的应用保留旧的 `PowerContext/Ops/bundle` 行为;空目录或损坏的 `ops/` 不会触发回退。 + +卸载 Desktop 时必须保留独立 helper 副本、操作引用/日志、Server 注册和用户数据。旧摘要目录和损坏副本保留,此实现不自动清理,也不授权删除可能仍在运行的旧版本。因此,每个不同 helper 版本占一份空间,另加隔离的损坏副本。每次启动读取完整资源清单,包括随包来源与已部署 helper;不宣称满足启动性能预算或通过干净机验收。现有 Ops 下载、修复、状态、取消和恢复契约保持不变。 diff --git a/docs/zh/docs/operate/local-server-ops.md b/docs/zh/docs/operate/local-server-ops.md index a350625830..98ea24ac20 100644 --- a/docs/zh/docs/operate/local-server-ops.md +++ b/docs/zh/docs/operate/local-server-ops.md @@ -184,6 +184,8 @@ Resume 先通过包含 `resume: { operationId, expectedAttempt }` 的新 preflig ### 配置桥接资源 +产品构建可通过[桌面端产品资源](../../development/desktop-product-resources.md)随包携带 helper,并自动部署到 `PowerContext/Ops/bundles/<清单SHA-256>`。下述固定 `bundle` 目录仅用于不含 `ops/` 的旧包;随包资源损坏不会回退到它。两种布局均在卸载 Desktop 时保留独立 Ops。 + 可信原生安装器或打包器将独立 Ops 分发包发布到固定当前用户目录: - Windows:`%LOCALAPPDATA%\PowerContext\Ops\bundle`。 diff --git a/integrations/dsh/plugins/powercontext/scripts/e2e-server.mjs b/integrations/dsh/plugins/powercontext/scripts/e2e-server.mjs index a931ab9839..67cc4bfbd2 100644 --- a/integrations/dsh/plugins/powercontext/scripts/e2e-server.mjs +++ b/integrations/dsh/plugins/powercontext/scripts/e2e-server.mjs @@ -126,7 +126,9 @@ export async function startPowerContextServer(options = {}) { child.stderr?.on('data', (chunk) => logs.push(String(chunk))) const baseUrl = `http://127.0.0.1:${port}` try { - await waitForUrl(`${baseUrl}/health/live`, 30000, () => { + // On a cold runner, Python and the Server can finish startup just after 30s. + // Leave time for the caller's first request inside its 60s setup hook. + await waitForUrl(`${baseUrl}/health/live`, 45000, () => { if (child.exitCode !== null) throw new Error(`Server exited with code ${child.exitCode}`) }) } catch (error) { diff --git a/integrations/opendal/src/powercontext_connector_opendal/source.py b/integrations/opendal/src/powercontext_connector_opendal/source.py index 920719eccc..a71885c5be 100644 --- a/integrations/opendal/src/powercontext_connector_opendal/source.py +++ b/integrations/opendal/src/powercontext_connector_opendal/source.py @@ -157,12 +157,12 @@ def project(self, source: TextFileSnapshotSource, /) -> BaseModel: metadata["provider_version"] = source.provider_version if source.modified_at is not None: metadata["modified_at"] = source.modified_at.isoformat() - return _TEXT_EVIDENCE_MODEL( - source_type=TEXT_FILE_SNAPSHOT_SOURCE_NAME, - source_id=source.name, - content=source.content, - metadata=metadata, - ) + return _TEXT_EVIDENCE_MODEL.model_validate({ + "source_type": TEXT_FILE_SNAPSHOT_SOURCE_NAME, + "source_id": source.name, + "content": source.content, + "metadata": metadata, + }) def _snapshot_id(namespace: str, path: str, content_digest: str) -> str: diff --git a/scripts/ci_managed_resource_smoke.py b/scripts/ci_managed_resource_smoke.py index 316b451bad..7d70647f31 100644 --- a/scripts/ci_managed_resource_smoke.py +++ b/scripts/ci_managed_resource_smoke.py @@ -49,6 +49,28 @@ MAX_DIAGNOSTIC_BYTES = 64 * 1024 +@contextmanager +def smoke_phase(evidence: Path, name: str) -> Iterator[None]: + """Persist bounded, content-free progress even if the outer process is terminated.""" + evidence.mkdir(parents=True, exist_ok=True) + progress = evidence / "progress.jsonl" + + def write(status: str, elapsed_seconds: float) -> None: + with progress.open("a", encoding="utf-8", newline="\n") as stream: + stream.write(json.dumps({"phase": name, "status": status, "elapsed_seconds": elapsed_seconds}) + "\n") + stream.flush() + + started = time.monotonic() + write("started", 0) + try: + yield + except Exception: + write("failed", round(time.monotonic() - started, 3)) + raise + else: + write("completed", round(time.monotonic() - started, 3)) + + @contextmanager def preserve_failure(evidence: Path, workspace: Path) -> Iterator[None]: """Keep bounded fixture logs before temporary workspace cleanup; suppress raw errors.""" @@ -144,16 +166,19 @@ def check(candidate: Path, *, serve: bool = False, evidence_dir: Path | None = N preserve_failure(evidence, Path(temporary).resolve()), ): work = Path(temporary).resolve() - catalog_digest = (candidate / "server/catalog.sha256").read_text(encoding="utf-8").strip() - control = protect_directory(work / "control", create=True) - path = control / "catalog.json" - write_protected_file(path, (candidate / "server/catalog.json").read_bytes()) - catalog = ResourceCatalog.read(path, catalog_digest) - spec = catalog.select_current() - cache = protect_directory(work / "cache", create=True) - shutil.copyfile(candidate / "server/server.tar.gz", cache / (spec.archive_sha256 + ".archive")) - prepared = ResourceStore(cache).prepare(spec, work / "staging") - verify(spec, prepared.directory) + with smoke_phase(evidence, "catalog_and_cache"): + catalog_digest = (candidate / "server/catalog.sha256").read_text(encoding="utf-8").strip() + control = protect_directory(work / "control", create=True) + path = control / "catalog.json" + write_protected_file(path, (candidate / "server/catalog.json").read_bytes()) + catalog = ResourceCatalog.read(path, catalog_digest) + spec = catalog.select_current() + cache = protect_directory(work / "cache", create=True) + shutil.copyfile(candidate / "server/server.tar.gz", cache / (spec.archive_sha256 + ".archive")) + with smoke_phase(evidence, "prepare_resource"): + prepared = ResourceStore(cache).prepare(spec, work / "staging") + with smoke_phase(evidence, "verify_prepared"): + verify(spec, prepared.directory) moved = work / "relocated server" prepared.directory.rename(moved) if os.name != "nt": @@ -169,10 +194,14 @@ def check(candidate: Path, *, serve: bool = False, evidence_dir: Path | None = N poison.mkdir() (poison / "powercontext.py").write_text("raise RuntimeError('checkout import leaked')\n", encoding="utf-8") env = {**environment(), "PATH": "", "PYTHONPATH": str(poison), "PYTHONHOME": str(poison / "missing")} - _server_probe(moved, spec_values, spec.server_version, env) - service = _serve(moved, spec, control, env) if serve else {"launcher": "help_only"} - verify(spec, moved) - check_ops(candidate / "ops") + with smoke_phase(evidence, "server_probe"): + _server_probe(moved, spec_values, spec.server_version, env) + with smoke_phase(evidence, "server_lifecycle"): + service = _serve(moved, spec, control, env) if serve else {"launcher": "help_only"} + with smoke_phase(evidence, "verify_relocated"): + verify(spec, moved) + with smoke_phase(evidence, "ops_inspection"): + check_ops(candidate / "ops") result = { "status": "candidate_smoke_passed", "qualified": False, diff --git a/scripts/prepare_desktop_product.py b/scripts/prepare_desktop_product.py new file mode 100644 index 0000000000..c65ee3d69c --- /dev/null +++ b/scripts/prepare_desktop_product.py @@ -0,0 +1,219 @@ +# 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. + +"""Prepare a product's pinned Ops bundle and downloadable Server catalog before packaging.""" + +from __future__ import annotations + +import argparse +import os +import re +import shutil +import tempfile +from pathlib import Path, PureWindowsPath +from urllib.parse import urlsplit + +from desktop_candidate import PRODUCT_ID, PRODUCT_NAME, ROOT, digest, directory, json_bytes, read, require, version +from prepare_managed_resources import inventory +from produce_managed_resources import measure_windows_paths + +from powercontext.ops.resources import MAX_FILES, MAX_UNPACKED_BYTES, ResourceSpec + + +def prepare( + resources: Path, + candidate_sha256: str, + output: Path, + desktop_version: str, + server_url: str, + origins: list[str], + qualification: str, +) -> None: + """Read immutable producer inputs; publish a new staging directory only after verification.""" + require(version(desktop_version), "expected Desktop X.Y.Z version") + directory(resources) + require( + not output.resolve().is_relative_to(resources.resolve()) + and not resources.resolve().is_relative_to(output.resolve()), + "resources and output must not contain one another", + ) + require(digest(resources / "candidate.json") == candidate_sha256, "producer candidate digest mismatch") + candidate = read(resources / "candidate.json") + require(candidate["format_version"] == 1, "unsupported producer candidate") + binding = candidate["binding"] + catalog_path = resources / "server/catalog.json" + require(digest(catalog_path) == candidate["catalog_sha256"], "producer catalog digest mismatch") + catalog = read(catalog_path) + require(catalog["format_version"] == 1 and len(catalog["resources"]) == 1, "expected one Server resource") + spec = ResourceSpec.model_validate(catalog["resources"][0]) + require(spec.server_version == binding["server_version"], "Server version mismatch") + require( + spec.archive_sha256 == binding["server_archive_sha256"] == digest(resources / "server/server.tar.gz"), + "Server archive digest mismatch", + ) + require((resources / "server/server.tar.gz").stat().st_size == spec.archive_size, "Server archive size mismatch") + require(digest(resources / "ops/bundle.json") == binding["ops_bundle_manifest_sha256"], "Ops manifest mismatch") + directory(resources / "ops") + files = inventory(resources / "ops") + manifest = read(resources / "ops/bundle.json") + require( + manifest["format_version"] == 1 and manifest["arguments"] == ["-I", "-S", "-B", "entry.py"], + "unsupported Ops launcher", + ) + require( + manifest["platform"] == {"windows": "win32", "macos": "darwin"}[spec.platform] + and manifest["architecture"].lower() + in ({"arm64", "aarch64"} if spec.architecture == "arm64" else {"x86_64", "amd64"}), + "Ops and Server target mismatch", + ) + require( + set(manifest) + == { + "format_version", + "python_version", + "platform", + "architecture", + "python_relative", + "arguments", + "requirements_sha256", + "installed_bytes", + "files_sha256", + } + and isinstance(manifest["python_version"], str) + and 0 < len(manifest["python_version"]) <= 128 + and re.fullmatch(r"[0-9a-f]{64}", manifest["requirements_sha256"]) is not None + and (resources / "ops/bundle.json").stat().st_size <= 16 * 1024 * 1024, + "unsupported Ops manifest", + ) + content = [f for f in files if f["path"] != "bundle.json"] + require( + 0 < len(content) <= MAX_FILES and sum(f["size"] for f in content) <= MAX_UNPACKED_BYTES, + "Ops bundle exceeds native limits", + ) + require( + {f["path"]: f["sha256"] for f in content} == manifest["files_sha256"] + and sum(f["size"] for f in content) == manifest["installed_bytes"], + "Ops contents mismatch", + ) + require( + manifest["python_relative"].startswith("runtime/") + and any(f["path"] == manifest["python_relative"] and f["executable"] for f in content) + and "entry.py" in manifest["files_sha256"], + "missing executable Ops interpreter or entry", + ) + if os.name == "nt": + ops_root = PureWindowsPath(os.environ["LOCALAPPDATA"]) / "PowerContext/Ops/bundles" + measure_windows_paths(ops_root / binding["ops_bundle_manifest_sha256"], files) + measure_windows_paths(ops_root / ("prepare-" + "0" * 6), files) + operations = read(ROOT / "desktop/src-tauri/src/transport/operations.json") + profiles = read(ROOT / "desktop/src-tauri/src/connections/compatibility.json") + matches = [ + p + for p in profiles + if p["id"] == qualification + and not p["id"].startswith("ci-") + and p["serverCommit"] == binding["source_commit"] + and p["artifactSha256"] == binding["server_wheel_sha256"] + and p["contractSha256"] == operations["contractSha256"] + and set(operations["operations"]).issubset(p["operations"]) + ] + require(len(matches) == 1, "no exact bundled product qualification for this Server wheel and operation set") + require( + "git+https://github.com/oceanbase/powercontext@" + binding["source_commit"] in spec.source_refs, + "Server source identity missing", + ) + host = urlsplit(server_url).hostname or "" + require( + bool(host) + and not host.endswith((".invalid", ".localhost", ".test", ".example")) + and host != "localhost" + and not urlsplit(server_url).query, + "expected durable distribution URL", + ) + updated = spec.model_dump(mode="json") + updated.update(url=server_url, allowed_origins=origins, qualification_ref=qualification) + product = ResourceSpec.model_validate(updated) + require(not output.exists() and not output.is_symlink(), "output already exists; use a fresh staging directory") + output.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(prefix=".desktop-product-", dir=output.parent) as temporary: + stage = Path(temporary) / "product" + stage.mkdir() + shutil.copytree(resources / "ops", stage / "ops") + require(inventory(stage / "ops") == files, "copied Ops contents changed") + (stage / "server").mkdir() + (stage / "server/catalog.json").write_bytes( + json_bytes({"format_version": 1, "resources": [product.model_dump(mode="json")]}) + ) + provision = { + "format_version": 1, + "binding_mode": "managed_catalog", + "bundle_manifest_sha256": binding["ops_bundle_manifest_sha256"], + "catalog_sha256": digest(stage / "server/catalog.json"), + } + (stage / "ops-provision.json").write_bytes(json_bytes(provision)) + # Tauri walks a directory mapping recursively, preserving nested paths + # and dotfiles without putting the full inventory in TAURI_CONFIG. + mappings = {str(output.resolve() / "ops"): "ops/"} + mappings.update({str(output.resolve() / p): p for p in ("ops-provision.json", "server/catalog.json")}) + (stage / "tauri.product.conf.json").write_bytes( + json_bytes({ + "productName": PRODUCT_NAME, + "identifier": PRODUCT_ID, + "version": desktop_version, + "bundle": {"shortDescription": "PowerContext Desktop", "resources": mappings}, + }) + ) + (stage / "product-resources.json").write_bytes( + json_bytes({ + "format_version": 1, + "producer_candidate_sha256": candidate_sha256, + "server_archive_sha256": spec.archive_sha256, + "source_commit": binding["source_commit"], + "server_wheel_sha256": binding["server_wheel_sha256"], + "qualification": matches[0], + "catalog_sha256": provision["catalog_sha256"], + "ops_bundle_manifest_sha256": provision["bundle_manifest_sha256"], + "signing": "not_performed", + "installed_acceptance": "not_performed", + }) + ) + stage.rename(output) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--resources", type=Path, required=True) + parser.add_argument("--candidate-sha256", required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--version", required=True) + parser.add_argument("--server-url", required=True) + parser.add_argument("--allowed-origin", action="append", required=True) + parser.add_argument("--qualification", required=True) + args = parser.parse_args() + try: + prepare( + args.resources, + args.candidate_sha256, + args.output, + args.version, + args.server_url, + args.allowed_origin, + args.qualification, + ) + except (OSError, ValueError, KeyError, TypeError) as error: + parser.exit(1, f"Product resources rejected: {error}\n") + + +if __name__ == "__main__": + main() diff --git a/scripts/prepare_managed_resources.py b/scripts/prepare_managed_resources.py index c5f51390ee..fee9db701b 100644 --- a/scripts/prepare_managed_resources.py +++ b/scripts/prepare_managed_resources.py @@ -129,8 +129,9 @@ def _download(url: str, partial: Path) -> None: 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: + # curl does not retry every TLS connection reset, or a Windows + # process crash. Retry once from an empty partial, then fail closed. + if attempt or error.returncode not in {35, _WINDOWS_ACCESS_VIOLATION}: raise partial.unlink(missing_ok=True) else: diff --git a/tests/e2e/test_worker_otlp.py b/tests/e2e/test_worker_otlp.py index 5b9d14c0f3..86878f9035 100644 --- a/tests/e2e/test_worker_otlp.py +++ b/tests/e2e/test_worker_otlp.py @@ -111,6 +111,61 @@ def _spans(received): ] +def _wait_for_failure_stats(client, scope, family, trace_id): + # Child and supervisor spans can arrive before the supervisor reaps the + # worker and publishes retry diagnostics. + deadline = time.monotonic() + 20 + while True: + stats = client.post( + "/v1/stats", + json={"selection": {"mode": "exact", "scope_ids": [scope]}, "include_processing": True}, + ) + assert stats.status_code == 200 + failed = next(row for row in stats.json()["by_scope"][0]["processing"] if row["family"] == family) + if ( + failed["last_error_worker_id"] and failed["last_error_trace_id"] == trace_id + ) or time.monotonic() >= deadline: + return failed + time.sleep(0.05) + + +def test_wait_for_failure_stats_requires_the_observed_attempt(monkeypatch): + class Response: + status_code = 200 + + def __init__(self, worker_id, trace_id): + self.worker_id = worker_id + self.trace_id = trace_id + + def json(self): + return { + "by_scope": [ + { + "processing": [ + { + "family": "topic-memory", + "last_error_worker_id": self.worker_id, + "last_error_trace_id": self.trace_id, + } + ] + } + ] + } + + class Client: + responses = iter([Response(None, None), Response("previous", "old"), Response("current", "expected")]) + + def post(self, path, *, json): + assert path == "/v1/stats" + assert json["selection"]["scope_ids"] == ["scope"] + return next(self.responses) + + monkeypatch.setattr(time, "sleep", lambda _delay: None) + result = _wait_for_failure_stats(Client(), "scope", "topic-memory", "expected") + assert result["last_error_worker_id"] == "current" + assert result["last_error_trace_id"] == "expected" + + def _blocked_worker(_assignment: ArtifactProcessingWorkAssignment): raise ArtifactProcessingBlockedError( ArtifactProcessingBlock("frontier", "topic_memory", "window_attempt_limit", (("attempts", 3),)) @@ -306,13 +361,8 @@ def test_builtin_spawned_worker_exports_model_and_execution_spans_to_otlp( ) if timeout: assert outcomes["powercontext.operation.outcome"] == "failure" - stats = client.post( - "/v1/stats", - json={"selection": {"mode": "exact", "scope_ids": [scope]}, "include_processing": True}, - ) - assert stats.status_code == 200 - failed = next(row for row in stats.json()["by_scope"][0]["processing"] if row["family"] == family) - assert failed["last_error_worker_id"] + failed = _wait_for_failure_stats(client, scope, family, execution.trace_id.hex()) + assert failed["last_error_worker_id"], failed assert failed["last_error_trace_id"] == execution.trace_id.hex() assert outcomes["powercontext.error.category"] == "timeout" else: diff --git a/tests/test_desktop_product.py b/tests/test_desktop_product.py new file mode 100644 index 0000000000..4eb4b4b1bc --- /dev/null +++ b/tests/test_desktop_product.py @@ -0,0 +1,277 @@ +# 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. + +"""Product staging with small synthetic resources; no platform qualification claims.""" + +import json +import os +import shutil +import subprocess +import sys +from pathlib import Path + +import prepare_desktop_product as product +import pytest +from desktop_candidate import digest, json_bytes +from prepare_managed_resources import inventory + +from tests.test_ops_resources import _archive, _spec + +_ROOT = Path(__file__).resolve().parents[1] + + +def fixture(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> tuple[Path, str, Path]: + root = tmp_path / "producer" + (root / "server").mkdir(parents=True) + (root / "ops/runtime").mkdir(parents=True) + (root / "ops/entry.py").write_text("# fixture") + (root / "ops/.runtime-marker").write_bytes(b"included") + python = root / "ops/runtime/python.exe" + python.write_bytes(b"synthetic interpreter") + python.chmod(0o755) + content = inventory(root / "ops") + manifest = { + "format_version": 1, + "python_version": "3.13.0", + "requirements_sha256": "d" * 64, + "platform": "win32", + "architecture": "amd64", + "python_relative": "runtime/python.exe", + "arguments": ["-I", "-S", "-B", "entry.py"], + "installed_bytes": sum(f["size"] for f in content), + "files_sha256": {f["path"]: f["sha256"] for f in content}, + } + (root / "ops/bundle.json").write_bytes(json_bytes(manifest)) + archive = _archive() + (root / "server/server.tar.gz").write_bytes(archive) + spec = _spec(archive, source_refs=["git+https://github.com/oceanbase/powercontext@" + "a" * 40]) + (root / "server/catalog.json").write_bytes( + json_bytes({"format_version": 1, "resources": [spec.model_dump(mode="json")]}) + ) + candidate = { + "format_version": 1, + "catalog_sha256": digest(root / "server/catalog.json"), + "binding": { + "source_commit": "a" * 40, + "server_version": "1.0.0", + "server_wheel_sha256": "b" * 64, + "server_archive_sha256": digest(root / "server/server.tar.gz"), + "ops_bundle_manifest_sha256": digest(root / "ops/bundle.json"), + }, + } + (root / "candidate.json").write_bytes(json_bytes(candidate)) + repo = tmp_path / "repository" + for folder in ("connections", "transport"): + (repo / "desktop/src-tauri/src" / folder).mkdir(parents=True) + (repo / "desktop/src-tauri/src/transport/operations.json").write_bytes( + json_bytes({"contractSha256": "c" * 64, "operations": {"search_memory": {}}}) + ) + (repo / "desktop/src-tauri/src/connections/compatibility.json").write_bytes( + json_bytes([ + { + "id": "qualified", + "serverCommit": "a" * 40, + "artifactSha256": "b" * 64, + "contractSha256": "c" * 64, + "operations": ["search_memory"], + "evidence": "synthetic", + } + ]) + ) + monkeypatch.setattr(product, "ROOT", repo) + return root, digest(root / "candidate.json"), tmp_path / "product" + + +def run(inputs: tuple[Path, str, Path], **changes: str) -> None: + root, pin, output = inputs + product.prepare( + root, + pin, + output, + "1.2.3", + changes.get("url", "https://downloads.powercontext.org/server.tar.gz"), + ["https://downloads.powercontext.org"], + changes.get("qualification", "qualified"), + ) + + +def large_fixture(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> tuple[Path, str, Path]: + root, _, output = fixture(tmp_path, monkeypatch) + for group in range(100): + directory = root / "ops/packages" / f"group-{group:03d}" + directory.mkdir(parents=True) + for entry in range(151 if group < 54 else 152): + (directory / f"module-{entry:03d}.py").write_bytes(b"synthetic module\n") + hidden = root / "ops/.hidden-package" + hidden.mkdir() + (hidden / ".nested-marker").write_bytes(b"nested hidden resource") + files = inventory(root / "ops") + manifest_path = root / "ops/bundle.json" + manifest = json.loads(manifest_path.read_bytes()) + content = [f for f in files if f["path"] != "bundle.json"] + manifest["files_sha256"] = {f["path"]: f["sha256"] for f in content} + manifest["installed_bytes"] = sum(f["size"] for f in content) + manifest_path.write_bytes(json_bytes(manifest)) + candidate_path = root / "candidate.json" + candidate = json.loads(candidate_path.read_bytes()) + candidate["binding"]["ops_bundle_manifest_sha256"] = digest(manifest_path) + candidate_path.write_bytes(json_bytes(candidate)) + return root, digest(candidate_path), output + + +def test_product_config_stays_bounded_for_a_complete_helper_inventory( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + inputs = large_fixture(tmp_path, monkeypatch) + run(inputs) + output = inputs[2] + config_bytes = (output / "tauri.product.conf.json").read_bytes() + config = json.loads(config_bytes) + assert len(inventory(output / "ops")) >= 15_146 + assert len(config_bytes) < 4096 + assert len(config["bundle"]["resources"]) == 3 + assert (output / "ops/.runtime-marker").read_bytes() == b"included" + assert (output / "ops/.hidden-package/.nested-marker").read_bytes() == b"nested hidden resource" + + +@pytest.mark.skipif( + sys.platform != "darwin" or os.environ.get("POWERCONTEXT_TEST_TAURI_PRODUCT_BUNDLE") != "1", + reason="requires an explicitly requested native macOS Tauri product build", +) +def test_tauri_cli_bundles_the_complete_helper_inventory(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + inputs = large_fixture(tmp_path, monkeypatch) + run(inputs) + output = inputs[2] + pnpm = shutil.which("pnpm") + assert pnpm is not None, "the pinned project Tauri CLI requires pnpm" + subprocess.run( + [ + pnpm, + "exec", + "tauri", + "build", + "--debug", + "--bundles", + "app", + "--ci", + "--no-sign", + "--config", + str(output / "tauri.product.conf.json"), + # The workflow already checks generated sources and TypeScript; + # build the frontend here without repeating generator downloads. + "--config", + '{"build":{"beforeBuildCommand":"pnpm exec vite build"}}', + "--", + "--locked", + ], + cwd=_ROOT / "desktop", + check=True, + timeout=1200, + ) + bundle = _ROOT / "desktop/src-tauri/target/debug/bundle/macos/PowerContext Desktop.app/Contents/Resources" + assert inventory(bundle / "ops") == inventory(output / "ops") + assert (bundle / "ops-provision.json").read_bytes() == (output / "ops-provision.json").read_bytes() + assert (bundle / "server/catalog.json").read_bytes() == (output / "server/catalog.json").read_bytes() + + +def test_product_staging_preserves_ops_and_pins_the_download(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + inputs = fixture(tmp_path, monkeypatch) + run(inputs) + root, _, output = inputs + assert inventory(output / "ops") == inventory(root / "ops") + provision = json.loads((output / "ops-provision.json").read_bytes()) + assert provision["catalog_sha256"] == digest(output / "server/catalog.json") + catalog = json.loads((output / "server/catalog.json").read_bytes()) + assert catalog["resources"][0]["qualification_ref"] == "qualified" + assert catalog["resources"][0]["url"] == "https://downloads.powercontext.org/server.tar.gz" + config = json.loads((output / "tauri.product.conf.json").read_bytes()) + assert config["version"] == "1.2.3" + assert config["identifier"] == "com.powercontext.desktop" + assert config["bundle"]["resources"][str(output / "ops")] == "ops/" + with pytest.raises(ValueError, match="output already exists"): + run(inputs) + assert inventory(output / "ops") == inventory(root / "ops") + + +@pytest.mark.parametrize("damage", ["ops", "archive", "catalog", "qualification", "url", "link"]) +def test_product_staging_rejects_invalid_inputs_without_publishing( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, damage: str +) -> None: + inputs = fixture(tmp_path, monkeypatch) + root, _, output = inputs + changes = {} + if damage == "ops": + (root / "ops/entry.py").write_text("changed") + elif damage == "archive": + (root / "server/server.tar.gz").write_bytes(b"changed") + elif damage == "catalog": + (root / "server/catalog.json").write_bytes(b"{}") + elif damage == "qualification": + changes["qualification"] = "ci-fixture" + elif damage == "url": + changes["url"] = "https://candidate.invalid/server.tar.gz" + else: + try: + (root / "ops/alias").symlink_to("entry.py") + except OSError: + pytest.skip("symlink creation unavailable on this host") + with pytest.raises(ValueError): + run(inputs, **changes) + assert not output.exists() + + +@pytest.mark.parametrize("field", ["serverCommit", "artifactSha256", "contractSha256", "operations"]) +def test_product_requires_exact_bundled_qualification( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + field: str, +) -> None: + inputs = fixture(tmp_path, monkeypatch) + path = product.ROOT / "desktop/src-tauri/src/connections/compatibility.json" + profiles = json.loads(path.read_bytes()) + profiles[0][field] = [] if field == "operations" else "mismatch" + path.write_bytes(json_bytes(profiles)) + with pytest.raises(ValueError, match="no exact bundled product qualification"): + run(inputs) + assert not inputs[2].exists() + + +def test_product_rejects_an_unsupported_manifest_even_with_a_matching_producer_pin( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + root, _, output = fixture(tmp_path, monkeypatch) + path = root / "ops/bundle.json" + manifest = json.loads(path.read_bytes()) + del manifest["requirements_sha256"] + path.write_bytes(json_bytes(manifest)) + candidate = json.loads((root / "candidate.json").read_bytes()) + candidate["binding"]["ops_bundle_manifest_sha256"] = digest(path) + (root / "candidate.json").write_bytes(json_bytes(candidate)) + with pytest.raises(ValueError, match="unsupported Ops manifest"): + run((root, digest(root / "candidate.json"), output)) + assert not output.exists() + + +@pytest.mark.parametrize("relative", ["ops/product", "ops", "."]) +def test_product_output_cannot_overlap_its_resource_inputs( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + relative: str, +) -> None: + root, pin, _ = fixture(tmp_path, monkeypatch) + original = inventory(root) + with pytest.raises(ValueError, match="must not contain one another"): + run((root, pin, root / relative)) + assert inventory(root) == original diff --git a/tests/test_managed_resource_producer.py b/tests/test_managed_resource_producer.py index 782e973f87..e897d5273c 100644 --- a/tests/test_managed_resource_producer.py +++ b/tests/test_managed_resource_producer.py @@ -32,7 +32,7 @@ import httpx import pytest from build_intel_managed_wheel import _check_linkage, native_build_environment, verify_backend -from ci_managed_resource_smoke import MAX_DIAGNOSTIC_BYTES, preserve_failure +from ci_managed_resource_smoke import MAX_DIAGNOSTIC_BYTES, preserve_failure, smoke_phase from prepare_managed_resources import ( _locked_dependencies, acquire, @@ -214,8 +214,9 @@ def test_corrupt_cached_interpreter_is_rejected_without_network(tmp_path: Path) @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 +@pytest.mark.parametrize("returncode", [35, 0xC0000005]) +def test_acquire_retries_transport_failure_or_windows_curl_crash_with_fresh_partial( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, retry_succeeds: bool, returncode: int ) -> None: content = b"locked candidate bytes" item = { @@ -231,7 +232,7 @@ def download(command: list[str], **_options: Any) -> None: with partial.open("xb") as stream: stream.write(content if succeeded else b"incomplete") if not succeeded: - raise subprocess.CalledProcessError(0xC0000005, command) + raise subprocess.CalledProcessError(returncode, command) monkeypatch.setattr(subprocess, "run", download) artifact = tmp_path / "wheel.whl" @@ -241,11 +242,31 @@ def download(command: list[str], **_options: Any) -> None: else: with pytest.raises(subprocess.CalledProcessError) as error: acquire(item, artifact, tmp_path / "cache") - assert error.value.returncode == 0xC0000005 + assert error.value.returncode == returncode assert not artifact.exists() assert next(results, None) is None +def test_acquire_rejects_corrupt_bytes_after_tls_retry(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + item = {"url": "https://candidate.invalid/wheel.whl", "sha256": hashlib.sha256(b"approved").hexdigest()} + attempts = 0 + + def download(command: list[str], **_options: Any) -> None: + nonlocal attempts + attempts += 1 + partial = Path(command[command.index("--output") + 1]) + partial.write_bytes(b"incomplete" if attempts == 1 else b"unexpected") + if attempts == 1: + raise subprocess.CalledProcessError(35, command) + + monkeypatch.setattr(subprocess, "run", download) + artifact = tmp_path / "wheel.whl" + with pytest.raises(ValueError, match="locked digest"): + acquire(item, artifact) + assert attempts == 2 + assert not artifact.exists() + + def test_windows_layout_requires_console_and_windowless_interpreters(tmp_path: Path) -> None: source = tmp_path / "python.tar.gz" _runtime_archive(source) @@ -396,6 +417,22 @@ def test_smoke_failure_keeps_bounded_logs_after_temporary_cleanup(tmp_path: Path assert "raw error content" not in str(failed.value) +def test_smoke_progress_survives_failure_without_recording_exception_content(tmp_path: Path) -> None: + with smoke_phase(tmp_path, "prepare_resource"): + pass + with pytest.raises(ValueError), smoke_phase(tmp_path, "server_probe"): + message = "private failure detail" + raise ValueError(message) + progress = [json.loads(line) for line in (tmp_path / "progress.jsonl").read_text(encoding="utf-8").splitlines()] + assert [(entry["phase"], entry["status"]) for entry in progress] == [ + ("prepare_resource", "started"), + ("prepare_resource", "completed"), + ("server_probe", "started"), + ("server_probe", "failed"), + ] + assert "private failure detail" not in (tmp_path / "progress.jsonl").read_text(encoding="utf-8") + + @pytest.mark.skipif(sys.platform != "darwin", reason="requires real Mach-O compiler and load-command inspection") @pytest.mark.parametrize("architecture", ["arm64", "x86_64"]) @pytest.mark.parametrize("external", [None, "dependency", "rpath"]) @@ -541,8 +578,8 @@ def test_native_candidate_is_consumed_and_runs_independent_ops(native_candidates ], cwd=_ROOT, check=True, - # Leave room for the launcher and Ops phase deadlines, archive I/O, - # and writing failure evidence before the outer process is stopped. + # Leave room for the bounded probe, launcher and Ops phases, archive I/O, + # cleanup, and writing failure evidence before stopping the outer process. timeout=1200, )