diff --git a/.github/CI_POLICY.md b/.github/CI_POLICY.md new file mode 100644 index 000000000000..eecfcf624645 --- /dev/null +++ b/.github/CI_POLICY.md @@ -0,0 +1,128 @@ +# Codefx Linux CI coverage policy + +Codefx supports Linux amd64 (x86_64) only. Every build, test, formatter and generator +runs in GitHub Actions. Local work is limited to source edits and static review. + +## Candidate and upstream provenance + +`.github/upstream-ci.json` pins `openai/codex` `rust-v0.166.0` at +`6ff1e1ca3b30fc8b914720681fcf5fe62e95f856`. The policy job compares retained +upstream workflows and helpers against that immutable checkout. It rejects +unlisted changes to commands, selectors, conditions and action pins. + +PR validation checks out GitHub's synthetic merge revision. Current-source +packages record the checked-out commit, target, version and archive SHA256. +SDK CI downloads an artifact from the same workflow run and verifies all four +fields against its checkout before extracting or executing it. Published release +packages never substitute for the candidate. + +## Required coverage + +`blocking-ci.yml` aggregates these checks into `CI required`: + +- Baseline and coverage policy, including mutation/fault regression tests. +- Fast Rust formatting, dependency usage, benchmark smoke and lint-tool tests. +- The official Linux Bazel test graph, Clippy and release configuration checks. +- Workspace argument-comment lint whenever Rust or CI inputs change. +- GNU Cargo Clippy over the workspace, including test targets. +- GNU Cargo nextest over every workspace package. Core, TUI and app-server use + dedicated build groups; other packages are assigned deterministically to three + groups before compilation. No nextest test-name filter narrows this coverage. +- TypeScript SDK build, lint and integration tests; Python SDK lint/tests and + an independently installed Python SDK smoke test. +- Dependency/security policy, repository/architecture checks, spelling and size. +- Installer transaction, rollback and failure tests. +- Current-source amd64 musl release-configuration builds, native ELF/ABI + checks including execution of the V8 ABI probe on the native runner, package + validation, actual installation and reinstallation. + +Every required dependency must succeed. Failure, cancellation, an unexpected +skip or a disconnected producer fails the aggregate. SDK waits for source-package +verification and reuses those executables instead of compiling V8 a second time. + +## Extended compatibility + +`codefx-extended-ci.yml` also exposes the required Bazel checks as standalone +compatibility checks on main and manual runs. `postmerge-ci.yml` retains full +Linux Cargo and V8 verification; +`rust-ci-full.yml` also supports manual runs and `full-ci` branches. The expensive +workspace argument-comment lint remains in full Cargo CI. + +Full verification must pass on the source being released, together with the +amd64 native package check. A successful fast gate does not establish full-suite or +release readiness. Upstream syncs must run full Linux verification before release. +Branch protection must explicitly require `CI required`; the job name alone does +not configure GitHub protection. This PR does not change repository settings. + +## Explicit infrastructure adaptations + +The policy checker permits only these reviewed transformations: + +- Remove unsupported Windows, macOS and ARM64 runners and retired upstream publishers. +- Replace private Linux runners with hosted Ubuntu and allow cold-build budgets. +- Grant only `contents: read` and `actions: read` to the postmerge V8 workflow + call. Its child requires artifact read access; the caller must explicitly + allow it on repositories whose default token permissions omit Actions access. + A manual postmerge entrypoint validates the complete nested call and aggregate + before merging, alongside the existing main push trigger. +- Replace the SDK's Bazel CLI build with a verified same-run source package, + preserving SDK commands and running Jest serially on the small runner. +- Remove the duplicate Bazel test entry labelled musl: its matrix value only + selected cache names, and both entries built native GNU. Genuine musl coverage + is supplied by explicit Cargo targets and inspected native packages. +- Disable the local Bazel disk action cache to avoid duplicating cold build + outputs. Repository download caches remain available; BuildBuddy is optional. + `setup-bazel` replaces the home bazelrc, so its `bazelrc` input must import + the separate runner policy. A real Bazel probe checks the effective CPU/memory + caps and absence of action-cache writes after setup, with an explicitly enabled + cache as a positive control. Bazel 9.2 uses `--disk_cache=` to disable this cache. + Local actions use the runner's available CPUs and a 4096 MiB memory budget; + Cargo retains its two-job limit. Remote execution concurrency is unchanged. +- Limit local Bazel test execution to one test binary and two Rust test threads. + Libtest otherwise multiplies the build scheduler's concurrency and can exhaust + short authentication/catalog deadlines during native compilation. Preserve + every test and the product's deadlines; repeat the full provider suite under + competing CPU load in the targeted regression workflow. Stop the Bazel run on + its first failed test so a test failure is visible before the remaining native + build finishes. Passing runs still execute the complete selected test graph. + On runners without BuildBuddy, use exclusive test scheduling so execution + starts after the native build graph finishes. A one-binary limit alone still + allows compilation to compete with short protocol deadlines. Remote execution + keeps its existing scheduling. The targeted regression also repeats the full + exec-server capability-discovery suite with competing CPU work. +- Allow six hours for the complete Bazel graph and workspace argument-comment + lint, including source-built V8 when BuildBuddy credentials are unavailable. + Keep all test, Clippy and release-only + commands. Sample free disk throughout the build and report the minimum and + per-directory consumption before artifact/cache uploads, including on failure. +- Set the CI test profile to no debug information and no incremental state. + Bound sccache to 2 GiB, share download-only Cargo caches across profiles and + pin installed tool versions using the install action's supported `tool` input. +- Build the Linux sandbox payload before test archival, compile its digest into + consumers, and transfer the payload and digest with runtime test helpers. + Test runners verify the digest before staging the executable beside the CLI. + Resolve compatibility release inputs on both archive and test runners. +- Put Zig's local cache outside the checkout and report disk consumption. +- Supply the checksum-verified Codex V8 archive and pinned GNU voice SDK/runtime. + Keep voice version probes, voice tests and V8 consumers enabled. +- Generate Linux V8 bindings in CI from the pinned headers and sandbox release + defines. The published Unix archive uses a 64-byte inline TypedArray threshold; + its size-zero published binding is incompatible. Preserve archive checksum + verification and test the generated binding against the actual native library. +- Select V8 canary features explicitly with `--no-default-features`, enabling + `sandbox` only for that native variant. The normal workspace probe defaults to + the sandbox pair used by production; both canary variants retain all tests. +- Use the canonical DotSlash action URL and the cargo-deny container cache path. +- Omit the unavailable OpenAI Fence audit hook while retaining blob-size checks. + +Musl native dependencies use bounded network retries, an alternate libcap source +and atomic checksum-verified promotion. A checksum mismatch fails immediately; +transport failure may try another source. These rules have CI fault coverage. + +## Updating the baseline + +Update the source version, manifest and policy checkout together. Retain upstream +commands except for the listed transformations. Update regression tests whenever +upstream changes job structure. Run fast, full and native package checks against +one final amd64 candidate and report exact commits and Actions links. Pending, skipped, +cancelled and unavailable checks are never reported as passes. diff --git a/.github/actions/codefx-linux-runner/action.yml b/.github/actions/codefx-linux-runner/action.yml new file mode 100644 index 000000000000..f487ab8edbd2 --- /dev/null +++ b/.github/actions/codefx-linux-runner/action.yml @@ -0,0 +1,30 @@ +name: Codefx Linux runner +description: Adapt hosted Linux runner resources without changing upstream checks. +runs: + using: composite + steps: + - name: Reclaim unused hosted runner tools + if: runner.environment == 'github-hosted' + shell: bash + run: | + set -euo pipefail + sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc + df -h "$GITHUB_WORKSPACE" + - name: Bound local build resources + shell: bash + run: | + set -euo pipefail + # setup-bazel replaces the home bazelrc. Keep the policy in a separate + # file, imported both here and by setup-bazel's bazelrc input. + # Bazel 9.2 disables the action cache with an empty disk_cache path. + cat > "$RUNNER_TEMP/codefx-linux.bazelrc" <<'EOF' + build --local_resources=cpu=HOST_CPUS + build --local_resources=memory=4096 + common --disk_cache= + test --local_test_jobs=1 + test --test_env=RUST_TEST_THREADS=2 + EOF + printf '\nimport %s/codefx-linux.bazelrc\n' "$RUNNER_TEMP" >> "$HOME/.bazelrc" + echo 'CARGO_BUILD_JOBS=2' >> "$GITHUB_ENV" + echo 'CARGO_INCREMENTAL=0' >> "$GITHUB_ENV" + echo 'SCCACHE_CACHE_SIZE=2G' >> "$GITHUB_ENV" diff --git a/.github/actions/codefx-linux-v8-binding/action.yml b/.github/actions/codefx-linux-v8-binding/action.yml new file mode 100644 index 000000000000..6baa1290dfbf --- /dev/null +++ b/.github/actions/codefx-linux-v8-binding/action.yml @@ -0,0 +1,73 @@ +name: Codefx Linux V8 binding +description: Generate Cargo bindings from the native Unix V8 ABI policy. +inputs: + target: + description: Linux Rust target paired with the verified sandbox archive. + required: true +runs: + using: composite + steps: + - name: Restore binding generated from the pinned native headers + id: cache + uses: actions/cache@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5.0.4 + with: + path: ${{ runner.temp }}/codefx-v8-binding + key: codefx-v8-binding-v1-${{ inputs.target }}-${{ hashFiles('third_party/v8/**', 'patches/**', 'MODULE.bazel', 'MODULE.bazel.lock', 'codex-rs/Cargo.lock', '.github/actions/codefx-linux-v8-binding/action.yml') }} + - name: Prepare binding generator + if: steps.cache.outputs.cache-hit != 'true' + uses: ./.github/actions/prepare-bazel-ci + with: + target: v8-binding-${{ inputs.target }} + cache-scope: codefx-v8-binding + - name: Generate the matching sandbox release binding + if: steps.cache.outputs.cache-hit != 'true' + shell: bash + env: + TARGET: ${{ inputs.target }} + run: | + set -euo pipefail + case "$TARGET" in + x86_64-unknown-linux-gnu) platform=linux_amd64 ;; + aarch64-unknown-linux-gnu) platform=linux_arm64 ;; + x86_64-unknown-linux-musl) platform=linux_amd64_musl ;; + aarch64-unknown-linux-musl) platform=linux_arm64_musl ;; + *) echo "Unsupported Linux V8 binding target: $TARGET" >&2; exit 1 ;; + esac + label="//third_party/v8:rusty_v8_sandbox_binding_${TARGET//-/_}" + ./.github/scripts/run-bazel-ci.sh --remote-download-toplevel -- \ + build "--platforms=@llvm//platforms:$platform" -- "$label" + binding="$(./.github/scripts/run-bazel-ci.sh -- \ + cquery "--platforms=@llvm//platforms:$platform" --output=files -- "$label" | grep -E '\.rs$')" + test -f "$binding" + mkdir -p "$RUNNER_TEMP/codefx-v8-binding" + cp "$binding" "$RUNNER_TEMP/codefx-v8-binding/binding.rs" + - name: Verify native threshold and select the generated binding + shell: bash + run: | + set -euo pipefail + binding="$RUNNER_TEMP/codefx-v8-binding/binding.rs" + # The published Unix archive uses the owned policy's 64-byte threshold. + # Its published size-zero binding must not reach get_contents FFI. + # Bazel bindgen output can be one line without rustfmt spacing. + python3 - "$binding" <<'PY' + import pathlib + import re + import sys + binding = pathlib.Path(sys.argv[1]).read_text() + values = re.findall( + r"\bpub\s+const\s+v8__TYPED_ARRAY_MAX_SIZE_IN_HEAP\s*:\s*[^=;]+?=\s*(\d+)(?:usize|u32|u64)?\s*;", + binding, + ) + if values != ["64"]: + raise SystemExit(f"Expected exactly one native 64-byte threshold; found {values}") + print("Generated Linux V8 binding uses the native 64-byte threshold") + PY + echo "RUSTY_V8_SRC_BINDING_PATH=$binding" >> "$GITHUB_ENV" + - name: Preserve generated binding for CI diagnosis + if: always() + uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 + with: + name: codefx-v8-binding-${{ inputs.target }} + path: ${{ runner.temp }}/codefx-v8-binding/binding.rs + if-no-files-found: ignore + retention-days: 3 diff --git a/.github/actions/codefx-linux-voice-sdk/action.yml b/.github/actions/codefx-linux-voice-sdk/action.yml new file mode 100644 index 000000000000..39ee666cd281 --- /dev/null +++ b/.github/actions/codefx-linux-voice-sdk/action.yml @@ -0,0 +1,74 @@ +name: Codefx Linux voice SDK +description: Supply the repository-pinned native SDK to the official GNU Cargo checks. +runs: + using: composite + steps: + - name: Install native audio prerequisites + shell: bash + run: | + set -euo pipefail + sudo apt-get update -o Acquire::Retries=3 + sudo apt-get install -y --no-install-recommends libasound2-dev pkg-config + - name: Restore pinned native voice SDK + id: cache + uses: actions/cache@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5.0.4 + with: + path: ${{ runner.temp }}/codefx-voice-sdk + key: codefx-voice-sdk-v3-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('third_party/voice/**', 'MODULE.bazel', 'MODULE.bazel.lock', '.github/actions/codefx-linux-voice-sdk/action.yml') }} + - name: Prepare native SDK build tools + if: steps.cache.outputs.cache-hit != 'true' + uses: ./.github/actions/prepare-bazel-ci + with: + target: voice-sdk-${{ runner.arch }} + cache-scope: codefx-voice-sdk + - name: Build and stage the pinned SDK + if: steps.cache.outputs.cache-hit != 'true' + working-directory: ${{ github.workspace }} + shell: bash + run: | + set -euo pipefail + # The official Bazel recipe verifies pinned source archives and exports + # relocatable development inputs from its inspected native runtime. + ./.github/scripts/run-bazel-ci.sh --remote-download-toplevel -- \ + build --platforms=//:local_linux -- \ + //third_party/voice:native_sdk //third_party/voice:native_runtime + sdk="$(./.github/scripts/run-bazel-ci.sh -- \ + cquery --platforms=//:local_linux --output=files -- \ + //third_party/voice:native_sdk | grep -E '^(/|bazel-out/)')" + test -d "$sdk" + mkdir -p "$RUNNER_TEMP/codefx-voice-sdk" + cp -a "$sdk/." "$RUNNER_TEMP/codefx-voice-sdk/" + # Bazel outputs are read-only. The staged copy must accept the runtime + # directory and remain writable when restored from the Actions cache. + chmod -R u+w "$RUNNER_TEMP/codefx-voice-sdk" + runtime="$(./.github/scripts/run-bazel-ci.sh -- \ + cquery --platforms=//:local_linux --output=files -- \ + //third_party/voice:native_runtime | grep -E '^(/|bazel-out/)')" + test -d "$runtime" + mkdir -p "$RUNNER_TEMP/codefx-voice-sdk/runtime" + cp -a "$runtime/." "$RUNNER_TEMP/codefx-voice-sdk/runtime/" + chmod -R u+w "$RUNNER_TEMP/codefx-voice-sdk/runtime" + - name: Configure Cargo development inputs and runtime libraries + shell: bash + run: | + set -euo pipefail + sdk="$RUNNER_TEMP/codefx-voice-sdk" + test -f "$sdk/sdk.json" + wrapper="$RUNNER_TEMP/codefx-voice-pkg-config" + cat > "$wrapper" <<'EOF' + #!/bin/sh + exec /usr/bin/pkg-config --define-prefix "$@" + EOF + chmod +x "$wrapper" + # Keep the SDK ahead of host packages so GNU Cargo uses the same + # GLib/GStreamer versions as Bazel. ALSA remains a system ABI input. + echo "PKG_CONFIG_PATH=$sdk/lib/pkgconfig" >> "$GITHUB_ENV" + echo "PKG_CONFIG=$wrapper" >> "$GITHUB_ENV" + echo "LD_LIBRARY_PATH=$sdk/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" >> "$GITHUB_ENV" + echo "GST_PLUGIN_SYSTEM_PATH_1_0=$sdk/runtime/lib/gstreamer-1.0" >> "$GITHUB_ENV" + echo "GST_PLUGIN_PATH_1_0=$sdk/runtime/lib/gstreamer-1.0" >> "$GITHUB_ENV" + echo "GST_REGISTRY=$RUNNER_TEMP/codefx-voice-registry.bin" >> "$GITHUB_ENV" + # Load the receipt-verified plugins directly in Cargo tests, just as the + # packaged helper does. A host GStreamer scanner can have a different ABI. + echo "CODEX_TEST_VOICE_RUNTIME=$sdk/runtime" >> "$GITHUB_ENV" + PKG_CONFIG_PATH="$sdk/lib/pkgconfig" "$wrapper" --atleast-version=1.28 gstreamer-audio-1.0 diff --git a/.github/actions/prepare-bazel-ci/action.yml b/.github/actions/prepare-bazel-ci/action.yml index 50f8618918ae..b06d8e84d8cb 100644 --- a/.github/actions/prepare-bazel-ci/action.yml +++ b/.github/actions/prepare-bazel-ci/action.yml @@ -7,10 +7,6 @@ inputs: cache-scope: description: Logical namespace used to keep concurrent Bazel jobs from reserving the same repository cache key. required: true - action-cache: - description: Enable the local Bazel disk action cache (disable for large cold CI test graphs to avoid exhausting runner disk). - required: false - default: "true" outputs: repository-cache-path: description: Filesystem path used for the Bazel repository cache. @@ -25,23 +21,6 @@ outputs: runs: using: composite steps: - # GitHub-hosted Linux runners have limited free disk space. A full - # cold Bazel graph exhausted the filesystem and prevented cache saves. - # These preinstalled SDKs are unused by the Rust/Bazel CI matrix. - - name: Reclaim unused runner disk space (Linux) - if: runner.os == 'Linux' - shell: bash - run: | - set -euo pipefail - for unused_path in /usr/local/lib/android /opt/ghc /opt/hostedtoolcache/CodeQL; do - if [[ -d "$unused_path" ]]; then - echo "Removing unused hosted-runner SDK: $unused_path" - sudo rm -rf -- "$unused_path" - fi - done - sudo apt-get clean - df -h "$GITHUB_WORKSPACE" - - id: setup_ci uses: ./.github/actions/setup-ci @@ -54,6 +33,25 @@ runs: # setup-bazel writes an explicit output_base, which otherwise overrides # BAZEL_OUTPUT_USER_ROOT and leaves Bazel's I/O-heavy trees on C:. output-base: ${{ steps.setup_ci.outputs.bazel-output-base }} + # setup-bazel overwrites ~/.bazelrc, including setup-ci's resource caps. + bazelrc: ${{ runner.os == 'Linux' && format('import {0}/codefx-linux.bazelrc', runner.temp) || '' }} + + - name: Verify effective Linux Bazel resource policy + if: runner.os == 'Linux' + shell: bash + run: python3 .github/scripts/verify_bazel_resources.py + + - name: Sample Bazel runner resources + if: runner.os == 'Linux' + shell: bash + run: | + mkdir -p "$RUNNER_TEMP/bazel-execution-logs" + pid_file="$RUNNER_TEMP/bazel-resource-sampler.pid" + if [[ ! -f "$pid_file" ]] || ! kill -0 "$(cat "$pid_file")" 2>/dev/null; then + nohup python3 .github/scripts/bazel_resource_usage.py watch \ + > "$RUNNER_TEMP/bazel-execution-logs/resource-sampler.log" 2>&1 < /dev/null & + echo "$!" > "$pid_file" + fi - name: Configure Bazel repository cache id: configure_bazel_repository_cache @@ -134,20 +132,6 @@ runs: echo "repository-cache-key=bazel-cache-${CACHE_SCOPE}-${TARGET}-${CACHE_HASH}" >> "${GITHUB_OUTPUT}" echo "repository-cache-restore-key=bazel-cache-${CACHE_SCOPE}-${TARGET}-" >> "${GITHUB_OUTPUT}" - # The repository cache only avoids downloading external archives. Keep the - # Bazel action cache separate and share it by target so test, clippy, and - # release verification jobs reuse compiled actions without sharing - # incompatible platform outputs. The action cache is content addressed by - # Bazel, so source changes safely invalidate individual entries. - - name: Cache Bazel action outputs - if: inputs.action-cache == 'true' - uses: actions/cache@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5.0.4 - with: - path: ~/.cache/bazel-disk-cache - key: bazel-action-${{ inputs.cache-scope }}-${{ inputs.target }}-${{ hashFiles('.bazelrc', 'MODULE.bazel', 'MODULE.bazel.lock', 'codex-rs/Cargo.lock', 'codex-rs/Cargo.toml') }} - restore-keys: | - bazel-action-${{ inputs.cache-scope }}-${{ inputs.target }}- - # Restore the Bazel repository cache explicitly so external dependencies # do not need to be re-downloaded on every CI run. Keep restore failures # non-fatal so transient cache-service errors degrade to a cold build diff --git a/.github/actions/run-argument-comment-lint/action.yml b/.github/actions/run-argument-comment-lint/action.yml index d145249d5e43..16cdd54eb47e 100644 --- a/.github/actions/run-argument-comment-lint/action.yml +++ b/.github/actions/run-argument-comment-lint/action.yml @@ -57,7 +57,6 @@ runs: shell: bash run: | ./.github/scripts/run-argument-comment-lint-bazel.sh \ - --repo_env=BAZEL_MSVC_RUNTIME_VISUAL_STUDIO_EULA=1 \ --config=argument-comment-lint \ --platforms=//:local_windows \ --keep_going \ diff --git a/.github/actions/setup-ci/action.yml b/.github/actions/setup-ci/action.yml index 6e145eb763bc..11004305dd69 100644 --- a/.github/actions/setup-ci/action.yml +++ b/.github/actions/setup-ci/action.yml @@ -11,6 +11,10 @@ outputs: runs: using: composite steps: + - name: Adapt Codefx hosted Linux resources + if: runner.os == 'Linux' + uses: ./.github/actions/codefx-linux-runner + # setup-ci expects either this step or the Unix fallback below to define # CI_BUILD_ROOT. Windows uses a Dev Drive because Cargo and Bazel # spend significant time reading and writing build/cache trees. @@ -67,6 +71,7 @@ runs: echo "BAZEL_OUTPUT_USER_ROOT=$bazel_output_user_root" echo "BAZEL_REPOSITORY_CACHE=$bazel_repository_cache" echo "BAZEL_REPO_CONTENTS_CACHE=$bazel_repo_contents_cache" + echo "ZIG_LOCAL_CACHE_DIR=$CI_BUILD_ROOT/zig-local" echo "CARGO_TARGET_DIR=$cargo_target_dir" echo "TEMP=$tmp" echo "TMP=$tmp" @@ -81,7 +86,7 @@ runs: run: mkdir -p "$RUNNER_TEMP/dotslash-curl" && echo retry-all-errors > "$RUNNER_TEMP/dotslash-curl/.curlrc" - name: Install DotSlash - uses: meta/install-dotslash@1e4e7b3e07eaca387acb98f1d4720e0bee8dbb6a # v2 + uses: facebook/install-dotslash@1e4e7b3e07eaca387acb98f1d4720e0bee8dbb6a # v2 env: CURL_HOME: ${{ runner.temp }}/dotslash-curl diff --git a/.github/actions/setup-rusty-v8/action.yml b/.github/actions/setup-rusty-v8/action.yml index 5779fca149cf..b37736a08f94 100644 --- a/.github/actions/setup-rusty-v8/action.yml +++ b/.github/actions/setup-rusty-v8/action.yml @@ -62,3 +62,9 @@ runs: (cd "${binding_dir}" && tr -d '\r' < "${checksums_path}" | "${checksum_command[@]}") echo "RUSTY_V8_ARCHIVE=${archive_path}" >> "${GITHUB_ENV}" echo "RUSTY_V8_SRC_BINDING_PATH=${binding_path}" >> "${GITHUB_ENV}" + + - name: Generate Linux bindings matching the verified native archive + if: runner.os == 'Linux' + uses: ./.github/actions/codefx-linux-v8-binding + with: + target: ${{ inputs.target }} diff --git a/.github/scripts/bazel_resource_usage.py b/.github/scripts/bazel_resource_usage.py new file mode 100644 index 000000000000..454cb6442244 --- /dev/null +++ b/.github/scripts/bazel_resource_usage.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +"""Record resource headroom during CI, including failures before cache upload.""" + +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import time + + +def sample() -> dict: + usage = shutil.disk_usage(os.environ["GITHUB_WORKSPACE"]) + return { + "time": time.time(), + "disk_total": usage.total, + "disk_free": usage.free, + } + + +def report(path: Path) -> None: + samples = [sample()] + if path.exists(): + for line in path.read_text().splitlines(): + try: + samples.append(json.loads(line)) + except json.JSONDecodeError: + # A cancelled writer can leave an incomplete final sample. + continue + minimum = min(item["disk_free"] for item in samples) / 1024**3 + message = ( + f"Bazel runner minimum free disk: {minimum:.2f} GiB ({len(samples)} samples)" + ) + print(message) + with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as stream: + stream.write(f"\n{message}\n") + subprocess.run(["df", "-h", os.environ["GITHUB_WORKSPACE"]], check=True) + subprocess.run(["free", "-h"], check=True) + for directory in ( + os.environ["CI_BUILD_ROOT"], + str(Path.home() / ".cache/bazel-disk-cache"), + ): + if Path(directory).exists(): + subprocess.run(["du", "-h", "--max-depth=1", directory], check=False) + + +def main() -> None: + directory = Path(os.environ["RUNNER_TEMP"]) / "bazel-execution-logs" + directory.mkdir(exist_ok=True) + path = directory / "resources.jsonl" + if sys.argv[1:] == ["watch"]: + with path.open("a", buffering=1) as stream: + while True: + stream.write(json.dumps(sample()) + "\n") + time.sleep(15) + elif sys.argv[1:] == ["report"]: + report(path) + else: + raise SystemExit("Expected watch or report") + + +if __name__ == "__main__": + main() diff --git a/.github/scripts/bound_bazel_action_cache.py b/.github/scripts/bound_bazel_action_cache.py new file mode 100644 index 000000000000..bc1f8c97ecf3 --- /dev/null +++ b/.github/scripts/bound_bazel_action_cache.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +"""Bound disposable Bazel CAS snapshots before uploading them to Actions cache.""" + +import argparse +import os +from pathlib import Path + + +def bound_cache(root: Path, max_bytes: int) -> tuple[int, int]: + if not root.exists(): + return 0, 0 + entries = [] + for directory, _, filenames in os.walk(root): + for filename in filenames: + path = Path(directory) / filename + if path.is_symlink(): + continue + try: + stat = path.stat() + except FileNotFoundError: + continue + entries.append( + (max(stat.st_atime_ns, stat.st_mtime_ns), str(path), stat.st_size) + ) + total = sum(size for _, _, size in entries) + removed = 0 + for _, name, size in sorted(entries): + if total <= max_bytes: + break + try: + Path(name).unlink() + except FileNotFoundError: + continue + removed += 1 + total -= size + return removed, total + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("path", type=Path) + parser.add_argument("--max-gib", type=int, default=2) + args = parser.parse_args() + if args.max_gib < 1: + parser.error("--max-gib must be positive") + removed, retained = bound_cache(args.path, args.max_gib * 1024**3) + print( + f"Bazel cache: removed {removed} files; retained {retained / (1024**3):.2f} GiB" + ) diff --git a/.github/scripts/check_ci_results.py b/.github/scripts/check_ci_results.py index 36d1eed3b4ee..f15602a30b3b 100644 --- a/.github/scripts/check_ci_results.py +++ b/.github/scripts/check_ci_results.py @@ -15,6 +15,8 @@ def main() -> None: # Keep result policy in one script so blocking-ci and postmerge-ci cannot # drift in how they interpret dependency conclusions. needs = json.loads(os.environ["NEEDS"]) + if not isinstance(needs, dict) or not needs: + raise SystemExit("CI aggregate has no dependencies") failures = sorted( (name, dependency["result"]) for name, dependency in needs.items() diff --git a/.github/scripts/check_upstream_ci.py b/.github/scripts/check_upstream_ci.py new file mode 100644 index 000000000000..ad9322b47980 --- /dev/null +++ b/.github/scripts/check_upstream_ci.py @@ -0,0 +1,553 @@ +#!/usr/bin/env python3 +"""Compare retained Linux CI with the exact official source version. + +Only the versioned platform, runner and coverage-preserving adaptations below are permitted. +Test commands, selectors, actions and their conditions must otherwise match. +This program checks files; it never regenerates or repairs them. +""" + +import argparse +import difflib +import json +from pathlib import Path +import re +import subprocess +import tomllib + +ROOT = Path(__file__).resolve().parents[2] +REMOVED_RESULTS = ( + "tests_macos_aarch64", + "tests_windows_x64", + "tests_windows_arm64", + "tests_linux_arm64", +) +PLATFORM_WORKFLOWS = {"bazel.yml", "rust-ci.yml", "rust-ci-full.yml", "v8-canary.yml"} +RUNNER_ADAPTER = """ - name: Adapt Codefx hosted Linux resources + if: runner.os == 'Linux' + uses: ./.github/actions/codefx-linux-runner + +""" +BAZEL_RESOURCE_PREPARATION = """ bazelrc: ${{ runner.os == 'Linux' && format('import {0}/codefx-linux.bazelrc', runner.temp) || '' }} + + - name: Verify effective Linux Bazel resource policy + if: runner.os == 'Linux' + shell: bash + run: python3 .github/scripts/verify_bazel_resources.py + + - name: Sample Bazel runner resources + if: runner.os == 'Linux' + shell: bash + run: | + mkdir -p "$RUNNER_TEMP/bazel-execution-logs" + pid_file="$RUNNER_TEMP/bazel-resource-sampler.pid" + if [[ ! -f "$pid_file" ]] || ! kill -0 "$(cat "$pid_file")" 2>/dev/null; then + nohup python3 .github/scripts/bazel_resource_usage.py watch \\ + > "$RUNNER_TEMP/bazel-execution-logs/resource-sampler.log" 2>&1 < /dev/null & + echo "$!" > "$pid_file" + fi +""" +BAZEL_RESOURCE_REPORT = """ - name: Report Bazel runner resources + if: always() && runner.os == 'Linux' + run: python3 .github/scripts/bazel_resource_usage.py report + +""" +VOICE_SDK_STEP = """ - name: Prepare pinned GNU voice SDK + if: runner.os == 'Linux' && endsWith(matrix.target, '-linux-gnu') + uses: ./.github/actions/codefx-linux-voice-sdk +""" +V8_ARCHIVE_STEP = """ - name: Configure rusty_v8 artifact overrides and verify checksums + if: runner.os == 'Linux' + uses: ./.github/actions/setup-rusty-v8 + with: + target: ${{ inputs.target }} +""" +LINUX_RUNTIME_PREPARATION_STEP = """ - name: Prepare Linux runtime payload and compatibility inputs + if: runner.os == 'Linux' + env: + GH_TOKEN: ${{ github.token }} + shell: bash + run: | + set -euo pipefail + releases="$(python3 ../.github/scripts/resolve_exec_server_releases.py)" + echo "CODEX_COMPAT_RELEASES=$releases" >> "$GITHUB_ENV" + cargo build --locked --target "$CODEX_CI_TARGET" --profile "$CODEX_CI_PROFILE" --bin bwrap + runtime="$CARGO_TARGET_DIR/$CODEX_CI_TARGET/$CODEX_CI_PROFILE" + digest="$(sha256sum "$runtime/bwrap" | cut -d ' ' -f 1)" + echo "CODEX_BWRAP_SHA256=$digest" >> "$GITHUB_ENV" + install -Dm755 "$runtime/bwrap" "$runtime/codex-resources/bwrap" + +""" +LINUX_COMPATIBILITY_STEP = """ - name: Resolve Linux compatibility test inputs + if: runner.os == 'Linux' + env: + GH_TOKEN: ${{ github.token }} + shell: bash + run: | + releases="$(python3 ../.github/scripts/resolve_exec_server_releases.py)" + echo "CODEX_COMPAT_RELEASES=$releases" >> "$GITHUB_ENV" + +""" +LINUX_RUNTIME_EXPORT = """ cp "${CARGO_TARGET_DIR}/${CODEX_CI_TARGET}/${CODEX_CI_PROFILE}/bwrap" "${helper_dir}/" + printf '%s bwrap\\n' "$CODEX_BWRAP_SHA256" > "${helper_dir}/bwrap.sha256" +""" +LINUX_RUNTIME_RESTORE = """ (cd "$helper_dir" && sha256sum --check bwrap.sha256) + install -Dm755 "$helper_dir/bwrap" "$helper_target_dir/bwrap" + install -Dm755 "$helper_dir/bwrap" "$helper_target_dir/codex-resources/bwrap" +""" +LINUX_RUNTIME_ENV = ' "CARGO_BIN_EXE_bwrap=${helper_target_dir}/bwrap"\n' + +SDK_PACKAGE_STEPS = ' - name: Download the same-run current source package\n uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1\n with:\n name: codefx-source-x86_64-unknown-linux-musl\n path: ${{ runner.temp }}/sdk-package\n\n - name: Verify candidate provenance and stage SDK executables\n run: python3 scripts/install/prepare_sdk_package.py --directory "$RUNNER_TEMP/sdk-package" --output "$RUNNER_TEMP/sdk-runtime"\n\n - name: Warm up the current source CLI\n run: \'"${CODEX_EXEC_PATH}" --version\'\n\n' + + +def supported_linux_matrix_entry(match: re.Match[str]) -> str: + entry = match.group() + targets = re.findall(r"(?m)^ target: (.+)$", entry) + if targets: + return ( + entry + if all( + target in ("x86_64-unknown-linux-gnu", "x86_64-unknown-linux-musl") + for target in targets + ) + else "" + ) + return ( + entry + if re.search( + r"(?m)^ - (?:os|runner): ubuntu[^\n]*$|^ runner: ubuntu[^\n]*$", + entry, + ) + and not re.search(r"ubuntu[^\n]*-arm", entry) + else "" + ) + + +def linux_projection(path: str, text: str) -> str: + """Apply the documented, bounded differences to official file contents.""" + name = Path(path).name + if name in PLATFORM_WORKFLOWS: + text = re.sub( + r"(?ms)^ (?:test-windows[^:]*|tests_windows[^:]*|tests_macos[^:]*|tests_linux_arm64|build-windows[^:]*):\n" + r".*?(?=^ [a-zA-Z_][\w-]*:|\Z)", + "", + text, + ) + text = re.sub( + r"(?ms)^ - (?:os|name|runner):.*?" + r"(?=^ - (?:os|name|runner):|^ \S|\Z)", + supported_linux_matrix_entry, + text, + ) + for result in REMOVED_RESULTS: + text = re.sub(rf"(?m)^.*{result}.*\n", "", text) + text = re.sub( + r"(?m)^ runs_on:\n group:.*\n labels:.*\n", + "", + text, + ) + text = re.sub(r"(?m)^ runner_(?:group|labels):.*\n", "", text) + text = text.replace("timeout-minutes: 30", "timeout-minutes: 180") + text = text.replace("timeout_minutes: 30", "timeout_minutes: 180") + text = text.replace( + "runs-on: ${{ matrix.runs_on || matrix.runner }}", + "runs-on: ${{ matrix.runner }}", + ) + if name == "rust-ci.yml": + text = text.replace("timeout_minutes: 180", "timeout_minutes: 360") + if name == "rust-ci-full.yml": + text = re.sub( + r"(?ms)(^ argument_comment_lint_prebuilt:\n.*?^ timeout-minutes:) 180", + r"\1 360", + text, + count=1, + ) + if name == "v8-canary.yml": + # Normal builds use the sandbox archive. Canary variants must choose + # their own feature explicitly so the release variant stays unsandboxed. + text = text.replace( + 'cargo_args=(test -p codex-v8-poc --target "${TARGET}")', + 'cargo_args=(test -p codex-v8-poc --no-default-features --target "${TARGET}")', + ) + if name == "bazel.yml": + text = text.replace( + " --test_tag_filters=-argument-comment-lint\n", + " --test_tag_filters=-argument-comment-lint\n" + " --notest_keep_going\n", + ) + text = text.replace( + " ./.github/scripts/run-bazel-ci.sh \\\n", + ' if [[ -z "${BUILDBUDDY_API_KEY:-}" ]]; then\n' + " # A local_test_jobs cap does not stop native compilation from\n" + " # starving tests with short protocol deadlines. Exclusive tests\n" + " # run after the build graph, retaining every selected test.\n" + " bazel_test_args+=(--test_strategy=exclusive)\n" + " fi\n" + " ./.github/scripts/run-bazel-ci.sh \\\n", + 1, + ) + text = text.replace( + "runs-on: ${{ matrix.runs_on || matrix.os }}", + "runs-on: ${{ matrix.os }}", + ) + # Full source V8 builds are local when BuildBuddy is unavailable. + text = text.replace("timeout-minutes: 180", "timeout-minutes: 360") + text = text.replace( + " - name: Upload Bazel execution logs\n", + BAZEL_RESOURCE_REPORT + " - name: Upload Bazel execution logs\n", + ) + # This matrix value only named caches; both entries executed native GNU. + text = text.replace( + " - os: ubuntu-24.04\n target: x86_64-unknown-linux-musl\n", + "", + ) + text = text.replace( + "name: Bazel test on ${{ matrix.os }} for ${{ matrix.target }}", + "name: Bazel native GNU tests on ${{ matrix.os }}", + ) + if name == "postmerge-ci.yml": + # Validate the caller as well as its children before merging. The V8 + # child requests actions:read, which cannot exceed caller permissions. + text = text.replace("on:\n", "on:\n workflow_dispatch:\n", 1) + text = text.replace( + " v8-canary:\n name: v8-canary\n", + " v8-canary:\n name: v8-canary\n" + " permissions:\n contents: read\n actions: read\n", + ) + if name == "rust-ci-full.yml": + text = text.replace( + "name: Tests — ubuntu-24.04 - x86_64-unknown-linux-gnu (remote)", + "name: Tests — ubuntu-24.04 - x86_64-unknown-linux-gnu (local)", + ) + text = text.replace(" remote_env: true\n", " remote_env: false\n") + text = text.replace( + " USE_SCCACHE: ${{ (startsWith(matrix.runner, 'windows') || (matrix.runner == 'macos-15-xlarge' && matrix.target == 'x86_64-apple-darwin')) && 'false' || 'true' }}", + ' USE_SCCACHE: "true"', + ) + text = text.replace( + "matrix.target == 'x86_64-unknown-linux-musl' || matrix.target == 'aarch64-unknown-linux-musl'", + "matrix.target == 'x86_64-unknown-linux-musl'", + ) + if name == "sdk.yml": + text = re.sub( + r" runs-on:\n group:.*\n labels:.*\n", + " runs-on: ubuntu-24.04\n", + text, + ) + # SDK tests consume a verified same-run package; no second CLI/V8 build. + start = text.index(" - name: Prepare Bazel CI") + end = text.index(" - name: Install dependencies", start) + text = text[:start] + SDK_PACKAGE_STEPS + text[end:] + start = text.index(" - name: Save bazel repository cache") + end = text.index(" - name: Check for a clean worktree", start) + text = text[:start] + text[end:] + text = text.replace( + " environment:\n name: bazel\n deployment: false\n", "" + ) + text = text.replace( + "pnpm -r --filter ./sdk/typescript run test", + "pnpm -r --filter ./sdk/typescript run test --runInBand", + ) + if name == "rust-ci-full.yml": + prefix, marker, suffix = text.partition(" lint_build:\n") + suffix = suffix.replace( + " - uses: ./.github/actions/setup-ci\n", + " - uses: ./.github/actions/setup-ci\n" + VOICE_SDK_STEP, + 1, + ) + text = prefix + marker + suffix + if name == "rust-ci-full-nextest-platform.yml": + text = text.replace( + " - uses: ./.github/actions/setup-ci\n", + " - uses: ./.github/actions/setup-ci\n" + + VOICE_SDK_STEP.replace("matrix.target", "inputs.target"), + ) + text = text.replace( + " - name: Compute lockfile hash\n", + V8_ARCHIVE_STEP + " - name: Compute lockfile hash\n", + 1, + ) + text = text.replace( + " - name: Build nextest archive\n", + LINUX_RUNTIME_PREPARATION_STEP + " - name: Build nextest archive\n", + 1, + ) + helper_copy = ' cp "${CARGO_TARGET_DIR}/${CODEX_CI_TARGET}/${CODEX_CI_PROFILE}/codex-linux-sandbox" "${helper_dir}/"\n' + text = text.replace(helper_copy, helper_copy + LINUX_RUNTIME_EXPORT) + text = text.replace( + " - name: tests\n", LINUX_COMPATIBILITY_STEP + " - name: tests\n" + ) + helper_chmod = ( + ' chmod +x "${helper_target_dir}/codex-linux-sandbox"\n' + ) + text = text.replace(helper_chmod, helper_chmod + LINUX_RUNTIME_RESTORE) + text = text.replace( + ' "CARGO_BIN_EXE_codex_linux_sandbox=${sandbox_helper}"\n', + ' "CARGO_BIN_EXE_codex_linux_sandbox=${sandbox_helper}"\n' + + LINUX_RUNTIME_ENV, + ) + if name == "rust-ci-full-nextest-platform.yml": + text = text.replace( + " SCCACHE_CACHE_SIZE: 10G", + ' SCCACHE_CACHE_SIZE: 2G\n CARGO_PROFILE_CI_TEST_DEBUG: "0"\n CARGO_PROFILE_CI_TEST_INCREMENTAL: "false"', + ) + text = text.replace( + "tool: sccache\n version: 0.7.5", "tool: sccache@0.12.0" + ) + text = text.replace( + "tool: nextest\n version: 0.9.103", "tool: cargo-nextest@0.9.103" + ) + text = text.replace(" ~/.cargo/bin/\n", "") + text = text.replace( + "cargo-home-${{ env.ARCHIVE_CACHE_RUNNER }}-${{ inputs.target }}-${{ inputs.profile }}-", + "cargo-sources-v2-${{ runner.os }}-", + ) + if name == "cargo-deny.yml": + text = text.replace( + " with:\n rust-version:", + " env:\n" + " CARGO_HOME: /github/home/cargo-home\n" + ' CARGO_NET_GIT_FETCH_WITH_CLI: "true"\n' + " with:\n rust-version:", + ) + if name == "blob-size-policy.yml": + # Manual validation has no push.before SHA. Inspect the branch's full + # divergence from the default branch instead of passing an empty base. + text = text.replace( + " id: range\n", + " id: range\n" + " env:\n" + " DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}\n", + ) + text = text.replace( + " else\n base='${{ github.event.before }}'", + ' elif [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then\n' + " head='${{ github.sha }}'\n" + ' base="$(git merge-base "origin/$DEFAULT_BRANCH" "$head")"\n' + " else\n base='${{ github.event.before }}'", + ) + text = text.replace( + " - uses: openai/fence@e017427978b91977d79a3023842166ab79b5b816 # pin@v0.12.2\n" + " with:\n mode: audit\n", + "", + ) + if path == ".github/actions/setup-ci/action.yml": + text = text.replace("meta/install-dotslash@", "facebook/install-dotslash@") + text = text.replace(" steps:\n", " steps:\n" + RUNNER_ADAPTER, 1) + text = text.replace( + ' echo "CARGO_TARGET_DIR=$cargo_target_dir"', + ' echo "ZIG_LOCAL_CACHE_DIR=$CI_BUILD_ROOT/zig-local"\n echo "CARGO_TARGET_DIR=$cargo_target_dir"', + ) + if path == ".github/actions/prepare-bazel-ci/action.yml": + output_base = ( + " output-base: ${{ steps.setup_ci.outputs.bazel-output-base }}\n" + ) + text = text.replace(output_base, output_base + BAZEL_RESOURCE_PREPARATION) + if path == ".github/actions/setup-rusty-v8/action.yml": + text += """ + - name: Generate Linux bindings matching the verified native archive + if: runner.os == 'Linux' + uses: ./.github/actions/codefx-linux-v8-binding + with: + target: ${{ inputs.target }} +""" + return text + + +def comparable(text: str) -> str: + # Comments and blank lines may explain the platform projection locally. + return "\n".join( + line.rstrip() + for line in text.splitlines() + if line.strip() and not line.lstrip().startswith("#") + ) + + +def job_blocks(text: str) -> dict[str, str]: + body = text.partition("\njobs:\n")[2] + return { + match[1]: match[0] + for match in re.finditer(r"(?ms)^ ([\w-]+):\n.*?(?=^ [\w-]+:|\Z)", body) + } + + +def gate_errors(blocking: str) -> list[str]: + jobs = job_blocks(blocking) + calls = { + "bazel": "bazel.yml", + "linux-cargo": "codefx-linux-cargo.yml", + "blob-size-policy": "blob-size-policy.yml", + "cargo-deny": "cargo-deny.yml", + "codespell": "codespell.yml", + "repo-checks": "repo-checks.yml", + "rust-ci": "rust-ci.yml", + "sdk": "sdk.yml", + "codefx-install": "codefx-install.yml", + "codefx-source-smoke": "codefx-source-smoke.yml", + } + errors = [] + for job, workflow in calls.items(): + block = jobs.get(job, "") + if f" uses: ./.github/workflows/{workflow}\n" not in block: + errors.append(f"Missing required workflow call: {job}") + if re.search(r"(?m)^ (?:if|continue-on-error):", block): + errors.append(f"Required workflow must run and propagate failure: {job}") + required = jobs.get("required", "") + needs = set(re.findall(r"(?m)^ - ([\w-]+)$", required)) + if needs != set(calls) | {"ci-policy"}: + errors.append("CI required must depend on all official Linux and Codefx checks") + if " if: ${{ always() }}" not in required: + errors.append("CI required must report failures even when dependencies fail") + if "run: python3 .github/scripts/check_ci_results.py" not in required: + errors.append("CI required must reject skipped/cancelled dependencies") + if "run: python3 .github/scripts/check_upstream_ci.py --upstream" not in jobs.get( + "ci-policy", "" + ): + errors.append("The official baseline comparison must execute") + if " needs: [ci-policy, codefx-source-smoke]" not in jobs.get("sdk", ""): + errors.append("SDK must consume successful same-candidate source packages") + return errors + + +def coverage_errors(root: Path) -> list[str]: + contracts = { + ".github/workflows/codefx-linux-cargo.yml": ( + "task: [clippy, core, tui, app-server, other-0, other-1, other-2]", + 'cargo clippy --locked --workspace --all-targets --target "$TARGET" -- -D warnings', + 'select_cargo_ci_packages.py --shard "$SHARD"', + 'cargo nextest run --locked --target "$TARGET" --cargo-profile ci-test --no-fail-fast --test-threads 2 "${packages[@]}"', + 'cargo build --locked --profile ci-test --target "$TARGET" --workspace --bins', + "uses: ./.github/actions/setup-rusty-v8", + "uses: ./.github/actions/codefx-linux-voice-sdk", + ), + ".github/workflows/codefx-extended-ci.yml": ( + "uses: ./.github/workflows/bazel.yml", + "workflow_dispatch:", + "branches: [main]", + ), + ".github/workflows/postmerge-ci.yml": ( + "workflow_dispatch:", + "uses: ./.github/workflows/rust-ci-full.yml", + "uses: ./.github/workflows/v8-canary.yml", + "actions: read", + "run: python3 .github/scripts/check_ci_results.py", + ), + ".github/workflows/rust-ci-full.yml": ( + "uses: ./.github/actions/run-argument-comment-lint", + "uses: ./.github/workflows/rust-ci-full-nextest-platform.yml", + ), + ".github/workflows/sdk.yml": ( + "name: codefx-source-x86_64-unknown-linux-musl", + "run: python3 scripts/install/prepare_sdk_package.py", + "uv run --only-group dev --frozen --no-sync pytest", + "pnpm -r --filter ./sdk/typescript run test --runInBand", + ), + ".github/workflows/codefx-source-smoke.yml": ( + "target: x86_64-unknown-linux-musl", + 'readelf -h "$binary"', + "run: python3 scripts/install/smoke_source_package.py", + ), + } + errors = [] + for path, commands in contracts.items(): + text = (root / path).read_text() + for command in commands: + if command not in text: + errors.append(f"Missing coverage contract in {path}: {command}") + if re.search(r"(?m)^\s*if: false|^ continue-on-error: true", text): + errors.append(f"Coverage cannot ignore failure or be disabled: {path}") + for name in ( + "bazel.yml", + "rust-ci.yml", + "rust-ci-full.yml", + "v8-canary.yml", + "codefx-source-smoke.yml", + "codefx-platform-release.yml", + "codefx-native-smoke.yml", + "codefx-publish-verified.yml", + ): + text = comparable((root / ".github/workflows" / name).read_text()) + if re.search( + r"\b(?:target|targets):[^\n]*(?:aarch64|arm64|apple-darwin|windows)|\b(?:runner|runs-on|os):[^\n]*(?:-arm|macos|windows)", + text, + ): + errors.append(f"Only Linux amd64 targets and runners are supported: {name}") + return errors + + +def baseline_errors(root: Path, upstream: Path, files: list[str]) -> list[str]: + errors = [] + for path in files: + expected = comparable(linux_projection(path, (upstream / path).read_text())) + actual = comparable((root / path).read_text()) + if actual != expected: + errors.append( + f"Official Linux CI drift: {path}\n" + + "\n".join( + difflib.unified_diff( + expected.splitlines(), + actual.splitlines(), + fromfile="official Linux baseline", + tofile=path, + n=2, + ) + ) + ) + return errors + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--upstream", type=Path, required=True) + args = parser.parse_args() + manifest = json.loads((ROOT / ".github/upstream-ci.json").read_text()) + upstream_sha = subprocess.check_output( + ["git", "-C", str(args.upstream), "rev-parse", "HEAD"], text=True + ).strip() + if upstream_sha != manifest["commit"]: + raise SystemExit("Official checkout does not match upstream-ci.json") + version = tomllib.loads((ROOT / "codex-rs/Cargo.toml").read_text())["workspace"][ + "package" + ]["version"] + if manifest["tag"] != f"rust-v{version}": + raise SystemExit( + "Update the official CI baseline together with the source version" + ) + errors = baseline_errors(ROOT, args.upstream, manifest["files"]) + blocking = (ROOT / ".github/workflows/blocking-ci.yml").read_text() + errors.extend(gate_errors(blocking)) + errors.extend(coverage_errors(ROOT)) + source_smoke = (ROOT / ".github/workflows/codefx-source-smoke.yml").read_text() + if re.search(r"(?m)^\s+(?:ref|tag):", source_smoke): + errors.append("Current source smoke must not check out an older ref or tag") + for path in (ROOT / ".github/workflows").glob("*.yml"): + content = path.read_text() + if re.search( + r"(?m)^\s*(?:-\s*)?(?:os|runner|runs-on):\s*(?:windows|macos)", + content, + ): + errors.append(f"Unsupported platform runner: {path.name}") + for called in re.findall( + r"(?m)^\s*uses: \./\.github/workflows/([\w.-]+\.yml)\s*$", content + ): + if not (path.parent / called).is_file(): + errors.append(f"Missing reusable workflow: {called}") + for obsolete in ( + "rust-release.yml", + "rust-release-windows.yml", + "rust-release-provisioned-macos.yml", + "rusty-v8-release.yml", + "rust-release-argument-comment-lint.yml", + ): + if (ROOT / ".github/workflows" / obsolete).exists(): + errors.append(f"Unsupported upstream publisher restored: {obsolete}") + if errors: + raise SystemExit("\n".join(errors)) + print(f"Official Linux CI matches {manifest['tag']} ({manifest['commit']})") + print( + "Official Linux Bazel, workspace argument lint, Cargo, SDK and Codefx " + "coverage is required." + ) + + +if __name__ == "__main__": + main() diff --git a/.github/scripts/ci_storage_cleanup.py b/.github/scripts/ci_storage_cleanup.py new file mode 100644 index 000000000000..f399e83369c1 --- /dev/null +++ b/.github/scripts/ci_storage_cleanup.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 +"""Bound disposable Actions storage without touching published releases.""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import subprocess +from datetime import datetime, timezone + +REPO = "hitmux/codefx" +LOG_PREFIXES = ("bazel-execution-logs-", "cargo-timings-", "v8-canary-") +LEGACY_CACHE = re.compile( + r"(windows|macos|codefx-bazel-actions-v1-|bazel-action-|bazel-cache-|codefx-native-.*-v1-)", + re.IGNORECASE, +) + + +def api_pages(endpoint: str): + raw = subprocess.check_output( + ["gh", "api", "--paginate", f"repos/{REPO}/{endpoint}?per_page=100"], + text=True, + ) + decoder = json.JSONDecoder() + pos = 0 + while pos < len(raw): + while pos < len(raw) and raw[pos].isspace(): + pos += 1 + if pos >= len(raw): + break + page, pos = decoder.raw_decode(raw, pos) + yield page + + +def age_days(value: str, now: datetime) -> float: + timestamp = datetime.fromisoformat(value.replace("Z", "+00:00")) + return (now - timestamp).total_seconds() / 86400 + + +def stale_cache(item: dict, now: datetime) -> bool: + key = item.get("key", "") + access = item.get("last_accessed_at") or item.get("created_at") + if not access: + return False + minimum_days = 4 if LEGACY_CACHE.search(key) else 14 + return age_days(access, now) >= minimum_days + + +def stale_artifact(item: dict, now: datetime) -> bool: + name = item.get("name", "") + created = item.get("created_at") + return bool( + created and name.startswith(LOG_PREFIXES) and age_days(created, now) >= 10 + ) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--apply", action="store_true", help="delete eligible objects") + parser.add_argument("--max-delete", type=int, default=100) + args = parser.parse_args() + if not 1 <= args.max_delete <= 500: + parser.error("--max-delete must be 1..500") + if args.apply and ( + os.getenv("GITHUB_ACTIONS") != "true" + or os.getenv("GITHUB_REPOSITORY") != REPO + or os.getenv("GITHUB_EVENT_NAME") not in {"schedule", "workflow_dispatch"} + ): + parser.error( + "Destructive mode is only allowed in the scheduled/manual repository workflow" + ) + + now = datetime.now(timezone.utc) + candidates = [] + for page in api_pages("actions/caches"): + for obj in page.get("actions_caches", []): + if stale_cache(obj, now): + candidates.append(("cache", obj)) + for page in api_pages("actions/artifacts"): + for obj in page.get("artifacts", []): + if stale_artifact(obj, now): + candidates.append(("artifact", obj)) + + candidates.sort( + key=lambda item: ( + item[1].get("last_accessed_at") or item[1].get("created_at") or "" + ) + ) + eligible = candidates[: args.max_delete] + total_bytes = 0 + for kind, obj in eligible: + ident = obj["id"] + name = obj.get("name") or obj.get("key", "") + size = obj.get("size_in_bytes", 0) + total_bytes += size + print( + f"{'DELETE' if args.apply else 'DRY-RUN'} {kind}: " + f"{ident} {size / 1024**2:.1f} MiB {name}" + ) + if args.apply: + endpoint = "actions/caches" if kind == "cache" else "actions/artifacts" + subprocess.run( + ["gh", "api", "--method", "DELETE", f"repos/{REPO}/{endpoint}/{ident}"], + check=True, + ) + + message = ( + f"Actions storage cleanup: mode={'apply' if args.apply else 'dry-run'}, " + f"eligible={len(candidates)}, selected={len(eligible)}, " + f"bytes={total_bytes / 1024**3:.2f} GiB. " + "GitHub Release assets, provenance, and native transfer artifacts are excluded." + ) + print(message) + summary = os.getenv("GITHUB_STEP_SUMMARY") + if summary: + with open(summary, "a", encoding="utf-8") as stream: + stream.write(f"### Codefx CI storage maintenance\n\n{message}\n") + + +if __name__ == "__main__": + main() diff --git a/.github/scripts/download-verified.sh b/.github/scripts/download-verified.sh new file mode 100644 index 000000000000..fd882e6e4508 --- /dev/null +++ b/.github/scripts/download-verified.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# Transport failures may use a mirror; a checksum mismatch always fails closed. +set -euo pipefail + +destination="${1:?destination required}" +expected="${2:?SHA256 required}" +shift 2 +[[ "$expected" =~ ^[0-9a-f]{64}$ && $# -gt 0 ]] +mkdir -p "$(dirname "$destination")" +partial="${destination}.part.$$" +trap 'rm -f "$partial"' EXIT +for url in "$@"; do + if curl --fail --silent --show-error --location \ + --connect-timeout 15 --max-time 180 \ + --retry 3 --retry-delay 2 --retry-max-time 240 --retry-connrefused \ + "$url" --output "$partial"; then + printf '%s %s\n' "$expected" "$partial" | sha256sum --check - + mv "$partial" "$destination" + exit 0 + fi + rm -f "$partial" +done +echo 'All verified download sources failed' >&2 +exit 1 diff --git a/.github/scripts/install-musl-build-tools.sh b/.github/scripts/install-musl-build-tools.sh index a7d37b7ff907..1c49ad2a6cbc 100644 --- a/.github/scripts/install-musl-build-tools.sh +++ b/.github/scripts/install-musl-build-tools.sh @@ -63,8 +63,10 @@ if [[ ! -f "${libcap_prefix}/lib/libcap.a" ]]; then mkdir -p "${libcap_src_root}" "${libcap_prefix}/lib" "${libcap_prefix}/include/sys" "${libcap_prefix}/include/linux" "${libcap_pkgconfig_dir}" libcap_tarball="${libcap_root}/${libcap_tarball_name}" - curl -fsSL "${libcap_download_url}" -o "${libcap_tarball}" - echo "${libcap_sha256} ${libcap_tarball}" | sha256sum -c - + bash "$(dirname "${BASH_SOURCE[0]}")/download-verified.sh" \ + "${libcap_tarball}" "${libcap_sha256}" \ + "https://www.kernel.org/pub/linux/libs/security/linux-privs/libcap2/${libcap_tarball_name}" \ + "${libcap_download_url}" tar -xJf "${libcap_tarball}" -C "${libcap_src_root}" libcap_source_dir="${libcap_src_root}/libcap-${libcap_version}" diff --git a/.github/scripts/install-musl-openssl.sh b/.github/scripts/install-musl-openssl.sh index 15c50c51e472..29bf703652a8 100644 --- a/.github/scripts/install-musl-openssl.sh +++ b/.github/scripts/install-musl-openssl.sh @@ -21,8 +21,9 @@ openssl_prefix="${openssl_root}/prefix" if [[ ! -f "${openssl_prefix}/.complete" ]]; then mkdir -p "${openssl_root}" archive="${openssl_root}/openssl-${openssl_version}.tar.gz" - curl -fsSL "https://github.com/openssl/openssl/releases/download/openssl-${openssl_version}/openssl-${openssl_version}.tar.gz" -o "${archive}" - echo "${openssl_sha256} ${archive}" | sha256sum -c - + bash "$(dirname "${BASH_SOURCE[0]}")/download-verified.sh" \ + "${archive}" "${openssl_sha256}" \ + "https://github.com/openssl/openssl/releases/download/openssl-${openssl_version}/openssl-${openssl_version}.tar.gz" tar -xzf "${archive}" -C "${openssl_root}" ( diff --git a/.github/scripts/run-bazel-ci.sh b/.github/scripts/run-bazel-ci.sh index 539a284cf754..89f937a998b8 100755 --- a/.github/scripts/run-bazel-ci.sh +++ b/.github/scripts/run-bazel-ci.sh @@ -324,29 +324,6 @@ if [[ -n "${CODEX_BAZEL_EXECUTION_LOG_COMPACT_DIR:-}" ]]; then fi if [[ "${RUNNER_OS:-}" == "Windows" ]]; then - # The Windows GNU test graph uses an MSVC host toolchain for helper - # binaries. Pass the Visual Studio terms acceptance directly to Bazel's - # repository environment so the windows_support module extension receives - # it even when the local fallback omits the ci-windows config. - post_config_bazel_args+=("--repo_env=BAZEL_MSVC_RUNTIME_VISUAL_STUDIO_EULA=1") - - # third_party/voice/windows_native.bzl reads these values during analysis. - # Bazel's inherited `--action_env=NAME` form is intentionally rejected here; - # pass the runner's concrete values so remote and local Windows actions see - # the same fixed host environment. - system_root="${SystemRoot:-${SYSTEMROOT:-}}" - processor_architecture="${PROCESSOR_ARCHITECTURE:-}" - if [[ -z "$system_root" || -z "$processor_architecture" ]]; then - echo "SystemRoot and PROCESSOR_ARCHITECTURE must be set for Windows Bazel CI." >&2 - exit 1 - fi - post_config_bazel_args+=( - "--action_env=SystemRoot=${system_root}" - "--host_action_env=SystemRoot=${system_root}" - "--action_env=PROCESSOR_ARCHITECTURE=${processor_architecture}" - "--host_action_env=PROCESSOR_ARCHITECTURE=${processor_architecture}" - ) - pass_windows_build_env=1 if [[ $windows_cross_compile -eq 1 && -n "${BUILDBUDDY_API_KEY:-}" ]]; then # Remote build actions execute on Linux RBE workers. Passing the Windows diff --git a/.github/scripts/run-bazel-query-ci.sh b/.github/scripts/run-bazel-query-ci.sh index 20021ef9db4f..39fa04c47de0 100755 --- a/.github/scripts/run-bazel-query-ci.sh +++ b/.github/scripts/run-bazel-query-ci.sh @@ -26,13 +26,6 @@ run_bazel() { bazel_query_args=(query) -if [[ "${RUNNER_OS:-}" == "Windows" ]]; then - # Windows GNU lint/test target discovery still uses the MSVC host toolchain - # for helper binaries, so match the main CI Bazel invocation's explicit - # Visual Studio terms acceptance. - bazel_query_args+=(--repo_env=BAZEL_MSVC_RUNTIME_VISUAL_STUDIO_EULA=1) -fi - if [[ -n "${BAZEL_REPO_CONTENTS_CACHE:-}" ]]; then bazel_query_args+=("--repo_contents_cache=${BAZEL_REPO_CONTENTS_CACHE}") fi diff --git a/.github/scripts/select_cargo_ci_packages.py b/.github/scripts/select_cargo_ci_packages.py new file mode 100644 index 000000000000..cd5002dbe70f --- /dev/null +++ b/.github/scripts/select_cargo_ci_packages.py @@ -0,0 +1,46 @@ +"""Partition workspace packages before compilation, without dropping tests.""" + +import argparse +import hashlib +import json +import sys + +SHARDS = ("core", "tui", "app-server", "other-0", "other-1", "other-2") +DEDICATED = { + "codex-core": "core", + "codex-tui": "tui", + "codex-app-server": "app-server", +} + + +def partition(metadata): + members = set(metadata["workspace_members"]) + packages = [p for p in metadata["packages"] if p["id"] in members] + if {p["id"] for p in packages} != members: + raise ValueError("Cargo metadata omitted workspace members") + names = [p["name"] for p in packages] + if len(names) != len(set(names)): + raise ValueError("Ambiguous workspace package names") + result = {shard: [] for shard in SHARDS} + for name in sorted(names): + shard = DEDICATED.get(name) + if shard is None: + bucket = int.from_bytes(hashlib.sha256(name.encode()).digest()[:4]) % 3 + shard = f"other-{bucket}" + result[shard].append(name) + if any(not names for names in result.values()): + raise ValueError("Empty Cargo test shard") + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--shard", choices=SHARDS, required=True) + args = parser.parse_args() + groups = partition(json.load(sys.stdin)) + print("\n".join(groups[args.shard])) + print(json.dumps(groups, sort_keys=True), file=sys.stderr) + + +if __name__ == "__main__": + main() diff --git a/.github/scripts/test_codefx_ci.py b/.github/scripts/test_codefx_ci.py new file mode 100644 index 000000000000..05e01abdc756 --- /dev/null +++ b/.github/scripts/test_codefx_ci.py @@ -0,0 +1,126 @@ +"""Coverage and fault tests for the hosted-runner CI adaptations.""" + +import hashlib +import json +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + +from select_cargo_ci_packages import DEDICATED, partition + +ROOT = Path(__file__).resolve().parents[2] + + +class CargoPartition(unittest.TestCase): + def metadata(self): + names = list(DEDICATED) + [f"codex-fixture-{i}" for i in range(100)] + return { + "workspace_members": names, + "packages": [{"id": name, "name": name} for name in names] + + [{"id": "dependency", "name": "external-dependency"}], + } + + def test_every_workspace_package_is_tested_exactly_once(self): + metadata = self.metadata() + groups = partition(metadata) + assigned = [name for names in groups.values() for name in names] + self.assertCountEqual(assigned, metadata["workspace_members"]) + self.assertEqual(len(assigned), len(set(assigned))) + for name, shard in DEDICATED.items(): + self.assertEqual(groups[shard], [name]) + metadata["packages"].reverse() + self.assertEqual(groups, partition(metadata)) + + def test_incomplete_metadata_and_ambiguous_names_fail(self): + metadata = self.metadata() + metadata["workspace_members"].append("missing") + with self.assertRaises(ValueError): + partition(metadata) + metadata = self.metadata() + metadata["packages"][1]["name"] = metadata["packages"][0]["name"] + with self.assertRaises(ValueError): + partition(metadata) + + +class VerifiedDownload(unittest.TestCase): + def download(self, modes): + with tempfile.TemporaryDirectory() as temp: + directory = Path(temp) + curl = directory / "curl" + curl.write_text( + "#!/usr/bin/env python3\n" + "import os, pathlib, sys\n" + "args = sys.argv[1:]\n" + "assert '--connect-timeout' in args and '--retry' in args\n" + "url = args[args.index('--output') - 1]\n" + "with open(os.environ['CALLS'], 'a') as calls: calls.write(url + '\\n')\n" + "if url == 'offline': sys.exit(28)\n" + "pathlib.Path(args[args.index('--output') + 1]).write_bytes(url.encode())\n" + ) + curl.chmod(0o755) + output = directory / "archive" + output.write_bytes(b"previous") + calls = directory / "calls" + result = subprocess.run( + [ + "bash", + str(ROOT / ".github/scripts/download-verified.sh"), + str(output), + hashlib.sha256(b"verified").hexdigest(), + *modes, + ], + env=os.environ + | {"PATH": f"{directory}:{os.environ['PATH']}", "CALLS": str(calls)}, + capture_output=True, + text=True, + timeout=10, + ) + return ( + result.returncode, + output.read_bytes(), + calls.read_text().splitlines(), + list(directory.glob("*.part.*")), + ) + + def test_network_failure_uses_verified_mirror(self): + code, content, calls, partials = self.download(["offline", "verified"]) + self.assertEqual( + (code, content, calls, partials), + (0, b"verified", ["offline", "verified"], []), + ) + + def test_checksum_failure_does_not_promote_or_try_another_mirror(self): + code, content, calls, partials = self.download(["tampered", "verified"]) + self.assertNotEqual(code, 0) + self.assertEqual((content, calls, partials), (b"previous", ["tampered"], [])) + + def test_all_sources_down_preserves_existing_file(self): + code, content, calls, partials = self.download(["offline", "offline"]) + self.assertNotEqual(code, 0) + self.assertEqual( + (content, calls, partials), (b"previous", ["offline", "offline"], []) + ) + + +class AggregateResults(unittest.TestCase): + def test_only_successful_nonempty_dependencies_pass(self): + cases = [({}, False), ({"child": {"result": "success"}}, True)] + cases.extend( + ({"child": {"result": result}}, False) + for result in ("failure", "cancelled", "skipped", "timed_out", "unknown") + ) + for dependencies, accepted in cases: + with self.subTest(dependencies=dependencies): + result = subprocess.run( + ["python3", str(ROOT / ".github/scripts/check_ci_results.py")], + env=os.environ | {"NEEDS": json.dumps(dependencies)}, + capture_output=True, + timeout=10, + ) + self.assertEqual(result.returncode == 0, accepted) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/scripts/test_upstream_ci.py b/.github/scripts/test_upstream_ci.py new file mode 100644 index 000000000000..7253b2e6a8cb --- /dev/null +++ b/.github/scripts/test_upstream_ci.py @@ -0,0 +1,389 @@ +"""Regression coverage for accidentally weakened Linux CI gates.""" + +from pathlib import Path +import shutil +import tempfile +import unittest + +import check_upstream_ci as policy + + +class LinuxProjection(unittest.TestCase): + def test_linux_test_archives_keep_the_verified_runtime_payload(self): + path = ".github/workflows/rust-ci-full-nextest-platform.yml" + official = ( + " - name: Build nextest archive\n" + " run: cargo nextest archive --workspace\n" + ' cp "${CARGO_TARGET_DIR}/${CODEX_CI_TARGET}/${CODEX_CI_PROFILE}/codex-linux-sandbox" "${helper_dir}/"\n' + " - name: tests\n" + ' chmod +x "${helper_target_dir}/codex-linux-sandbox"\n' + ' cargo nextest run --archive-file "$archive_file"\n' + ) + projected = policy.linux_projection(path, official) + self.assertIn("CODEX_BWRAP_SHA256", projected) + self.assertIn("sha256sum --check bwrap.sha256", projected) + self.assertIn("run: cargo nextest archive --workspace", projected) + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) / "fork" + upstream = Path(temp) / "upstream" + for directory in (root, upstream): + (directory / path).parent.mkdir(parents=True) + (upstream / path).write_text(official) + (root / path).write_text(projected) + self.assertEqual(policy.baseline_errors(root, upstream, [path]), []) + for mutation in ( + projected.replace(" --bin bwrap", " --bin codex"), + projected.replace("sha256sum --check bwrap.sha256", "true"), + projected.replace(policy.LINUX_RUNTIME_EXPORT, ""), + ): + with self.subTest(mutation=mutation): + (root / path).write_text(mutation) + self.assertTrue(policy.baseline_errors(root, upstream, [path])) + + def test_workspace_argument_comment_lint_stays_in_the_pr_graph(self): + path = ".github/workflows/rust-ci.yml" + official = ( + "jobs:\n argument_comment_lint_prebuilt:\n" + " runs-on: ubuntu-24.04\n" + " steps:\n - uses: ./.github/actions/run-argument-comment-lint\n" + " results:\n needs: [argument_comment_lint_prebuilt]\n" + " run: summarize\n" + ) + projected = policy.linux_projection(path, official) + self.assertEqual(projected, official) + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) / "fork" + upstream = Path(temp) / "upstream" + for directory in (root, upstream): + (directory / path).parent.mkdir(parents=True) + (upstream / path).write_text(official) + for mutation in ( + projected.replace( + " - uses: ./.github/actions/run-argument-comment-lint\n", "" + ), + projected.replace( + "needs: [argument_comment_lint_prebuilt]", "needs: []" + ), + projected.replace(" steps:\n", " if: false\n steps:\n"), + ): + with self.subTest(mutation=mutation): + (root / path).write_text(mutation) + self.assertTrue(policy.baseline_errors(root, upstream, [path])) + + def test_linux_binding_generation_preserves_archive_verification(self): + path = ".github/actions/setup-rusty-v8/action.yml" + official = "runs:\n using: composite\n steps:\n - run: sha256sum --check manifest\n" + projected = policy.linux_projection(path, official) + self.assertIn("sha256sum --check manifest", projected) + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) / "fork" + upstream = Path(temp) / "upstream" + for directory in (root, upstream): + (directory / path).parent.mkdir(parents=True) + (upstream / path).write_text(official) + (root / path).write_text(projected) + self.assertEqual(policy.baseline_errors(root, upstream, [path]), []) + for mutation in ( + projected.replace("sha256sum --check manifest", "true"), + projected.replace("if: runner.os == 'Linux'", "if: false"), + projected.replace("codefx-linux-v8-binding", "unverified-binding"), + ): + (root / path).write_text(mutation) + self.assertTrue(policy.baseline_errors(root, upstream, [path])) + + def test_linux_matrices_keep_commands_and_drop_other_platforms(self): + source = ( + "jobs:\n test:\n strategy:\n matrix:\n include:\n" + " - os: macos-15-xlarge\n target: aarch64-apple-darwin\n" + " - os: ubuntu-24.04\n target: x86_64-unknown-linux-gnu\n" + " - os: ubuntu-24.04\n target: x86_64-unknown-linux-musl\n" + " - os: ubuntu-24.04-arm\n target: aarch64-unknown-linux-gnu\n" + " - os: ubuntu-24.04-arm\n target: aarch64-unknown-linux-musl\n" + " - os: windows-latest\n target: x86_64-pc-windows-msvc\n" + " steps:\n - run: bazel test //...\n" + ) + projected = policy.linux_projection( + ".github/workflows/rust-ci-full.yml", source + ) + self.assertIn("target: x86_64-unknown-linux-gnu", projected) + self.assertIn("target: x86_64-unknown-linux-musl", projected) + self.assertIn("run: bazel test //...", projected) + self.assertNotIn("target: aarch64-apple-darwin", projected) + self.assertNotIn("target: x86_64-pc-windows-msvc", projected) + self.assertNotIn("target: aarch64-unknown-linux-gnu", projected) + self.assertNotIn("target: aarch64-unknown-linux-musl", projected) + + def test_named_linux_lint_matrix_is_retained(self): + source = ( + "jobs:\n lint:\n strategy:\n matrix:\n include:\n" + " - name: Linux\n runner: ubuntu-24.04\n" + " timeout_minutes: 30\n" + " - name: Windows\n runner: windows-x64\n" + " steps:\n - run: lint\n" + ) + projected = policy.linux_projection(".github/workflows/rust-ci.yml", source) + self.assertIn("name: Linux", projected) + self.assertIn("timeout_minutes: 360", projected) + self.assertNotIn("name: Windows", projected) + self.assertIn("run: lint", projected) + + def test_v8_linux_smoke_keeps_target_and_ignored_tests(self): + source = ( + "jobs:\n build:\n strategy:\n matrix:\n include:\n" + " - runner: ubuntu-24.04\n" + " target: x86_64-unknown-linux-musl\n" + " - runner: macos-15-xlarge\n" + " target: aarch64-apple-darwin\n" + " steps:\n" + ' - run: cargo test --target "${TARGET}" -- --include-ignored\n' + " build-windows-source:\n runs-on: windows-2025\n" + ) + projected = policy.linux_projection(".github/workflows/v8-canary.yml", source) + self.assertIn("target: x86_64-unknown-linux-musl", projected) + self.assertIn('--target "${TARGET}" -- --include-ignored', projected) + self.assertNotIn("build-windows-source", projected) + self.assertNotIn("target: aarch64-apple-darwin", projected) + + def test_v8_canary_selects_each_native_feature_variant_explicitly(self): + path = ".github/workflows/v8-canary.yml" + official = ( + 'cargo_args=(test -p codex-v8-poc --target "${TARGET}")\n' + 'if [[ "${SANDBOX}" == "true" ]]; then\n' + " cargo_args+=(--features sandbox)\n" + "fi\n" + "cargo_args+=(-- --include-ignored)\n" + ) + projected = policy.linux_projection(path, official) + self.assertIn("--no-default-features", projected) + self.assertIn("--features sandbox", projected) + self.assertIn("--include-ignored", projected) + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) / "fork" + upstream = Path(temp) / "upstream" + for directory in (root, upstream): + (directory / path).parent.mkdir(parents=True) + (upstream / path).write_text(official) + (root / path).write_text(projected) + self.assertEqual(policy.baseline_errors(root, upstream, [path]), []) + for mutation in ( + projected.replace(" --no-default-features", ""), + projected.replace("--features sandbox", "--features wrong"), + projected.replace("--include-ignored", "--ignored"), + ): + with self.subTest(mutation=mutation): + (root / path).write_text(mutation) + self.assertTrue(policy.baseline_errors(root, upstream, [path])) + + def test_nextest_archive_prepares_verified_v8_inputs(self): + path = ".github/workflows/rust-ci-full-nextest-platform.yml" + official = ( + "jobs:\n archive:\n steps:\n" + " - uses: ./.github/actions/setup-ci\n" + " - name: Compute lockfile hash\n" + " run: sha256sum Cargo.lock\n" + " - run: cargo nextest archive --workspace\n" + ) + projected = policy.linux_projection(path, official) + self.assertIn(policy.V8_ARCHIVE_STEP, projected) + self.assertIn("run: cargo nextest archive --workspace", projected) + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) / "fork" + upstream = Path(temp) / "upstream" + for directory in (root, upstream): + (directory / path).parent.mkdir(parents=True) + (upstream / path).write_text(official) + (root / path).write_text(projected) + self.assertEqual(policy.baseline_errors(root, upstream, [path]), []) + for mutation in ( + projected.replace(policy.V8_ARCHIVE_STEP, ""), + projected.replace("if: runner.os == 'Linux'\n", "if: false\n"), + projected.replace("target: ${{ inputs.target }}", "target: wrong"), + ): + with self.subTest(mutation=mutation): + (root / path).write_text(mutation) + self.assertTrue(policy.baseline_errors(root, upstream, [path])) + + def test_missing_command_and_new_skip_condition_are_drift(self): + path = ".github/workflows/rust-ci.yml" + official = ( + "jobs:\n shear:\n steps:\n - run: cargo shear --deny-warnings\n" + ) + mutations = ( + official.replace(" - run: cargo shear --deny-warnings\n", ""), + official.replace(" - run:", " - if: false\n run:"), + official.replace("--deny-warnings", "--deny-warnings || true"), + ) + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) / "fork" + upstream = Path(temp) / "upstream" + for directory in (root, upstream): + (directory / path).parent.mkdir(parents=True) + (upstream / path).write_text(official) + for mutation in mutations: + with self.subTest(mutation=mutation): + (root / path).write_text(mutation) + self.assertTrue(policy.baseline_errors(root, upstream, [path])) + (root / path).write_text(official) + self.assertEqual(policy.baseline_errors(root, upstream, [path]), []) + + def test_full_ci_keeps_amd64_fan_in_and_removes_other_platform_jobs(self): + source = ( + "jobs:\n tests_macos_aarch64:\n run: macos\n" + " tests_linux_x64_remote:\n run: linux\n" + " tests_linux_arm64:\n run: arm\n" + " tests_windows_x64:\n run: windows\n" + " results:\n needs:\n - tests_linux_x64_remote\n - tests_linux_arm64\n" + " - tests_macos_aarch64\n - tests_windows_x64\n" + " run: summarize\n" + ) + projected = policy.linux_projection( + ".github/workflows/rust-ci-full.yml", source + ) + self.assertIn("tests_linux_x64_remote", projected) + self.assertNotIn("tests_linux_arm64", projected) + self.assertIn("run: summarize", projected) + self.assertNotIn("tests_macos_aarch64", projected) + self.assertNotIn("tests_windows_x64", projected) + + def test_full_ci_removes_arm64_only_conditions(self): + source = ( + "jobs:\n lint_build:\n" + " env:\n" + " USE_SCCACHE: ${{ (startsWith(matrix.runner, 'windows') || (matrix.runner == 'macos-15-xlarge' && matrix.target == 'x86_64-apple-darwin')) && 'false' || 'true' }}\n" + " steps:\n" + " - if: ${{ matrix.target == 'x86_64-unknown-linux-musl' || matrix.target == 'aarch64-unknown-linux-musl'}}\n" + ) + projected = policy.linux_projection( + ".github/workflows/rust-ci-full.yml", source + ) + self.assertIn('USE_SCCACHE: "true"', projected) + self.assertNotIn("aarch64", projected) + self.assertNotIn("macos-15", projected) + self.assertNotIn("windows", projected) + + +class BazelResourcePolicy(unittest.TestCase): + def test_postmerge_caller_must_allow_the_v8_child_read_permission(self): + path = ".github/workflows/postmerge-ci.yml" + source = ( + "on:\n push:\n branches: [main]\n" + "jobs:\n v8-canary:\n name: v8-canary\n" + " uses: ./.github/workflows/v8-canary.yml\n" + ) + projected = policy.linux_projection(path, source) + self.assertIn("workflow_dispatch:", projected) + self.assertIn("actions: read", projected) + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) / "root" + upstream = Path(temp) / "upstream" + for directory, content in ((root, projected), (upstream, source)): + file = directory / path + file.parent.mkdir(parents=True) + file.write_text(content) + self.assertEqual(policy.baseline_errors(root, upstream, [path]), []) + for original in (" workflow_dispatch:\n", " actions: read\n"): + with self.subTest(original=original): + (root / path).write_text(projected.replace(original, "")) + self.assertTrue(policy.baseline_errors(root, upstream, [path])) + + def test_setup_bazel_must_preserve_and_verify_the_resource_policy(self): + path = ".github/actions/prepare-bazel-ci/action.yml" + source = ( + " output-base: ${{ steps.setup_ci.outputs.bazel-output-base }}\n" + ) + projected = policy.linux_projection(path, source) + self.assertIn("bazelrc:", projected) + self.assertIn("verify_bazel_resources.py", projected) + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) / "root" + upstream = Path(temp) / "upstream" + for directory, content in ((root, projected), (upstream, source)): + file = directory / path + file.parent.mkdir(parents=True) + file.write_text(content) + self.assertEqual(policy.baseline_errors(root, upstream, [path]), []) + for original in ( + " bazelrc:", + "verify_bazel_resources.py", + "bazel_resource_usage.py watch", + ): + with self.subTest(original=original): + (root / path).write_text(projected.replace(original, "disabled")) + self.assertTrue(policy.baseline_errors(root, upstream, [path])) + + def test_cold_build_budget_keeps_all_bazel_commands(self): + source = ( + "jobs:\n test:\n timeout-minutes: 30\n" + " steps:\n - run: bazel test //...\n" + " --test_tag_filters=-argument-comment-lint\n" + " ./.github/scripts/run-bazel-ci.sh \\\n" + " - name: Upload Bazel execution logs\n" + ) + projected = policy.linux_projection(".github/workflows/bazel.yml", source) + self.assertIn("timeout-minutes: 360", projected) + self.assertIn("run: bazel test //...", projected) + self.assertIn("--notest_keep_going", projected) + self.assertIn('if [[ -z "${BUILDBUDDY_API_KEY:-}" ]]', projected) + self.assertIn("--test_strategy=exclusive", projected) + self.assertIn("bazel_resource_usage.py report", projected) + + +class RequiredGate(unittest.TestCase): + def test_unsupported_architectures_cannot_return_to_custom_matrices(self): + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) + shutil.copytree( + policy.ROOT / ".github/workflows", root / ".github/workflows" + ) + self.assertEqual(policy.coverage_errors(root), []) + for name in ("codefx-source-smoke.yml", "codefx-platform-release.yml"): + path = root / ".github/workflows" / name + original = path.read_text() + path.write_text( + original + + "\n - runner: ubuntu-24.04-arm\n target: aarch64-unknown-linux-musl\n" + ) + self.assertTrue(policy.coverage_errors(root)) + path.write_text(original) + + def setUp(self): + self.blocking = (policy.ROOT / ".github/workflows/blocking-ci.yml").read_text() + + def test_all_current_checks_are_required(self): + self.assertEqual(policy.gate_errors(self.blocking), []) + + def test_disconnected_bazel_cargo_or_sdk_cannot_pass(self): + for job in ("bazel", "linux-cargo", "sdk"): + with self.subTest(job=job): + weakened = self.blocking.replace(f" - {job}\n", "") + self.assertTrue(policy.gate_errors(weakened)) + weakened = self.blocking.replace( + f"uses: ./.github/workflows/{'codefx-linux-cargo' if job == 'linux-cargo' else job}.yml", + "uses: ./.github/workflows/rust-ci.yml", + ) + self.assertTrue(policy.gate_errors(weakened)) + + def test_required_call_cannot_ignore_failure_or_run_conditionally(self): + for job in ("bazel", "sdk"): + for condition in ("if: false", "continue-on-error: true"): + weakened = self.blocking.replace( + f" {job}:\n", f" {job}:\n {condition}\n" + ) + self.assertTrue(policy.gate_errors(weakened)) + + def test_required_coverage_is_preserved(self): + self.assertEqual(policy.coverage_errors(policy.ROOT), []) + + def test_sdk_cannot_use_a_package_without_a_successful_producer(self): + weakened = self.blocking.replace( + "needs: [ci-policy, codefx-source-smoke]", "needs: ci-policy" + ) + self.assertTrue(policy.gate_errors(weakened)) + + def test_terminal_gate_cannot_be_skipped_after_failure(self): + weakened = self.blocking.replace(" if: ${{ always() }}\n", "") + self.assertTrue(policy.gate_errors(weakened)) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/scripts/verify_bazel_resources.py b/.github/scripts/verify_bazel_resources.py new file mode 100644 index 000000000000..23986243e524 --- /dev/null +++ b/.github/scripts/verify_bazel_resources.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +"""Exercise the effective resource policy after setup-bazel rewrites its rc file.""" + +import os +from pathlib import Path +import subprocess +import tempfile + + +def verify() -> None: + with tempfile.TemporaryDirectory(prefix="codefx-bazel-policy-") as temp: + root = Path(temp) + cache = root / "action-cache" + # Bazelisk must exercise this checkout's pinned Bazel, not latest. + (root / ".bazelversion").write_text( + (Path(__file__).resolve().parents[2] / ".bazelversion").read_text() + ) + (root / "MODULE.bazel").write_text('module(name = "resource_probe")\n') + (root / ".bazelrc").write_text(f"common --disk_cache={cache}\n") + (root / "BUILD.bazel").write_text( + 'load(":probe.bzl", "resource_test")\n' + 'genrule(name = "probe", outs = ["probe.txt"], ' + 'cmd = "echo verified > $@")\n' + 'resource_test(name = "test_budget")\n' + ) + (root / "probe.bzl").write_text( + "def _impl(ctx):\n" + ' out = ctx.actions.declare_file(ctx.label.name + ".sh")\n' + " ctx.actions.write(out, '#!/bin/sh\\nset -eu\\n" + "test $RUST_TEST_THREADS = 2\\n', is_executable = True)\n" + " return [DefaultInfo(executable = out)]\n" + "resource_test = rule(implementation = _impl, test = True)\n" + ) + bazel = ["bazel", f"--output_base={root / 'output'}"] + try: + result = subprocess.run( + [*bazel, "build", "--announce_rc", "//:probe"], + cwd=root, + capture_output=True, + text=True, + timeout=120, + check=True, + ) + # These options must survive setup-bazel and override the workspace + # rc. The positive control below proves the cache probe is live. + for option in ( + "--disk_cache=", + "--local_resources=cpu=HOST_CPUS", + "--local_resources=memory=4096", + ): + if option not in result.stderr: + raise RuntimeError(f"Effective rc policy missing {option}") + if cache.exists() and any(cache.iterdir()): + raise RuntimeError("setup-bazel re-enabled the disk action cache") + result = subprocess.run( + [ + *bazel, + "test", + "--announce_rc", + "--test_output=errors", + "//:test_budget", + ], + cwd=root, + capture_output=True, + text=True, + timeout=120, + check=True, + ) + for option in ( + "--local_test_jobs=1", + "--test_env=RUST_TEST_THREADS=2", + ): + if option not in result.stderr: + raise RuntimeError(f"Effective test budget missing {option}") + if cache.exists() and any(cache.iterdir()): + raise RuntimeError("Test invocation re-enabled the disk action cache") + # Force another action and explicitly enable caching as a control. + (root / "BUILD.bazel").write_text( + 'genrule(name = "probe", outs = ["probe.txt"], ' + 'cmd = "echo control > $@")\n' + ) + subprocess.run( + [*bazel, "build", f"--disk_cache={cache}", "//:probe"], + cwd=root, + capture_output=True, + text=True, + timeout=120, + check=True, + ) + if not cache.exists() or not any(cache.iterdir()): + raise RuntimeError("Disk cache positive control did not populate") + except subprocess.CalledProcessError as error: + # The isolated probe never has credentials in its command line. + print(error.stdout) + print(error.stderr) + raise + finally: + subprocess.run([*bazel, "shutdown"], cwd=root, timeout=30, check=False) + print("Verified Bazel CPU/memory/test budgets and disabled disk action cache") + + +if __name__ == "__main__": + if os.environ.get("GITHUB_ACTIONS") != "true": + raise SystemExit("This build probe runs only in GitHub Actions") + verify() diff --git a/.github/scripts/verify_cargo_workspace_manifests.py b/.github/scripts/verify_cargo_workspace_manifests.py index a8c6c28602f2..8c99e8b07063 100644 --- a/.github/scripts/verify_cargo_workspace_manifests.py +++ b/.github/scripts/verify_cargo_workspace_manifests.py @@ -26,7 +26,12 @@ "path-utils": "codex-utils-path", } MANIFEST_FEATURE_EXCEPTIONS = { - "codex-rs/v8-poc/Cargo.toml": {"sandbox": ("v8/v8_enable_sandbox",)}, + # Match the native sandbox pair used by workspace builds. Canary smoke + # selects each release variant explicitly with --no-default-features. + "codex-rs/v8-poc/Cargo.toml": { + "default": ("sandbox",), + "sandbox": ("v8/v8_enable_sandbox",), + }, } OPTIONAL_DEPENDENCY_EXCEPTIONS = set() INTERNAL_DEPENDENCY_FEATURE_EXCEPTIONS = {} diff --git a/.github/upstream-ci.json b/.github/upstream-ci.json new file mode 100644 index 000000000000..7e263478fcba --- /dev/null +++ b/.github/upstream-ci.json @@ -0,0 +1,32 @@ +{ + "repository": "openai/codex", + "tag": "rust-v0.166.0", + "commit": "6ff1e1ca3b30fc8b914720681fcf5fe62e95f856", + "files": [ + ".github/workflows/bazel.yml", + ".github/workflows/blob-size-policy.yml", + ".github/workflows/cargo-deny.yml", + ".github/workflows/codespell.yml", + ".github/workflows/postmerge-ci.yml", + ".github/workflows/repo-checks.yml", + ".github/workflows/rust-ci.yml", + ".github/workflows/rust-ci-full.yml", + ".github/workflows/rust-ci-full-nextest-platform.yml", + ".github/workflows/sdk.yml", + ".github/workflows/v8-canary.yml", + ".github/actions/check-clean-worktree/action.yml", + ".github/actions/prepare-bazel-ci/action.yml", + ".github/actions/run-argument-comment-lint/action.yml", + ".github/actions/setup-ci/action.yml", + ".github/actions/setup-rusty-v8/action.yml", + ".github/scripts/run-bazel-ci.sh", + ".github/scripts/run-bazel-query-ci.sh", + ".github/scripts/run_bazel_with_buildbuddy.py", + ".github/scripts/run-argument-comment-lint-bazel.sh", + ".github/scripts/rusty_v8_bazel.py", + ".github/scripts/v8_canary_changes.py", + "scripts/check-module-bazel-lock.sh", + "scripts/list-bazel-clippy-targets.sh", + "scripts/list-bazel-release-targets.sh" + ] +} diff --git a/.github/workflows/README.md b/.github/workflows/README.md index 70445ab5936c..86c334911b88 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -1,37 +1,33 @@ -# Workflow Strategy +# Codefx Linux CI -The workflows in this directory are split so that pull requests get fast, review-friendly signal while `main` still gets the full cross-platform verification pass. +All validation runs in GitHub Actions. See [CI_POLICY.md](../CI_POLICY.md) for +the immutable upstream baseline, coverage requirements and allowed adaptations. -## Pull Requests +`blocking-ci.yml` validates the PR merge revision and produces `CI required`. +It requires the official Linux Bazel graph and workspace argument-comment lint, +fast Rust checks, complete GNU Cargo package test coverage and Clippy, +SDK tests, dependency/repository policy, installer safety and current-source +amd64 musl packages. ARM64, macOS and Windows are outside the supported matrix. +Failed, cancelled or unexpectedly skipped dependencies +fail the aggregate. -- Required checks run against GitHub's synthetic merge commit, not the pull - request head alone. This includes changes already on `main` and catches - conflicts before they reach the branch. -- `bazel.yml` is the main pre-merge verification path for Rust code. - It runs Bazel `test` and Bazel `clippy` on the supported Bazel targets, - including the generated Rust test binaries needed to lint inline `#[cfg(test)]` - code. -- `rust-ci.yml` keeps the Cargo-native PR checks intentionally small: - - `cargo fmt --check` - - `cargo shear` - - `argument-comment-lint` on Linux, macOS, and Windows - - `tools/argument-comment-lint` package tests when the lint or its workflow wiring changes +`codefx-linux-cargo.yml` partitions workspace packages before compilation so a +single runner does not link and archive the complete workspace. It retains core +retry, TUI/update and app-server tests. It runs tests directly with nextest. -## Post-Merge On `main` +`codefx-source-smoke.yml` builds and installs the actual candidate packages. +`sdk.yml` consumes the successful same-run x86_64 package after checking its source, +version, target and digest. It does not rebuild the CLI or reuse a published tag. +`codefx-native-smoke.yml` checks published releases separately. -- `bazel.yml` also runs on pushes to `main`. - This re-verifies the merged Bazel path and helps keep the BuildBuddy caches warm. -- `rust-ci-full.yml` is the full Cargo-native verification workflow. - It keeps the heavier checks off the PR path while still validating them after merge: - - the full Cargo `clippy` matrix - - the full Cargo `nextest` matrix via per-platform archive-backed shards - - Windows ARM64 nextest archives cross-compiled on Windows x64, then replayed on native Windows ARM64 shards - - release-profile Cargo builds - - cross-platform `argument-comment-lint` - - Linux remote-env tests +`codefx-extended-ci.yml` also runs the required Bazel checks independently on main +or manually. `postmerge-ci.yml` retains full Linux Cargo and V8 validation. +It also supports manual runs to validate nested workflow permissions and the +postmerge aggregate on a candidate before merging. +Full Cargo includes remote-environment tests and also supports manual execution +and `full-ci` branches. -## Rule Of Thumb - -- If a build/test/clippy check can be expressed in Bazel, prefer putting the PR-time version in `bazel.yml`. -- Keep `rust-ci.yml` fast enough that it usually does not dominate PR latency. -- Reserve `rust-ci-full.yml` for heavyweight Cargo-native coverage that Bazel does not replace yet. +For an upstream upgrade or release, run full Linux amd64 validation and its native +package check on the final candidate. A green fast gate is not a full CI pass. +Use Actions run links and exact commits when reporting results. Branch protection +must explicitly require the aggregate; workflows do not configure it themselves. diff --git a/.github/workflows/bazel.yml b/.github/workflows/bazel.yml index 1394620dd65b..86b2b1bfa18d 100644 --- a/.github/workflows/bazel.yml +++ b/.github/workflows/bazel.yml @@ -10,28 +10,35 @@ on: concurrency: # Cancel previous actions from the same PR or branch except 'main' branch. # See https://docs.github.com/en/actions/using-jobs/using-concurrency and https://docs.github.com/en/actions/learn-github-actions/contexts for more info. - group: concurrency-group::${{ github.workflow }}::${{ github.event.pull_request.number > 0 && format('pr-{0}', github.event.pull_request.number) || github.ref_name }}${{ github.ref_name == 'main' && format('::{0}', github.run_id) || ''}}::scheduler-v4 + group: concurrency-group::${{ github.workflow }}::${{ github.event.pull_request.number > 0 && format('pr-{0}', github.event.pull_request.number) || github.ref_name }}${{ github.ref_name == 'main' && format('::{0}', github.run_id) || ''}} cancel-in-progress: ${{ github.ref_name != 'main' }} jobs: test: - # Split the complete Linux Bazel test set across isolated runners. - # A monolithic cold build occupied 88 GiB in Bazel's output base and - # exhausted the 145 GiB hosted runner during Rust test linking. - # Deterministic target sharding preserves every compatible test target. - timeout-minutes: 240 + # PRs use the sharded Windows cross-compiled test jobs below. Post-merge + # pushes to main also run the native Windows test job for broader Windows + # signal without putting PR latency back on the critical path. When + # Code-mode unit tests run on every Bazel target. When authenticated RBE + # is available, the Windows-cross shards exercise the source-built V8 path. + timeout-minutes: 360 strategy: fail-fast: false - max-parallel: 2 matrix: - target: - - x86_64-unknown-linux-gnu - - x86_64-unknown-linux-musl - shard: [1, 2, 3, 4] - # ARM Linux tests remain disabled due to upstream flakiness. - runs-on: ubuntu-24.04 - - name: Bazel test on ubuntu-24.04 for ${{ matrix.target }} shard ${{ matrix.shard }}/4 + include: + # macOS + - os: ubuntu-24.04 + target: x86_64-unknown-linux-gnu + # 2026-02-27 Bazel tests have been flaky on arm in CI. + # Disable until we can investigate and stabilize them. + # - os: ubuntu-24.04-arm + # target: aarch64-unknown-linux-musl + # - os: ubuntu-24.04-arm + # target: aarch64-unknown-linux-gnu + + runs-on: ${{ matrix.os }} + + # Configure a human readable name for each job + name: Bazel native GNU tests on ${{ matrix.os }} environment: name: bazel deployment: false @@ -46,32 +53,17 @@ jobs: uses: ./.github/actions/prepare-bazel-ci with: target: ${{ matrix.target }} - cache-scope: bazel-target - # The full local Linux test graph can exhaust even a 145 GB runner. - # Avoid duplicating thousands of Bazel outputs in the disk action cache. - action-cache: "false" - - # Bazel's CAS validates each artifact. Only shard 1 saves a bounded - # snapshot, which later shards and PR commits can reuse. - - name: Restore Linux Bazel compiled actions - id: restore_linux_actions - continue-on-error: true - uses: actions/cache/restore@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5.0.4 - with: - path: ${{ runner.temp }}/codefx-bazel-actions - key: codefx-bazel-actions-v1-${{ matrix.target }}-${{ hashFiles('.bazelrc', 'MODULE.bazel', 'MODULE.bazel.lock', 'codex-rs/Cargo.lock', 'codex-rs/Cargo.toml') }} - restore-keys: | - codefx-bazel-actions-v1-${{ matrix.target }}- + cache-scope: bazel-${{ github.job }} - name: Check rusty_v8 MODULE.bazel checksums - if: matrix.target == 'x86_64-unknown-linux-gnu' && matrix.shard == 1 + if: matrix.os == 'ubuntu-24.04' && matrix.target == 'x86_64-unknown-linux-gnu' shell: bash run: | python3 .github/scripts/rusty_v8_bazel.py check-module-bazel just test-github-scripts - name: Check MODULE.bazel.lock is up to date - if: matrix.target == 'x86_64-unknown-linux-gnu' && matrix.shard == 1 + if: matrix.os == 'ubuntu-24.04' && matrix.target == 'x86_64-unknown-linux-gnu' env: BUILDBUDDY_API_KEY: ${{ secrets.BUILDBUDDY_API_KEY }} shell: bash @@ -85,282 +77,6 @@ jobs: releases="$(python3 .github/scripts/resolve_exec_server_releases.py)" echo "CODEX_COMPAT_RELEASES=$releases" >> "$GITHUB_ENV" - - name: bazel test shard - env: - BUILDBUDDY_API_KEY: ${{ secrets.BUILDBUDDY_API_KEY }} - BAZEL_TEST_SHARD: ${{ matrix.shard }} - BAZEL_TEST_SHARD_COUNT: 4 - BAZEL_ACTION_CACHE_HIT: ${{ steps.restore_linux_actions.outputs.cache-hit }} - shell: bash - run: | - set -euo pipefail - # Match the test set selected by Bazel's //... wildcard while - # excluding standalone V8, manual and separately linted tests. - query='tests(//...) except tests(//third_party/v8:all) except attr(tags, "manual", tests(//...)) except attr(tags, "argument-comment-lint", tests(//...))' - targets_file="$(mktemp)" - selected_file="$(mktemp)" - trap 'rm -f "${targets_file}" "${selected_file}"' EXIT - ./.github/scripts/run-bazel-query-ci.sh --output=label -- "${query}" \ - | LC_ALL=C sort > "${targets_file}" - # The shared deterministic selector also supports Linux when - # duration weights are disabled. Each label appears on one shard. - python3 .github/scripts/select_windows_bazel_targets.py \ - --shard "${BAZEL_TEST_SHARD}" \ - --shard-count "${BAZEL_TEST_SHARD_COUNT}" \ - --durations /dev/null \ - < "${targets_file}" > "${selected_file}" - mapfile -t selected_targets < "${selected_file}" - - bazel_test_args=( - test - --build_tests_only - --skip_incompatible_explicit_targets - --disk_cache=${RUNNER_TEMP}/codefx-bazel-actions - --experimental_disk_cache_gc_max_size=2G - --test_tag_filters=-argument-comment-lint - --test_verbose_timeout_warnings - --build_metadata=COMMIT_SHA=${GITHUB_SHA} - --build_metadata=TAG_linux_test_shard=${BAZEL_TEST_SHARD} - ) - if [[ -z "${BUILDBUDDY_API_KEY:-}" ]]; then - bazel_test_args+=(--jobs=8) - # Immutable cache snapshots are read-only on exact hits; other - # shards read the shared snapshot without duplicating cache writes. - if [[ "${BAZEL_TEST_SHARD}" != "1" || "${BAZEL_ACTION_CACHE_HIT}" == "true" ]]; then - bazel_test_args+=(--noremote_upload_local_results) - fi - fi - ./.github/scripts/run-bazel-ci.sh \ - --print-failed-action-summary \ - --print-failed-test-logs \ - -- \ - "${bazel_test_args[@]}" \ - -- \ - "${selected_targets[@]}" - - - name: Record disk usage after Linux Bazel tests - if: always() && !cancelled() - shell: bash - run: | - df -h "${GITHUB_WORKSPACE}" - for dir in "${BAZEL_OUTPUT_BASE}" "${BAZEL_REPOSITORY_CACHE}" "${RUNNER_TEMP}/codefx-bazel-actions"; do - if [[ -d "${dir}" ]]; then - du -sh "${dir}" || true - fi - done - - # Prune after Bazel exits to prevent races with running compilation. - # Keep only a 2 GiB snapshot per Linux target (4 GiB for both targets). - - name: Bound Linux Bazel compiled action cache - if: ${{ always() && !cancelled() && matrix.shard == 1 && steps.restore_linux_actions.outputs.cache-hit != 'true' }} - shell: bash - run: | - python3 - <<'PY' - import os - from pathlib import Path - - cache = Path(os.environ["RUNNER_TEMP"]) / "codefx-bazel-actions" - limit = 2 * 1024 ** 3 - files = [] - for directory, _, names in os.walk(cache): - for name in names: - path = Path(directory) / name - if path.is_symlink(): - continue - try: - stat = path.stat() - except FileNotFoundError: - continue - files.append((max(stat.st_atime_ns, stat.st_mtime_ns), path, stat.st_size)) - size = sum(length for _, _, length in files) - for _, path, length in sorted(files): - if size <= limit: - break - try: - path.unlink() - except FileNotFoundError: - continue - size -= length - print(f"Bazel action cache snapshot: {size / 1024 ** 3:.2f} GiB") - PY - - - name: Save bounded Linux Bazel compiled action cache - if: ${{ always() && !cancelled() && matrix.shard == 1 && steps.restore_linux_actions.outputs.cache-hit != 'true' }} - continue-on-error: true - uses: actions/cache/save@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5.0.4 - with: - path: ${{ runner.temp }}/codefx-bazel-actions - key: codefx-bazel-actions-v1-${{ matrix.target }}-${{ hashFiles('.bazelrc', 'MODULE.bazel', 'MODULE.bazel.lock', 'codex-rs/Cargo.lock', 'codex-rs/Cargo.toml') }} - - - name: Upload Bazel execution logs - if: always() && !cancelled() - continue-on-error: true - uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 - with: - name: bazel-execution-logs-test-${{ matrix.target }}-shard-${{ matrix.shard }} - path: ${{ runner.temp }}/bazel-execution-logs - if-no-files-found: ignore - - # Save the job-scoped Bazel repository cache after cache misses. Keep the - # upload non-fatal so cache service issues never fail the job itself. - - name: Save bazel repository cache - if: always() && !cancelled() && steps.prepare_bazel.outputs.repository-cache-hit != 'true' - continue-on-error: true - uses: actions/cache/save@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5.0.4 - with: - path: ${{ steps.prepare_bazel.outputs.repository-cache-path }} - key: ${{ steps.prepare_bazel.outputs.repository-cache-key }} - - - name: Check for a clean worktree - if: always() && !cancelled() - uses: ./.github/actions/check-clean-worktree - - test-windows-shard: - # Split the Windows Bazel test leg across separate Windows hosts. Jobs with - # BuildBuddy credentials use Linux RBE for build actions; test execution - # remains on a Windows runner. - timeout-minutes: 180 - needs: test - # Preserve coverage after a failed Linux dependency, but stop all queued - # Windows shards promptly when a newer PR revision cancels this run. - if: ${{ always() && !cancelled() }} - strategy: - fail-fast: false - max-parallel: 2 - matrix: - shard: - - 1 - - 2 - - 3 - - 4 - runs-on: windows-2025 - name: Bazel test on windows-latest for x86_64-pc-windows-gnullvm shard ${{ matrix.shard }}/4 - environment: - name: bazel - deployment: false - - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - persist-credentials: false - - - name: Test BuildBuddy Bazel wrapper - if: matrix.shard == 1 - shell: pwsh - run: python .github/scripts/test_run_bazel_with_buildbuddy.py - - - name: Test Windows Bazel target selector - if: matrix.shard == 1 - shell: pwsh - run: python -m unittest discover -s .github/scripts -p test_select_windows_bazel_targets.py - - - name: Prepare Bazel CI - id: prepare_bazel - uses: ./.github/actions/prepare-bazel-ci - with: - target: x86_64-pc-windows-gnullvm - # Reuse the former monolithic Windows test cache for restores. Do - # not save it from every shard below; duplicate uploads would sit on - # the PR-blocking critical path after the useful test work is done. - cache-scope: bazel-target - - - name: bazel test shard - env: - BAZEL_TEST_SHARD: ${{ matrix.shard }} - BAZEL_TEST_SHARD_COUNT: 4 - BUILDBUDDY_API_KEY: ${{ secrets.BUILDBUDDY_API_KEY }} - shell: bash - run: | - set -euo pipefail - - bazel_test_query='tests(//...) except tests(//third_party/v8:all) except attr(tags, "manual", tests(//...))' - bazel_targets_file="$(mktemp)" - selected_targets_file="$(mktemp)" - trap 'rm -f "${bazel_targets_file}" "${selected_targets_file}"' EXIT - - # Keep query and selection in the foreground so failures cannot leave - # different jobs assigning different partial target lists. - ./.github/scripts/run-bazel-query-ci.sh --output=label -- "${bazel_test_query}" \ - | LC_ALL=C sort > "${bazel_targets_file}" - python .github/scripts/select_windows_bazel_targets.py \ - --shard "${BAZEL_TEST_SHARD}" \ - --shard-count "${BAZEL_TEST_SHARD_COUNT}" \ - < "${bazel_targets_file}" > "${selected_targets_file}" - mapfile -t selected_targets < "${selected_targets_file}" - - bazel_test_args=( - test - --skip_incompatible_explicit_targets - --test_tag_filters=-argument-comment-lint - --test_verbose_timeout_warnings - --build_metadata=COMMIT_SHA=${GITHUB_SHA} - --build_metadata=TAG_windows_test_shard=${BAZEL_TEST_SHARD} - ) - - ./.github/scripts/run-bazel-ci.sh \ - --print-failed-action-summary \ - --print-failed-test-logs \ - --windows-cross-compile \ - --remote-download-toplevel \ - -- \ - "${bazel_test_args[@]}" \ - -- \ - "${selected_targets[@]}" - - - name: Upload Bazel execution logs - if: always() && !cancelled() - continue-on-error: true - uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 - with: - name: bazel-execution-logs-test-x86_64-pc-windows-gnullvm-shard-${{ matrix.shard }} - path: ${{ runner.temp }}/bazel-execution-logs - if-no-files-found: ignore - - - name: Check for a clean worktree - if: always() && !cancelled() - uses: ./.github/actions/check-clean-worktree - - test-windows: - # Preserve the existing required-check surface while the real work happens - # in the sharded Windows jobs above. - if: ${{ always() && !cancelled() }} - needs: test-windows-shard - runs-on: ubuntu-24.04 - name: Bazel test on windows-latest for x86_64-pc-windows-gnullvm - - steps: - - name: Confirm Windows Bazel test shards passed - shell: bash - run: | - if [[ "${{ needs.test-windows-shard.result }}" != "success" ]]; then - echo "Windows Bazel test shards finished with result: ${{ needs.test-windows-shard.result }}" >&2 - exit 1 - fi - - test-windows-native-main: - # Native Windows Bazel tests are slower and frequently approach the - # 30-minute PR budget. Run this only for post-merge commits to main and give - # it a larger timeout. Also allow manual runs for native toolchain changes. - if: (github.event_name == 'push' && github.ref == 'refs/heads/main') || github.event_name == 'workflow_dispatch' - timeout-minutes: 240 - runs-on: windows-2025 - name: Bazel test on windows-latest for x86_64-pc-windows-msvc (native main) - environment: - name: bazel - deployment: false - - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - persist-credentials: false - - - name: Prepare Bazel CI - id: prepare_bazel - uses: ./.github/actions/prepare-bazel-ci - with: - target: x86_64-pc-windows-msvc - cache-scope: bazel-target - - name: bazel test //... env: BUILDBUDDY_API_KEY: ${{ secrets.BUILDBUDDY_API_KEY }} @@ -372,34 +88,42 @@ jobs: # path. V8 consumers under `//codex-rs/...` still participate # transitively through `//...`. -//third_party/v8:all - -//codex-rs/v8-poc:v8-poc-unit-tests ) + bazel_wrapper_args=( + --print-failed-action-summary + --print-failed-test-logs + ) bazel_test_args=( test - --config=ci-windows-msvc - --platforms=//:windows_x86_64_msvc --test_tag_filters=-argument-comment-lint + --notest_keep_going --test_verbose_timeout_warnings --build_metadata=COMMIT_SHA=${GITHUB_SHA} - --build_metadata=TAG_windows_native_main=true ) - + if [[ -z "${BUILDBUDDY_API_KEY:-}" ]]; then + # A local_test_jobs cap does not stop native compilation from + # starving tests with short protocol deadlines. Exclusive tests + # run after the build graph, retaining every selected test. + bazel_test_args+=(--test_strategy=exclusive) + fi ./.github/scripts/run-bazel-ci.sh \ - --print-failed-action-summary \ - --print-failed-test-logs \ - --windows-msvc-host-platform \ + "${bazel_wrapper_args[@]}" \ -- \ "${bazel_test_args[@]}" \ -- \ "${bazel_targets[@]}" + - name: Report Bazel runner resources + if: always() && runner.os == 'Linux' + run: python3 .github/scripts/bazel_resource_usage.py report + - name: Upload Bazel execution logs if: always() && !cancelled() continue-on-error: true uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 with: - name: bazel-execution-logs-test-windows-native-x86_64-pc-windows-msvc + name: bazel-execution-logs-test-${{ matrix.target }} path: ${{ runner.temp }}/bazel-execution-logs if-no-files-found: ignore @@ -418,23 +142,18 @@ jobs: uses: ./.github/actions/check-clean-worktree clippy: - # Run after the platform test matrix so the shared Bazel action cache is - # warm before lint builds start. The always() guard keeps lint diagnostics - # available even when a test leg fails. - needs: [test, test-windows-shard] - if: ${{ always() && !cancelled() }} - timeout-minutes: 180 + timeout-minutes: 360 strategy: fail-fast: false - max-parallel: 1 matrix: include: - # Retain Linux x64 and Windows gnullvm lint coverage on the CI toolchains. + # Keep Linux lint coverage on x64 and add the arm64 macOS path that + # the Bazel test job already exercises. Add Windows gnullvm as well + # so PRs get Bazel-native lint signal on the same Windows toolchain + # that the Bazel test job uses. - os: ubuntu-24.04 target: x86_64-unknown-linux-gnu - - os: windows-2025 - target: x86_64-pc-windows-gnullvm - runs-on: ${{ matrix.runs_on || matrix.os }} + runs-on: ${{ matrix.os }} name: Bazel clippy on ${{ matrix.os }} for ${{ matrix.target }} environment: name: bazel @@ -450,7 +169,7 @@ jobs: uses: ./.github/actions/prepare-bazel-ci with: target: ${{ matrix.target }} - cache-scope: bazel-target + cache-scope: bazel-${{ github.job }} - name: Resolve app-server/exec-server compatibility releases if: runner.os == 'Linux' @@ -503,6 +222,10 @@ jobs: -- \ "${bazel_targets[@]}" + - name: Report Bazel runner resources + if: always() && runner.os == 'Linux' + run: python3 .github/scripts/bazel_resource_usage.py report + - name: Upload Bazel execution logs if: always() && !cancelled() continue-on-error: true @@ -527,21 +250,14 @@ jobs: uses: ./.github/actions/check-clean-worktree verify-release-build: - # Reuse the action cache populated by tests and clippy instead of starting - # two cold Bazel graphs in parallel. - needs: clippy - if: ${{ always() && !cancelled() }} - timeout-minutes: 180 + timeout-minutes: 360 strategy: fail-fast: false - max-parallel: 1 matrix: include: - os: ubuntu-24.04 target: x86_64-unknown-linux-gnu - - os: windows-2025 - target: x86_64-pc-windows-gnullvm - runs-on: ${{ matrix.runs_on || matrix.os }} + runs-on: ${{ matrix.os }} name: Verify release build on ${{ matrix.os }} for ${{ matrix.target }} environment: name: bazel @@ -557,7 +273,7 @@ jobs: uses: ./.github/actions/prepare-bazel-ci with: target: ${{ matrix.target }} - cache-scope: bazel-target + cache-scope: bazel-${{ github.job }} - name: Resolve app-server/exec-server compatibility releases if: runner.os == 'Linux' @@ -627,6 +343,10 @@ jobs: -- \ //codex-rs/bwrap:bwrap + - name: Report Bazel runner resources + if: always() && runner.os == 'Linux' + run: python3 .github/scripts/bazel_resource_usage.py report + - name: Upload Bazel execution logs if: always() && !cancelled() continue-on-error: true diff --git a/.github/workflows/blob-size-policy.yml b/.github/workflows/blob-size-policy.yml index 43d571e28fbe..7a0a2b7684b4 100644 --- a/.github/workflows/blob-size-policy.yml +++ b/.github/workflows/blob-size-policy.yml @@ -10,9 +10,6 @@ jobs: permissions: contents: read steps: - - uses: openai/fence@e017427978b91977d79a3023842166ab79b5b816 # pin@v0.12.2 - with: - mode: audit - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: fetch-depth: 0 @@ -20,6 +17,8 @@ jobs: - name: Determine comparison range id: range + env: + DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} shell: bash run: | set -euo pipefail @@ -29,6 +28,9 @@ jobs: if [[ "${{ github.event_name }}" == "pull_request" ]]; then base='${{ github.event.pull_request.base.sha }}' head='${{ github.event.pull_request.head.sha }}' + elif [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then + head='${{ github.sha }}' + base="$(git merge-base "origin/$DEFAULT_BRANCH" "$head")" else base='${{ github.event.before }}' head='${{ github.sha }}' diff --git a/.github/workflows/blocking-ci.yml b/.github/workflows/blocking-ci.yml index a85fc782a266..3e3f1c655b58 100644 --- a/.github/workflows/blocking-ci.yml +++ b/.github/workflows/blocking-ci.yml @@ -3,69 +3,61 @@ name: blocking-ci # This is the single entrypoint for checks that block a PR merge. It also runs # after pushes to main so the same check family stays grouped in the Actions UI. on: - pull_request: - paths: - - "codex-rs/**" - - "sdk/**" - - "scripts/**" - - "tools/**" - - "third_party/**" - - ".github/actions/**" - - ".github/scripts/**" - - ".github/workflows/**" - - "Cargo.toml" - - "Cargo.lock" - - "MODULE.bazel" - - "MODULE.bazel.lock" - - ".bazelrc" - - "WORKSPACE*" - - "BUILD*" - - "*.bzl" - - "justfile" - - "package.json" - - "pnpm-lock.yaml" - - "pyproject.toml" - - "uv.lock" + pull_request: {} workflow_dispatch: push: branches: [main] - paths: - - "codex-rs/**" - - "sdk/**" - - "scripts/**" - - "tools/**" - - "third_party/**" - - ".github/actions/**" - - ".github/scripts/**" - - ".github/workflows/**" - - "Cargo.toml" - - "Cargo.lock" - - "MODULE.bazel" - - "MODULE.bazel.lock" - - ".bazelrc" - - "WORKSPACE*" - - "BUILD*" - - "*.bzl" - - "justfile" - - "package.json" - - "pnpm-lock.yaml" - - "pyproject.toml" - - "uv.lock" concurrency: - # A newer commit supersedes every older PR run. This prevents a burst of - # commits from consuming a full matrix for each intermediate revision while - # keeping main pushes serialized for release confidence. - # v3 isolates this PR gate from stuck pre-fix v2 reusable-workflow jobs; - # those old runs may keep macOS/Windows workers alive after cancellation. - group: blocking-ci::${{ github.event.pull_request.number || github.ref }}::scheduler-v3 - cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + group: blocking-ci::${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: ${{ github.ref_name != 'main' }} jobs: - # Keep reusable workflow calls alphabetized. The `required` job below is the + ci-policy: + name: Linux CI policy + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + contents: read + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + - name: Check out the pinned official CI baseline + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + repository: openai/codex + ref: 6ff1e1ca3b30fc8b914720681fcf5fe62e95f856 # rust-v0.166.0 + path: .tmp/upstream-ci + persist-credentials: false + - name: Test CI coverage and baseline guard + run: python3 -m unittest discover -s .github/scripts -p test_upstream_ci.py -v + - name: Validate changed workflow syntax + run: >- + go run github.com/rhysd/actionlint/cmd/actionlint@v1.7.12 + -shellcheck= -pyflakes= + .github/workflows/blocking-ci.yml + .github/workflows/codefx-linux-cargo.yml + .github/workflows/codefx-extended-ci.yml + .github/workflows/sdk.yml + .github/workflows/bazel.yml + .github/workflows/postmerge-ci.yml + .github/workflows/rust-ci.yml + .github/workflows/rust-ci-full.yml + .github/workflows/v8-canary.yml + .github/workflows/codefx-ci-format.yml + - name: Test CI resource and provenance regressions + run: | + python3 -m unittest discover -s .github/scripts -p 'test_codefx_ci.py' -v + python3 -m unittest discover -s scripts/install -p 'test_prepare_sdk_package.py' -v + - name: Verify Linux-only upstream CI wiring + run: python3 .github/scripts/check_upstream_ci.py --upstream .tmp/upstream-ci + + # Keep reusable workflow calls alphabetized. The required job below is the # version-controlled list that the main-branch ruleset should require. bazel: - name: Bazel + name: Bazel compatibility + needs: ci-policy uses: ./.github/workflows/bazel.yml secrets: inherit @@ -79,6 +71,17 @@ jobs: uses: ./.github/workflows/cargo-deny.yml secrets: inherit + codefx-install: + name: Codefx installer safety + needs: ci-policy + uses: ./.github/workflows/codefx-install.yml + secrets: inherit + + codefx-source-smoke: + name: Codefx current source packages + needs: ci-policy + uses: ./.github/workflows/codefx-source-smoke.yml + codespell: name: Codespell uses: ./.github/workflows/codespell.yml @@ -91,16 +94,21 @@ jobs: rust-ci: name: rust-ci + needs: ci-policy + permissions: + contents: read + id-token: write uses: ./.github/workflows/rust-ci.yml secrets: inherit + linux-cargo: + name: Linux Cargo coverage + needs: ci-policy + uses: ./.github/workflows/codefx-linux-cargo.yml + sdk: - name: sdk - # SDK Bazel targets overlap with the main GNU Bazel graph. Start this - # suite after that graph so the shared action cache can be reused while - # still running the SDK tests when the Bazel suite fails. - needs: bazel - if: ${{ always() && !cancelled() }} + name: SDK + needs: [ci-policy, codefx-source-smoke] uses: ./.github/workflows/sdk.yml secrets: inherit @@ -108,11 +116,15 @@ jobs: name: CI required # Without `always()`, GitHub skips this job after a failed dependency and a # required check can appear successful instead of reporting the failure. - if: ${{ always() && !cancelled() }} + if: ${{ always() }} needs: + - ci-policy - bazel + - linux-cargo - blob-size-policy - cargo-deny + - codefx-install + - codefx-source-smoke - codespell - repo-checks - rust-ci diff --git a/.github/workflows/cargo-deny.yml b/.github/workflows/cargo-deny.yml index 0f8ebae902bd..efe8863343de 100644 --- a/.github/workflows/cargo-deny.yml +++ b/.github/workflows/cargo-deny.yml @@ -22,6 +22,9 @@ jobs: - name: Run cargo-deny uses: EmbarkStudios/cargo-deny-action@82eb9f621fbc699dd0918f3ea06864c14cc84246 # v2 + env: + CARGO_HOME: /github/home/cargo-home + CARGO_NET_GIT_FETCH_WITH_CLI: "true" with: rust-version: 1.95.0 manifest-path: ./codex-rs/Cargo.toml diff --git a/.github/workflows/ci-maintenance.yml b/.github/workflows/ci-maintenance.yml new file mode 100644 index 000000000000..dcd1c337f946 --- /dev/null +++ b/.github/workflows/ci-maintenance.yml @@ -0,0 +1,43 @@ +name: Codefx CI storage maintenance +on: + workflow_dispatch: + inputs: + dry_run: + description: Preview deletion candidates without removing anything + type: boolean + required: true + default: true + schedule: + - cron: "17 4 * * 1" + +permissions: + contents: read + +concurrency: + group: codefx-ci-maintenance + cancel-in-progress: false + +jobs: + cleanup: + if: github.repository == 'hitmux/codefx' + runs-on: ubuntu-24.04 + timeout-minutes: 15 + permissions: + contents: read + actions: write + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + - name: Remove only aged disposable CI caches and diagnostic artifacts + env: + GH_TOKEN: ${{ github.token }} + APPLY: ${{ github.event_name == 'schedule' || inputs.dry_run == false }} + shell: bash + run: | + set -euo pipefail + if [[ "$APPLY" == "true" ]]; then + python3 .github/scripts/ci_storage_cleanup.py --apply + else + python3 .github/scripts/ci_storage_cleanup.py + fi diff --git a/.github/workflows/codefx-ci-format.yml b/.github/workflows/codefx-ci-format.yml new file mode 100644 index 000000000000..e77d66e62c71 --- /dev/null +++ b/.github/workflows/codefx-ci-format.yml @@ -0,0 +1,356 @@ +name: Codefx CI formatting suggestions +on: + pull_request: + paths: + - .github/** + - codex-rs/**/Cargo.toml + - codex-rs/Cargo.lock + - codex-rs/v8-poc/** + - vendor/**/Cargo.toml + - scripts/install/*.py + - sdk/typescript/** + workflow_dispatch: + inputs: + http_regressions: + description: Run focused HTTP transport regressions on the selected source + type: boolean + default: false + plugin_regressions: + description: Verify plugin isolation and local plugin compatibility + type: boolean + default: false + runtime_regressions: + description: Diagnose CLI startup and shell snapshot regressions + type: boolean + default: false + runtime_component: + description: Runtime component to verify + type: choice + options: [all, exec, shell, app-server, core, v8, budget, clippy] + default: all + sdk_regressions: + description: Verify SDK child process lifecycle regressions + type: boolean + default: false + provider_regressions: + description: Stress Bazel provider and exec-server discovery suites with competing CPU work + type: boolean + default: false +permissions: + contents: read +jobs: + provider-regressions: + name: Bazel protocol deadline regressions + if: github.event_name == 'workflow_dispatch' && inputs.provider_regressions + runs-on: ubuntu-24.04 + timeout-minutes: 120 + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + - uses: ./.github/actions/prepare-bazel-ci + with: + target: x86_64-unknown-linux-gnu + cache-scope: provider-concurrency + - name: Compile both complete test binaries before execution + run: >- + ./.github/scripts/run-bazel-ci.sh --print-failed-action-summary -- + build -- //codex-rs/model-provider:model-provider-unit-tests-bin + //codex-rs/exec-server:exec-server-capability_discovery-test + - name: Repeat both complete suites with competing CPU work + shell: bash + run: | + set -euo pipefail + load_pids=() + trap 'kill "${load_pids[@]}" 2>/dev/null || true' EXIT + for worker in 1 2 3; do + yes > /dev/null & + load_pids+=("$!") + done + ./.github/scripts/run-bazel-ci.sh --print-failed-test-logs -- \ + test --notest_keep_going --runs_per_test=10 --nocache_test_results -- \ + //codex-rs/model-provider:model-provider-unit-tests \ + //codex-rs/exec-server:exec-server-capability_discovery-test + - name: Report regression resource headroom + if: always() + run: python3 .github/scripts/bazel_resource_usage.py report + - name: Preserve regression diagnostics + if: always() + uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 + with: + name: provider-concurrency-logs + path: ${{ runner.temp }}/bazel-execution-logs + retention-days: 3 + bazel-resources: + name: Bazel resource and installer regressions + strategy: + fail-fast: false + matrix: + runner: [ubuntu-24.04, ubuntu-latest] + runs-on: ${{ matrix.runner }} + timeout-minutes: 15 + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + - uses: ./.github/actions/prepare-bazel-ci + with: + target: x86_64-unknown-linux-gnu + cache-scope: resource-policy + - name: Verify installer retention with the runner's real process tools + run: python3 -m unittest discover -s scripts/install -p test_install_sh.py -v + runtime-regressions: + if: github.event_name == 'workflow_dispatch' && inputs.runtime_regressions + runs-on: ubuntu-24.04 + timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + component: ${{ fromJSON(inputs.runtime_component == 'shell' && '["shell"]' || inputs.runtime_component == 'exec' && '["exec"]' || inputs.runtime_component == 'app-server' && '["app-server"]' || inputs.runtime_component == 'core' && '["core"]' || inputs.runtime_component == 'v8' && '["v8"]' || inputs.runtime_component == 'budget' && '["budget"]' || inputs.runtime_component == 'clippy' && '["clippy"]' || '["exec","shell"]') }} + env: + CARGO_BUILD_JOBS: "2" + CARGO_PROFILE_CI_TEST_DEBUG: "0" + CARGO_INCREMENTAL: "0" + RUST_BACKTRACE: "1" + RUST_LOG: codex_exec_server=warn + RUST_MIN_STACK: "8388608" + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + - uses: ./.github/actions/setup-ci + - uses: ./.github/actions/codefx-linux-voice-sdk + if: matrix.component != 'shell' && matrix.component != 'v8' + - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + with: + components: clippy + - uses: ./.github/actions/setup-rusty-v8 + if: matrix.component != 'shell' + with: + target: x86_64-unknown-linux-gnu + - name: Install sandbox test prerequisites + run: | + sudo apt-get update -o Acquire::Retries=3 + sudo apt-get install -y --no-install-recommends build-essential libcap-dev bubblewrap + - name: Reuse Cargo download inputs + uses: actions/cache@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5.0.4 + with: + path: | + ~/.cargo/registry/index + ~/.cargo/registry/cache + ~/.cargo/git/db + key: cargo-sources-v2-${{ runner.os }}-${{ hashFiles('codex-rs/Cargo.lock', 'codex-rs/rust-toolchain.toml') }} + - uses: taiki-e/install-action@44c6d64aa62cd779e873306675c7a58e86d6d532 # v2.62.49 + with: + tool: cargo-nextest@0.9.103 + - name: Prepare bundled sandbox executable + if: matrix.component != 'v8' + working-directory: codex-rs + run: | + cargo build --locked --profile ci-test --bin bwrap + runtime="$CARGO_TARGET_DIR/ci-test" + echo "CODEX_BWRAP_SHA256=$(sha256sum "$runtime/bwrap" | cut -d ' ' -f 1)" >> "$GITHUB_ENV" + install -Dm755 "$runtime/bwrap" "$runtime/codex-resources/bwrap" + - name: Verify shell snapshot regressions + if: matrix.component == 'shell' + working-directory: codex-rs + run: cargo nextest run --locked --cargo-profile ci-test -p codex-exec-server --no-fail-fast --test-threads 2 --retries 0 -E 'test(shell_snapshot)' + - name: Verify isolated CLI startup + if: matrix.component == 'exec' + working-directory: codex-rs + run: | + cargo build --locked --profile ci-test --bin codex-exec --bin codex-linux-sandbox --bin codex-code-mode-host + export CARGO_BIN_EXE_codex_linux_sandbox="$CARGO_TARGET_DIR/ci-test/codex-linux-sandbox" + cargo nextest run --locked --cargo-profile ci-test -p codex-exec --no-fail-fast --test-threads 2 --retries 0 + - name: Verify account and plugin protocol regressions + if: matrix.component == 'app-server' + working-directory: codex-rs + run: | + cargo build --locked --profile ci-test --bin codex-app-server --bin codex-linux-sandbox --bin codex-code-mode-host --bin test_stdio_server + export CARGO_BIN_EXE_codex_linux_sandbox="$CARGO_TARGET_DIR/ci-test/codex-linux-sandbox" + cargo nextest run --locked --cargo-profile ci-test -p codex-app-server --no-fail-fast --test-threads 2 --retries 0 -E 'test(suite::v2::plugin_) | test(curated_mcp_sync) | test(marketplace_upgrade) | test(plugin_metadata_refresh) | test(marketplace_upgrade_refreshes_hook_runtime) | test(suite::v2::cyber_access_program) | test(recommended_plugins) | test(suite::v2::skills_list) | test(turn_cost_otel)' + - name: Verify core inference and local plugin regressions + if: matrix.component == 'core' + working-directory: codex-rs + run: | + cargo build --locked --profile ci-test --bin codex --bin codex-linux-sandbox --bin codex-exec --bin codex-code-mode-host --bin test_stdio_server + export CARGO_BIN_EXE_codex_linux_sandbox="$CARGO_TARGET_DIR/ci-test/codex-linux-sandbox" + cargo nextest run --locked --cargo-profile ci-test -p codex-core -p codex-config -p codex-v8-poc --no-fail-fast --test-threads 2 --retries 0 -E 'test(compact_program_tests) | test(rollout_budget) | test(bundled_plugin_compatibility_guard) | test(cli_stream) | test(reads_typed_array_contents) | test(prompt_cache_key) | test(suite::scenarios) | package(codex-config)' + for iteration in {1..20}; do + echo "Core scheduling regression iteration $iteration/20" + cargo nextest run --locked --cargo-profile ci-test -p codex-core --test all --test-threads 2 --retries 0 -E 'test(api_key_subagent_inherits_prompt_cache_key_policy) | test(child_completion_wakes_parent_after_final_answer) | test(matched_response_mocks_capture_only_the_selected_thread)' + done + - name: Verify generated binding against the verified native V8 library + if: matrix.component == 'v8' + working-directory: codex-rs + run: cargo nextest run --locked --cargo-profile ci-test -p codex-v8-poc --no-fail-fast --test-threads 2 --retries 0 + - name: Verify shared rollout budget regression + if: matrix.component == 'budget' + working-directory: codex-rs + run: | + cargo build --locked --profile ci-test --bin codex-linux-sandbox + export CARGO_BIN_EXE_codex_linux_sandbox="$CARGO_TARGET_DIR/ci-test/codex-linux-sandbox" + cargo nextest run --locked --cargo-profile ci-test -p codex-core --test all --no-fail-fast --test-threads 2 --retries 0 -E 'test(rollout_budget)' + - name: Verify full workspace Clippy including test targets + if: matrix.component == 'clippy' + working-directory: codex-rs + run: cargo clippy --locked --workspace --all-targets -- -D warnings + plugin-regressions: + if: github.event_name == 'workflow_dispatch' && inputs.plugin_regressions + runs-on: ubuntu-24.04 + timeout-minutes: 30 + env: + CARGO_BUILD_JOBS: "2" + CARGO_PROFILE_DEV_DEBUG: "0" + CARGO_INCREMENTAL: "0" + RUST_BACKTRACE: "1" + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + - name: Reuse Cargo download inputs + uses: actions/cache@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5.0.4 + with: + path: | + ~/.cargo/registry/index + ~/.cargo/registry/cache + ~/.cargo/git/db + key: cargo-sources-v2-${{ runner.os }}-${{ hashFiles('codex-rs/Cargo.lock', 'codex-rs/rust-toolchain.toml') }} + - uses: taiki-e/install-action@44c6d64aa62cd779e873306675c7a58e86d6d532 # v2.62.49 + with: + tool: cargo-nextest@0.9.103 + - name: Verify all feature and plugin library regressions + working-directory: codex-rs + run: cargo nextest run --locked -p codex-features -p codex-core-plugins -p codex-model-provider-info --lib --no-fail-fast --test-threads 2 + http-regressions: + if: github.event_name == 'workflow_dispatch' && inputs.http_regressions + runs-on: ubuntu-24.04 + timeout-minutes: 20 + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + - name: Reuse Cargo download inputs + uses: actions/cache@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5.0.4 + with: + path: | + ~/.cargo/registry/index + ~/.cargo/registry/cache + ~/.cargo/git/db + key: cargo-sources-v2-${{ runner.os }}-${{ hashFiles('codex-rs/Cargo.lock', 'codex-rs/rust-toolchain.toml') }} + - name: Check HTTP transport behavior independently of workspace tests + working-directory: codex-rs + env: + CARGO_BUILD_JOBS: "2" + CARGO_PROFILE_DEV_DEBUG: "0" + RUST_BACKTRACE: "1" + run: cargo test --locked -p codex-http-client --lib -- --test-threads=1 + cargo-suggestions: + name: Cargo lockfile and Rust formatting suggestions + runs-on: ubuntu-24.04 + timeout-minutes: 20 + env: + CARGO_NET_GIT_FETCH_WITH_CLI: "true" + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + with: + components: rustfmt + - name: Produce a minimal lockfile repair and Rust formatting patch + working-directory: codex-rs + shell: bash + run: | + set -euo pipefail + git rev-parse HEAD > "$RUNNER_TEMP/codefx-cargo-source.txt" + # Resolve the existing graph without requesting dependency upgrades. + # Ordinary validation keeps --locked and rejects any worktree drift. + cargo metadata --format-version 1 > "$RUNNER_TEMP/codefx-cargo-metadata.json" + cargo metadata --locked --offline --format-version 1 > /dev/null + cargo fmt --all -- --config imports_granularity=Item + git diff --binary -- . > "$RUNNER_TEMP/codefx-cargo-repair.patch" + git diff --stat + - uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 + with: + name: codefx-cargo-repair + path: | + ${{ runner.temp }}/codefx-cargo-repair.patch + ${{ runner.temp }}/codefx-cargo-source.txt + if-no-files-found: error + retention-days: 3 + suggestions: + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + - uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2 + with: + version: "0.13.5" + - uses: pnpm/action-setup@a8198c4bff370c8506180b035930dea56dbd5288 # v5 + with: + run_install: false + - uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0 + with: + node-version-file: .nvmrc + - uses: facebook/install-dotslash@1e4e7b3e07eaca387acb98f1d4720e0bee8dbb6a # v2 + - name: Prepare formatters from repository locks + run: pnpm install --frozen-lockfile + - name: Verify CI policy regression guards + run: | + python3 -m unittest discover -s .github/scripts -p test_upstream_ci.py -v + python3 -m unittest discover -s .github/scripts -p test_codefx_ci.py -v + - name: Validate active CI workflow syntax + run: >- + go run github.com/rhysd/actionlint/cmd/actionlint@v1.7.12 + -shellcheck= -pyflakes= + .github/workflows/blocking-ci.yml + .github/workflows/bazel.yml + .github/workflows/rust-ci.yml + .github/workflows/rust-ci-full.yml + .github/workflows/v8-canary.yml + .github/workflows/postmerge-ci.yml + .github/workflows/codefx-ci-format.yml + - name: Check out the pinned official CI baseline + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + repository: openai/codex + ref: 6ff1e1ca3b30fc8b914720681fcf5fe62e95f856 # rust-v0.166.0 + path: .tmp/upstream-ci + persist-credentials: false + - name: Verify the official Linux graph before expensive builds + run: python3 .github/scripts/check_upstream_ci.py --upstream .tmp/upstream-ci + - name: Produce formatting patch in CI + shell: bash + run: | + set -euo pipefail + dotslash tools/buildifier -mode=fix -lint=off third_party/v8/BUILD.bazel + uv run --frozen --project scripts ruff format \ + .github/scripts/check_upstream_ci.py \ + .github/scripts/test_upstream_ci.py \ + .github/scripts/verify_cargo_workspace_manifests.py \ + .github/scripts/select_cargo_ci_packages.py \ + .github/scripts/test_codefx_ci.py \ + .github/scripts/verify_bazel_resources.py \ + .github/scripts/bazel_resource_usage.py \ + .github/scripts/check_ci_results.py \ + scripts/install/smoke_source_package.py \ + scripts/install/prepare_sdk_package.py \ + scripts/install/test_prepare_sdk_package.py + uv run --frozen --project scripts ruff format scripts/install/test_install_sh.py + pnpm exec prettier --write .github/workflows/*.yml .github/actions/codefx-linux-runner/action.yml .github/actions/prepare-bazel-ci/action.yml .github/actions/codefx-linux-v8-binding/action.yml .github/actions/setup-rusty-v8/action.yml .github/upstream-ci.json .github/CI_POLICY.md .github/workflows/README.md sdk/typescript/src/exec.ts sdk/typescript/tests/exec.test.ts sdk/typescript/tests/run.test.ts sdk/typescript/tests/testCodex.ts + git diff --binary > "$RUNNER_TEMP/codefx-ci-format.patch" + git diff --stat + - uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 + with: + name: codefx-ci-format + path: ${{ runner.temp }}/codefx-ci-format.patch + if-no-files-found: error + retention-days: 3 + - name: Verify SDK child process lifecycle + if: github.event_name == 'workflow_dispatch' && inputs.sdk_regressions + run: pnpm -r --filter ./sdk/typescript run test --runInBand tests/exec.test.ts diff --git a/.github/workflows/codefx-extended-ci.yml b/.github/workflows/codefx-extended-ci.yml new file mode 100644 index 000000000000..1ca4f7618d52 --- /dev/null +++ b/.github/workflows/codefx-extended-ci.yml @@ -0,0 +1,28 @@ +name: Codefx extended compatibility +on: + workflow_dispatch: + push: + branches: [main] +permissions: + contents: read +concurrency: + group: codefx-extended::${{ github.ref }} + cancel-in-progress: ${{ github.ref_name != 'main' }} +jobs: + bazel: + name: Full Bazel graph + uses: ./.github/workflows/bazel.yml + secrets: inherit + results: + name: Extended compatibility results + if: ${{ always() }} + needs: [bazel] + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + - name: Report extended failures + env: + NEEDS: ${{ toJSON(needs) }} + run: python3 .github/scripts/check_ci_results.py diff --git a/.github/workflows/codefx-install.yml b/.github/workflows/codefx-install.yml index 7a0c675f22da..3468d63dde99 100644 --- a/.github/workflows/codefx-install.yml +++ b/.github/workflows/codefx-install.yml @@ -1,5 +1,6 @@ name: Codefx installer safety on: + workflow_call: workflow_dispatch: push: branches: [main] @@ -10,12 +11,7 @@ permissions: contents: read jobs: installers: - strategy: - fail-fast: false - max-parallel: 2 - matrix: - os: [ubuntu-24.04, windows-2025] - runs-on: ${{ matrix.os }} + runs-on: ubuntu-24.04 timeout-minutes: 15 steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd @@ -23,22 +19,9 @@ jobs: - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 with: { python-version: "3.12" } - name: Shell transaction checks - if: runner.os != 'Windows' shell: bash run: | sh -n scripts/install/install.sh scripts/install/install-codefx.sh python3 -m unittest discover -s scripts/install -p test_install_transactions.py -v - name: Existing Linux regression suite - if: runner.os == 'Linux' run: python3 -m unittest discover -s scripts/install -p test_install_sh.py -v - - name: PowerShell syntax and bootstrap failure checks - shell: pwsh - run: ./scripts/install/test_install_ps1.ps1 - - name: Native Windows transactions on PowerShell 5.1 - if: runner.os == 'Windows' - shell: powershell - run: ./.github/scripts/codefx-windows-standard-user.ps1 -Mode transactions -Engine powershell - - name: Native Windows transactions on PowerShell 7 - if: runner.os == 'Windows' - shell: pwsh - run: ./.github/scripts/codefx-windows-standard-user.ps1 -Mode transactions -Engine pwsh diff --git a/.github/workflows/codefx-linux-cargo.yml b/.github/workflows/codefx-linux-cargo.yml new file mode 100644 index 000000000000..7dced352e99e --- /dev/null +++ b/.github/workflows/codefx-linux-cargo.yml @@ -0,0 +1,122 @@ +name: Codefx Linux Cargo coverage +on: + workflow_call: + workflow_dispatch: +permissions: + contents: read + +jobs: + cargo: + name: GNU ${{ matrix.task }} + runs-on: ubuntu-24.04 + timeout-minutes: 90 + strategy: + fail-fast: false + matrix: + task: [clippy, core, tui, app-server, other-0, other-1, other-2] + env: + CARGO_INCREMENTAL: "0" + CARGO_PROFILE_DEV_DEBUG: "0" + CARGO_PROFILE_CI_TEST_DEBUG: "0" + TARGET: x86_64-unknown-linux-gnu + RUST_BACKTRACE: "1" + RUST_LOG: codex_exec_server=warn + RUST_MIN_STACK: "8388608" + defaults: + run: + working-directory: codex-rs + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + - uses: ./.github/actions/setup-ci + - uses: ./.github/actions/codefx-linux-voice-sdk + - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + with: + targets: x86_64-unknown-linux-gnu + components: clippy + - name: Install Linux test dependencies + run: | + sudo apt-get update -o Acquire::Retries=3 + sudo apt-get install -y --no-install-recommends build-essential libcap-dev libasound2-dev bubblewrap + - uses: ./.github/actions/setup-rusty-v8 + with: + target: x86_64-unknown-linux-gnu + - name: Cache Cargo download inputs + uses: actions/cache@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5.0.4 + with: + path: | + ~/.cargo/registry/index + ~/.cargo/registry/cache + ~/.cargo/git/db + key: cargo-sources-v2-${{ runner.os }}-${{ hashFiles('codex-rs/Cargo.lock', 'codex-rs/rust-toolchain.toml') }} + - uses: taiki-e/install-action@44c6d64aa62cd779e873306675c7a58e86d6d532 # v2.62.49 + with: + tool: cargo-nextest@0.9.103 + - name: Resolve compatibility releases + env: + GH_TOKEN: ${{ github.token }} + run: | + releases="$(python3 ../.github/scripts/resolve_exec_server_releases.py)" + echo "CODEX_COMPAT_RELEASES=$releases" >> "$GITHUB_ENV" + - name: Clippy including test targets + if: matrix.task == 'clippy' + run: cargo clippy --locked --workspace --all-targets --target "$TARGET" -- -D warnings + - name: Select workspace packages before compilation + if: matrix.task != 'clippy' + env: + SHARD: ${{ matrix.task }} + run: | + set -euo pipefail + cargo metadata --locked --no-deps --format-version 1 | + python3 ../.github/scripts/select_cargo_ci_packages.py --shard "$SHARD" > "$RUNNER_TEMP/cargo-packages" + - name: Build workspace runtime executables + if: matrix.task != 'clippy' + run: | + cargo build --locked --profile ci-test --target "$TARGET" --bin bwrap + runtime="$CARGO_TARGET_DIR/$TARGET/ci-test" + export CODEX_BWRAP_SHA256="$(sha256sum "$runtime/bwrap" | cut -d ' ' -f 1)" + echo "CODEX_BWRAP_SHA256=$CODEX_BWRAP_SHA256" >> "$GITHUB_ENV" + cargo build --locked --profile ci-test --target "$TARGET" --workspace --bins + install -Dm755 "$runtime/bwrap" "$runtime/codex-resources/bwrap" + echo "CARGO_BIN_EXE_bwrap=$runtime/bwrap" >> "$GITHUB_ENV" + helper="$CARGO_TARGET_DIR/$TARGET/ci-test/codex-linux-sandbox" + echo "CARGO_BIN_EXE_codex-linux-sandbox=$helper" >> "$GITHUB_ENV" + echo "CARGO_BIN_EXE_codex_linux_sandbox=$helper" >> "$GITHUB_ENV" + - name: Run every selected package test + if: matrix.task != 'clippy' + env: + INSTA_UPDATE: new + run: | + set -euo pipefail + packages=() + while IFS= read -r package; do + packages+=(-p "$package") + done < "$RUNNER_TEMP/cargo-packages" + test "${#packages[@]}" -gt 0 + cargo nextest run --locked --target "$TARGET" --cargo-profile ci-test --no-fail-fast --test-threads 2 "${packages[@]}" + - name: Upload snapshot candidates + if: failure() && matrix.task != 'clippy' + uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 + with: + name: codefx-snapshot-candidates-${{ matrix.task }} + path: codex-rs/**/*.snap.new + if-no-files-found: ignore + retention-days: 3 + - name: Record disk usage + if: always() + run: | + df -h "$GITHUB_WORKSPACE" + du -sh "$CARGO_TARGET_DIR" "$HOME/.cache/bazel-disk-cache" "$BAZEL_OUTPUT_BASE" 2>/dev/null || true + - name: Upload test reports + if: always() && matrix.task != 'clippy' + uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 + with: + name: codefx-cargo-junit-${{ matrix.task }} + path: ${{ env.CARGO_TARGET_DIR }}/nextest/default/junit.xml + include-hidden-files: true + if-no-files-found: warn + retention-days: 3 + - name: Check for a clean worktree + if: always() && !cancelled() + uses: ./.github/actions/check-clean-worktree diff --git a/.github/workflows/codefx-native-package.yml b/.github/workflows/codefx-native-package.yml index c4311491db49..dba3b813983b 100644 --- a/.github/workflows/codefx-native-package.yml +++ b/.github/workflows/codefx-native-package.yml @@ -40,7 +40,7 @@ jobs: set -euo pipefail [[ "$RELEASE_TAG" =~ ^rust-v[0-9]+\.[0-9]+\.[0-9]+$ ]] case "$TARGET" in - x86_64-unknown-linux-musl|aarch64-unknown-linux-musl|x86_64-pc-windows-msvc|aarch64-pc-windows-msvc) ;; + x86_64-unknown-linux-musl) ;; *) echo "Unsupported Codefx release target: $TARGET" >&2; exit 1 ;; esac cp scripts/install/release_package.py "$RUNNER_TEMP/codefx-release-package.py" @@ -83,15 +83,42 @@ jobs: with: toolchain: "1.99.1" targets: ${{ inputs.target }} - - uses: actions/cache@668228422ae6a00e4ad889ee87cd7109ec5666a7 + - name: Restore shared Linux Cargo sources if: steps.prepare.outputs.reuse != 'true' + uses: actions/cache@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5.0.4 with: path: | ~/.cargo/registry ~/.cargo/git - codex-rs/target - key: codefx-native-${{ inputs.target }}-v1-${{ hashFiles('codex-rs/Cargo.lock', 'codex-rs/rust-toolchain.toml') }} - restore-keys: codefx-native-${{ inputs.target }}-v1- + # Registry and git sources are architecture-neutral; avoid a second copy. + key: codefx-native-deps-linux-v2-${{ hashFiles('codex-rs/Cargo.lock', 'codex-rs/rust-toolchain.toml') }} + restore-keys: | + codefx-native-deps-linux-v2- + + - name: Install sccache + if: steps.prepare.outputs.reuse != 'true' + uses: taiki-e/install-action@44c6d64aa62cd779e873306675c7a58e86d6d532 # v2.62.49 + with: + tool: sccache + version: 0.8.2 + + - name: Restore bounded Linux native compilation cache + if: steps.prepare.outputs.reuse != 'true' + uses: actions/cache@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5.0.4 + with: + path: ${{ runner.temp }}/codefx-native-sccache + key: codefx-native-sccache-v2-${{ inputs.target }}-${{ hashFiles('codex-rs/Cargo.lock', 'codex-rs/rust-toolchain.toml') }}-${{ github.sha }} + restore-keys: | + codefx-native-sccache-v2-${{ inputs.target }}-${{ hashFiles('codex-rs/Cargo.lock', 'codex-rs/rust-toolchain.toml') }}- + codefx-native-sccache-v2-${{ inputs.target }}- + + - name: Enable bounded sccache + if: steps.prepare.outputs.reuse != 'true' + run: | + mkdir -p "${RUNNER_TEMP}/codefx-native-sccache" + echo "RUSTC_WRAPPER=sccache" >> "${GITHUB_ENV}" + echo "SCCACHE_DIR=${RUNNER_TEMP}/codefx-native-sccache" >> "${GITHUB_ENV}" + echo "SCCACHE_CACHE_SIZE=1G" >> "${GITHUB_ENV}" - uses: mlugg/setup-zig@d1434d08867e3ee9daa34448df10607b98908d29 if: runner.os == 'Linux' && steps.prepare.outputs.reuse != 'true' with: { version: 0.14.0, use-cache: false } @@ -102,10 +129,6 @@ jobs: if: steps.prepare.outputs.reuse != 'true' with: target: ${{ inputs.target }} - - uses: ./.github/actions/setup-msvc-env - if: runner.os == 'Windows' && steps.prepare.outputs.reuse != 'true' - with: - target: ${{ inputs.target }} - name: Build native binaries if: steps.prepare.outputs.reuse != 'true' working-directory: codex-rs @@ -116,12 +139,14 @@ jobs: cargo build --locked --release --target "$TARGET" --bin bwrap strip --strip-debug --strip-unneeded "target/$TARGET/release/bwrap" export CODEX_BWRAP_SHA256="$(sha256sum "target/$TARGET/release/bwrap" | cut -d ' ' -f 1)" - elif [[ "$TARGET" == *windows* ]]; then - export LIBSQLITE3_FLAGS=SQLITE_DISABLE_INTRINSIC - bins+=(--bin codex-command-runner --bin codex-windows-sandbox-setup) fi export STABLE_GIT_COMMIT="$(git rev-parse HEAD)" cargo build --locked --release --target "$TARGET" "${bins[@]}" + - name: Report Linux native compiler cache efficiency + if: ${{ always() && !cancelled() && steps.prepare.outputs.reuse != 'true' }} + continue-on-error: true + run: sccache --show-stats + - name: Assemble platform package if: steps.prepare.outputs.reuse != 'true' run: | diff --git a/.github/workflows/codefx-native-smoke.yml b/.github/workflows/codefx-native-smoke.yml index 0526d654c560..201de627f6ae 100644 --- a/.github/workflows/codefx-native-smoke.yml +++ b/.github/workflows/codefx-native-smoke.yml @@ -27,8 +27,7 @@ jobs: import json, os, re, subprocess tag = os.environ['RELEASE_TAG'] assert re.fullmatch(r'rust-v[0-9]+\.[0-9]+\.[0-9]+', tag) - pairs = [('ubuntu-24.04','x86_64-unknown-linux-musl'), ('ubuntu-24.04-arm','aarch64-unknown-linux-musl'), - ('windows-2025','x86_64-pc-windows-msvc'), ('windows-11-arm','aarch64-pc-windows-msvc')] + pairs = [('ubuntu-24.04','x86_64-unknown-linux-musl')] requested = os.environ['REQUESTED_TARGETS'] if requested == 'available': release = json.loads(subprocess.check_output(['gh','api',f'repos/hitmux/codefx/releases/tags/{tag}'])) @@ -59,7 +58,6 @@ jobs: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd with: { persist-credentials: false } - name: Install published package through the public bootstrap - if: runner.os != 'Windows' shell: bash run: | set -euo pipefail @@ -89,7 +87,3 @@ jobs: daemon_version="$(sed -n 's/.*"appServerVersion"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$HOME/daemon-after.json")" [[ "$daemon_version" == "$version" ]] test ! -d "$CODEX_HOME/packages/standalone/.transaction" - - name: Install published package through the Windows bootstrap as a standard user - if: runner.os == 'Windows' - shell: pwsh - run: ./.github/scripts/codefx-windows-standard-user.ps1 -Mode smoke -Engine pwsh diff --git a/.github/workflows/codefx-platform-release.yml b/.github/workflows/codefx-platform-release.yml index 8a1aff03d301..7cb19a43d888 100644 --- a/.github/workflows/codefx-platform-release.yml +++ b/.github/workflows/codefx-platform-release.yml @@ -1,4 +1,4 @@ -name: Codefx Linux/Windows packages +name: Codefx Linux packages on: workflow_call: inputs: @@ -51,9 +51,6 @@ jobs: matrix: include: - { runner: ubuntu-24.04, target: x86_64-unknown-linux-musl } - - { runner: windows-2025, target: x86_64-pc-windows-msvc } - - { runner: ubuntu-24.04-arm, target: aarch64-unknown-linux-musl } - - { runner: windows-11-arm, target: aarch64-pc-windows-msvc } uses: ./.github/workflows/codefx-native-package.yml with: tag: ${{ inputs.tag }} @@ -74,7 +71,7 @@ jobs: set -euo pipefail mkdir dist cd dist - for target in x86_64-unknown-linux-musl aarch64-unknown-linux-musl x86_64-pc-windows-msvc aarch64-pc-windows-msvc; do + for target in x86_64-unknown-linux-musl; do gh release download "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" --pattern "$target.sha256" file="codex-package-$target.tar.gz" digest="$(gh api "repos/$GITHUB_REPOSITORY/releases/tags/$RELEASE_TAG" --jq '.assets[] | [.name,.digest] | @tsv' | awk -F '\t' -v name="$file" '$1 == name {print $2}')" diff --git a/.github/workflows/codefx-publish-verified.yml b/.github/workflows/codefx-publish-verified.yml index 1b92ffa0fdf8..e9f38e42db17 100644 --- a/.github/workflows/codefx-publish-verified.yml +++ b/.github/workflows/codefx-publish-verified.yml @@ -7,13 +7,7 @@ on: target: type: choice required: true - options: - [ - x86_64-pc-windows-msvc, - aarch64-pc-windows-msvc, - x86_64-unknown-linux-musl, - aarch64-unknown-linux-musl, - ] + options: [x86_64-unknown-linux-musl] permissions: contents: write actions: write @@ -38,6 +32,7 @@ jobs: set -euo pipefail [[ "$SOURCE_RUN" =~ ^[0-9]+$ ]] [[ "$RELEASE_TAG" =~ ^rust-v[0-9]+\.[0-9]+\.[0-9]+$ ]] + [[ "$TARGET" == x86_64-unknown-linux-musl ]] gh api "repos/$GITHUB_REPOSITORY/actions/runs/$SOURCE_RUN" > "$RUNNER_TEMP/source-run.json" gh api "repos/$GITHUB_REPOSITORY/actions/runs/$SOURCE_RUN/jobs?per_page=100" > "$RUNNER_TEMP/source-jobs.json" gh api "repos/$GITHUB_REPOSITORY/actions/runs/$SOURCE_RUN/artifacts?per_page=100" > "$RUNNER_TEMP/source-artifacts.json" diff --git a/.github/workflows/codefx-rust-v0.166-release.yml b/.github/workflows/codefx-rust-v0.166-release.yml index 4cd4c7590646..df5a23b3a81e 100644 --- a/.github/workflows/codefx-rust-v0.166-release.yml +++ b/.github/workflows/codefx-rust-v0.166-release.yml @@ -113,7 +113,7 @@ jobs: fi if ! gh release view "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" --json tagName >/dev/null 2>&1; then gh release create "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" --target "$SOURCE_SHA" \ - --title "Codefx CLI 0.166.0" --notes "Verified Codefx 0.166.0 release candidate. Linux/Windows packages only; promoted after native checks." \ + --title "Codefx CLI 0.166.0" --notes "Verified Codefx 0.166.0 release candidate. Linux packages only; promoted after native checks." \ --prerelease fi gh release view "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" --json tagName,isDraft,isPrerelease @@ -140,7 +140,7 @@ jobs: RELEASE_TAG: rust-v0.166.0 SOURCE_SHA: ${{ needs.gate.outputs.source_sha }} steps: - - name: Verify Linux/Windows digests, provenance and installers before stable publication + - name: Verify Linux amd64 digests, provenance and installers before stable publication shell: bash run: | set -euo pipefail @@ -152,8 +152,7 @@ jobs: assert data["tag_name"] == os.environ["RELEASE_TAG"] assert data["prerelease"] and not data["draft"], "release must be an accessible prerelease during native smoke" assets={a["name"]:a for a in data["assets"]} - targets=("x86_64-unknown-linux-musl", "aarch64-unknown-linux-musl", - "x86_64-pc-windows-msvc", "aarch64-pc-windows-msvc") + targets=("x86_64-unknown-linux-musl",) required={"codex-package_SHA256SUMS"} for target in targets: required.update((f"codex-package-{target}.tar.gz", f"{target}.sha256", @@ -166,8 +165,8 @@ jobs: asset=assets[name] assert asset["state"] == "uploaded", f"unfinished release asset: {name}" assert re.fullmatch(r"sha256:[0-9a-f]{64}", asset.get("digest") or ""), f"unverified digest: {name}" - assert not any("apple-darwin" in name or name.endswith(".dmg") for name in assets), "macOS release asset present" - print("All four platform packages, per-target SHA256/provenance, manifest and pinned installers verified.") + assert not any("aarch64" in name or "arm64" in name or "apple-darwin" in name or "windows" in name or name.endswith(".dmg") for name in assets), "unsupported platform release asset present" + print("Linux amd64 package, SHA256/provenance, manifest and pinned installers verified.") PY gh release edit "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" --prerelease=false --latest gh release view "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" --json isDraft,isPrerelease,tagName diff --git a/.github/workflows/codefx-source-smoke.yml b/.github/workflows/codefx-source-smoke.yml new file mode 100644 index 000000000000..e28584cd7adc --- /dev/null +++ b/.github/workflows/codefx-source-smoke.yml @@ -0,0 +1,110 @@ +name: Codefx current source packages +on: + workflow_call: + workflow_dispatch: +permissions: + contents: read +jobs: + native: + name: Current source — ${{ matrix.target }} + runs-on: ${{ matrix.runner }} + timeout-minutes: 180 + strategy: + fail-fast: false + matrix: + include: + - runner: ubuntu-24.04 + target: x86_64-unknown-linux-musl + env: + TARGET: ${{ matrix.target }} + CARGO_PROFILE_RELEASE_DEBUG: "0" + CARGO_PROFILE_RELEASE_LTO: "false" + CARGO_PROFILE_RELEASE_CODEGEN_UNITS: "16" + AWS_LC_SYS_NO_JITTER_ENTROPY: "1" + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + - uses: ./.github/actions/setup-ci + - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + with: + targets: ${{ matrix.target }} + - name: Cache Cargo sources + uses: actions/cache@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5.0.4 + with: + path: | + ~/.cargo/registry/index + ~/.cargo/registry/cache + ~/.cargo/git/db + key: cargo-sources-v2-${{ runner.os }}-${{ hashFiles('codex-rs/Cargo.lock', 'codex-rs/rust-toolchain.toml') }} + - uses: mlugg/setup-zig@d1434d08867e3ee9daa34448df10607b98908d29 # v2.2.1 + with: + version: 0.14.0 + use-cache: false + - name: Prepare native musl dependencies + run: bash .github/scripts/install-musl-build-tools.sh + - uses: ./.github/actions/setup-rusty-v8 + with: + target: ${{ matrix.target }} + - name: Build this exact source revision + working-directory: codex-rs + shell: bash + run: | + set -euo pipefail + export STABLE_GIT_COMMIT="$(git rev-parse HEAD)" + cargo build --locked --release --target "$TARGET" --bin bwrap + sandbox="$CARGO_TARGET_DIR/$TARGET/release/bwrap" + strip --strip-debug --strip-unneeded "$sandbox" + export CODEX_BWRAP_SHA256="$(sha256sum "$sandbox" | cut -d ' ' -f 1)" + cargo build --locked --release --target "$TARGET" \ + --bin codex --bin codex-code-mode-host --bin codex-exec-server + - name: Verify V8 ABI on the native musl runner + working-directory: codex-rs + run: | + cargo test --locked --release --target "$TARGET" -p codex-v8-poc --lib \ + -- --test-threads=1 + - name: Confirm native architecture and musl linkage + shell: bash + run: | + set -euo pipefail + case "$TARGET" in + x86_64-unknown-linux-musl) machine='Advanced Micro Devices X86-64' ;; + *) exit 1 ;; + esac + for name in codex codex-code-mode-host codex-exec-server bwrap; do + binary="$CARGO_TARGET_DIR/$TARGET/release/$name" + readelf -h "$binary" | grep -F "$machine" + if readelf -l "$binary" | grep -q 'ld-linux'; then + echo "Unexpected glibc interpreter in $name" >&2 + exit 1 + fi + done + - name: Record build disk usage + if: always() + run: | + df -h "$GITHUB_WORKSPACE" + du -sh "$CARGO_TARGET_DIR" "$BAZEL_OUTPUT_BASE" 2>/dev/null || true + - name: Assemble current source package + shell: bash + run: | + set -euo pipefail + bash .github/scripts/build-codex-package-archive.sh \ + --target "$TARGET" --bundle primary \ + --entrypoint-dir "$CARGO_TARGET_DIR/$TARGET/release" \ + --archive-dir "$RUNNER_TEMP/codefx-source-dist" + - name: Verify native package and real installation + run: python3 scripts/install/smoke_source_package.py --target "$TARGET" --directory "$RUNNER_TEMP/codefx-source-dist" + - name: Remove generated Zig cache + if: always() && !cancelled() + run: rm -rf .zig-cache + - name: Check for a clean worktree + if: always() && !cancelled() + uses: ./.github/actions/check-clean-worktree + - name: Upload verified current source packages + uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 + with: + name: codefx-source-${{ matrix.target }} + path: ${{ runner.temp }}/codefx-source-dist/* + if-no-files-found: error + compression-level: 0 + retention-days: 3 diff --git a/.github/workflows/postmerge-ci.yml b/.github/workflows/postmerge-ci.yml index 02df3e9f88ea..b36d2ad54372 100644 --- a/.github/workflows/postmerge-ci.yml +++ b/.github/workflows/postmerge-ci.yml @@ -3,6 +3,7 @@ name: postmerge-ci # This is the single entrypoint for main-only CI that is intentionally outside # the merge-blocking suite. It keeps the broader postmerge signal in one run. on: + workflow_dispatch: push: branches: [main] @@ -16,6 +17,9 @@ jobs: v8-canary: name: v8-canary + permissions: + contents: read + actions: read uses: ./.github/workflows/v8-canary.yml secrets: inherit @@ -24,7 +28,7 @@ jobs: needs: - rust-ci-full - v8-canary - if: ${{ always() && !cancelled() }} + if: ${{ always() }} runs-on: ubuntu-24.04 steps: # Postmerge runs use the pushed main commit, so this helper always comes diff --git a/.github/workflows/r2-release.yml b/.github/workflows/r2-release.yml deleted file mode 100644 index d1783bb2d39f..000000000000 --- a/.github/workflows/r2-release.yml +++ /dev/null @@ -1,59 +0,0 @@ -name: publish-r2-release - -on: - workflow_call: - inputs: - tag: - required: true - type: string - make_latest: - required: true - type: boolean - prerelease: - required: true - type: boolean - stage: - required: true - type: string - -permissions: {} - -jobs: - publish: - runs-on: ubuntu-latest - timeout-minutes: 60 - environment: codex-r2-publisher - permissions: - contents: read - - steps: - - name: Checkout - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - persist-credentials: false - - - name: Publish release assets and metadata to R2 - # R2 exposes an S3-compatible API, so the AWS CLI reads AWS-named variables. - env: - AWS_ACCESS_KEY_ID: ${{ secrets.CODEX_R2_ACCESS_KEY_ID }} - AWS_SECRET_ACCESS_KEY: ${{ secrets.CODEX_R2_SECRET_ACCESS_KEY }} - AWS_ENDPOINT_URL: ${{ vars.CODEX_R2_ENDPOINT_URL }} - AWS_REGION: ${{ vars.CODEX_R2_REGION }} - AWS_RETRY_MODE: standard - AWS_MAX_ATTEMPTS: "6" - GH_TOKEN: ${{ github.token }} - RELEASE_TAG: ${{ inputs.tag }} - RELEASE_MAKE_LATEST: ${{ inputs.make_latest }} - RELEASE_PRERELEASE: ${{ inputs.prerelease }} - RELEASE_STAGE: ${{ inputs.stage }} - PYTHONPATH: .github/scripts - run: | - set -euo pipefail - # The publisher parallelizes objects; serialize parts within each object to avoid R2 throttling. - aws configure set default.s3.preferred_transfer_client classic - aws configure set default.s3.max_concurrent_requests 1 - python3 .github/scripts/publish_r2_release.py \ - --tag "${RELEASE_TAG}" \ - --make-latest "${RELEASE_MAKE_LATEST}" \ - --prerelease "${RELEASE_PRERELEASE}" \ - --stage "${RELEASE_STAGE}" diff --git a/.github/workflows/repo-checks.yml b/.github/workflows/repo-checks.yml index a4e975d2ac43..8938ea62e8ae 100644 --- a/.github/workflows/repo-checks.yml +++ b/.github/workflows/repo-checks.yml @@ -46,6 +46,9 @@ jobs: - name: Test standalone installer run: python3 -m unittest discover -s scripts/install -p 'test_*.py' + - name: Test macOS signing and notarization + run: python3 -m unittest discover -s .github/scripts/macos-signing -p 'test_*.py' + - name: Setup pnpm uses: pnpm/action-setup@a8198c4bff370c8506180b035930dea56dbd5288 # v5 with: diff --git a/.github/workflows/rust-ci-full-nextest-platform.yml b/.github/workflows/rust-ci-full-nextest-platform.yml index e16fce2b91f5..3952e6405dc7 100644 --- a/.github/workflows/rust-ci-full-nextest-platform.yml +++ b/.github/workflows/rust-ci-full-nextest-platform.yml @@ -52,7 +52,7 @@ jobs: archive: name: Build nextest archive runs-on: ${{ inputs.archive_runner_group != '' && fromJSON(format('{{"group":"{0}","labels":"{1}"}}', inputs.archive_runner_group, inputs.archive_runner_labels)) || inputs.archive_runner != '' && inputs.archive_runner || inputs.runner_group != '' && fromJSON(format('{{"group":"{0}","labels":"{1}"}}', inputs.runner_group, inputs.runner_labels)) || inputs.runner }} - timeout-minutes: 180 + timeout-minutes: 60 defaults: run: working-directory: codex-rs @@ -65,7 +65,9 @@ jobs: CODEX_CI_PROFILE: ${{ inputs.profile }} CODEX_CI_TARGET: ${{ inputs.target }} CARGO_INCREMENTAL: "0" - SCCACHE_CACHE_SIZE: 10G + SCCACHE_CACHE_SIZE: 2G + CARGO_PROFILE_CI_TEST_DEBUG: "0" + CARGO_PROFILE_CI_TEST_INCREMENTAL: "false" NEXTEST_ARCHIVE_FILE: nextest-${{ inputs.artifact_id }}.tar.zst TEST_HELPERS_ARTIFACT: nextest-test-helpers-${{ inputs.artifact_id }} steps: @@ -74,6 +76,9 @@ jobs: persist-credentials: false - uses: ./.github/actions/setup-ci + - name: Prepare pinned GNU voice SDK + if: runner.os == 'Linux' && endsWith(inputs.target, '-linux-gnu') + uses: ./.github/actions/codefx-linux-voice-sdk - name: Install Linux build dependencies if: ${{ runner.os == 'Linux' }} @@ -95,6 +100,12 @@ jobs: with: target: ${{ inputs.target }} + - name: Configure rusty_v8 artifact overrides and verify checksums + if: runner.os == 'Linux' + uses: ./.github/actions/setup-rusty-v8 + with: + target: ${{ inputs.target }} + - name: Compute lockfile hash id: lockhash shell: bash @@ -108,20 +119,18 @@ jobs: uses: actions/cache/restore@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5.0.4 with: path: | - ~/.cargo/bin/ ~/.cargo/registry/index/ ~/.cargo/registry/cache/ ~/.cargo/git/db/ - key: cargo-home-${{ env.ARCHIVE_CACHE_RUNNER }}-${{ inputs.target }}-${{ inputs.profile }}-${{ steps.lockhash.outputs.hash }}-${{ steps.lockhash.outputs.toolchain_hash }} + key: cargo-sources-v2-${{ runner.os }}-${{ steps.lockhash.outputs.hash }}-${{ steps.lockhash.outputs.toolchain_hash }} restore-keys: | - cargo-home-${{ env.ARCHIVE_CACHE_RUNNER }}-${{ inputs.target }}-${{ inputs.profile }}- + cargo-sources-v2-${{ runner.os }}- - name: Install sccache if: ${{ env.USE_SCCACHE == 'true' }} uses: taiki-e/install-action@44c6d64aa62cd779e873306675c7a58e86d6d532 # v2.62.49 with: - tool: sccache - version: 0.7.5 + tool: sccache@0.12.0 - name: Configure sccache backend if: ${{ env.USE_SCCACHE == 'true' }} @@ -162,8 +171,22 @@ jobs: - uses: taiki-e/install-action@44c6d64aa62cd779e873306675c7a58e86d6d532 # v2.62.49 with: - tool: nextest - version: 0.9.103 + tool: cargo-nextest@0.9.103 + + - name: Prepare Linux runtime payload and compatibility inputs + if: runner.os == 'Linux' + env: + GH_TOKEN: ${{ github.token }} + shell: bash + run: | + set -euo pipefail + releases="$(python3 ../.github/scripts/resolve_exec_server_releases.py)" + echo "CODEX_COMPAT_RELEASES=$releases" >> "$GITHUB_ENV" + cargo build --locked --target "$CODEX_CI_TARGET" --profile "$CODEX_CI_PROFILE" --bin bwrap + runtime="$CARGO_TARGET_DIR/$CODEX_CI_TARGET/$CODEX_CI_PROFILE" + digest="$(sha256sum "$runtime/bwrap" | cut -d ' ' -f 1)" + echo "CODEX_BWRAP_SHA256=$digest" >> "$GITHUB_ENV" + install -Dm755 "$runtime/bwrap" "$runtime/codex-resources/bwrap" - name: Build nextest archive shell: bash @@ -192,6 +215,8 @@ jobs: -p codex-linux-sandbox \ --bin codex-linux-sandbox cp "${CARGO_TARGET_DIR}/${CODEX_CI_TARGET}/${CODEX_CI_PROFILE}/codex-linux-sandbox" "${helper_dir}/" + cp "${CARGO_TARGET_DIR}/${CODEX_CI_TARGET}/${CODEX_CI_PROFILE}/bwrap" "${helper_dir}/" + printf '%s bwrap\n' "$CODEX_BWRAP_SHA256" > "${helper_dir}/bwrap.sha256" else cargo build \ --target "${CODEX_CI_TARGET}" \ @@ -234,11 +259,10 @@ jobs: uses: actions/cache/save@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5.0.4 with: path: | - ~/.cargo/bin/ ~/.cargo/registry/index/ ~/.cargo/registry/cache/ ~/.cargo/git/db/ - key: cargo-home-${{ env.ARCHIVE_CACHE_RUNNER }}-${{ inputs.target }}-${{ inputs.profile }}-${{ steps.lockhash.outputs.hash }}-${{ steps.lockhash.outputs.toolchain_hash }} + key: cargo-sources-v2-${{ runner.os }}-${{ steps.lockhash.outputs.hash }}-${{ steps.lockhash.outputs.toolchain_hash }} - name: Save sccache cache (fallback) if: always() && !cancelled() && env.USE_SCCACHE == 'true' && env.SCCACHE_GHA_ENABLED != 'true' @@ -269,7 +293,7 @@ jobs: name: Tests shard ${{ matrix.shard }}/4 needs: archive runs-on: ${{ inputs.runner_group != '' && fromJSON(format('{{"group":"{0}","labels":"{1}"}}', inputs.runner_group, inputs.runner_labels)) || inputs.runner }} - timeout-minutes: 180 + timeout-minutes: 60 defaults: run: working-directory: codex-rs @@ -289,6 +313,9 @@ jobs: persist-credentials: false - uses: ./.github/actions/setup-ci + - name: Prepare pinned GNU voice SDK + if: runner.os == 'Linux' && endsWith(inputs.target, '-linux-gnu') + uses: ./.github/actions/codefx-linux-voice-sdk - name: Install Linux build dependencies if: ${{ runner.os == 'Linux' }} @@ -306,8 +333,7 @@ jobs: - uses: taiki-e/install-action@44c6d64aa62cd779e873306675c7a58e86d6d532 # v2.62.49 with: - tool: nextest - version: 0.9.103 + tool: cargo-nextest@0.9.103 - name: Set up remote test env (Docker) if: ${{ runner.os == 'Linux' && inputs.remote_env }} @@ -334,6 +360,15 @@ jobs: name: ${{ env.TEST_HELPERS_ARTIFACT }} path: ${{ runner.temp }}/${{ env.TEST_HELPERS_ARTIFACT }} + - name: Resolve Linux compatibility test inputs + if: runner.os == 'Linux' + env: + GH_TOKEN: ${{ github.token }} + shell: bash + run: | + releases="$(python3 ../.github/scripts/resolve_exec_server_releases.py)" + echo "CODEX_COMPAT_RELEASES=$releases" >> "$GITHUB_ENV" + - name: tests id: test shell: bash @@ -353,6 +388,9 @@ jobs: mkdir -p "${helper_target_dir}" cp "${helper_dir}/codex-linux-sandbox" "${helper_target_dir}/" chmod +x "${helper_target_dir}/codex-linux-sandbox" + (cd "$helper_dir" && sha256sum --check bwrap.sha256) + install -Dm755 "$helper_dir/bwrap" "$helper_target_dir/bwrap" + install -Dm755 "$helper_dir/bwrap" "$helper_target_dir/codex-resources/bwrap" elif [[ "${RUNNER_OS}" == "Windows" ]]; then helper_dir="${RUNNER_TEMP}/${TEST_HELPERS_ARTIFACT}" helper_target_dir="${CARGO_TARGET_DIR}/${CODEX_CI_TARGET}/${CODEX_CI_PROFILE}" @@ -379,6 +417,7 @@ jobs: env "CARGO_BIN_EXE_codex-linux-sandbox=${sandbox_helper}" "CARGO_BIN_EXE_codex_linux_sandbox=${sandbox_helper}" + "CARGO_BIN_EXE_bwrap=${helper_target_dir}/bwrap" cargo nextest "${nextest_args[@]}" ) elif [[ "${RUNNER_OS}" == "Windows" ]]; then diff --git a/.github/workflows/rust-ci-full.yml b/.github/workflows/rust-ci-full.yml index 82b8719e9152..8b8965547f34 100644 --- a/.github/workflows/rust-ci-full.yml +++ b/.github/workflows/rust-ci-full.yml @@ -51,8 +51,8 @@ jobs: name: Argument comment lint package runs-on: ubuntu-24.04 env: - CARGO_DYLINT_VERSION: 6.3.2 - DYLINT_LINK_VERSION: 6.3.2 + CARGO_DYLINT_VERSION: 6.1.0 + DYLINT_LINK_VERSION: 6.1.0 steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: @@ -91,8 +91,8 @@ jobs: argument_comment_lint_prebuilt: name: Argument comment lint - ${{ matrix.name }} - runs-on: ${{ matrix.runs_on || matrix.runner }} - timeout-minutes: 180 + runs-on: ${{ matrix.runner }} + timeout-minutes: 360 environment: name: bazel deployment: false @@ -102,8 +102,6 @@ jobs: include: - name: Linux runner: ubuntu-24.04 - - name: Windows - runner: windows-2025 steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: @@ -117,14 +115,14 @@ jobs: # --- CI to validate on different os/targets -------------------------------- lint_build: name: Lint/Build — ${{ matrix.runner }} - ${{ matrix.target }}${{ matrix.profile == 'release' && ' (release)' || '' }} - runs-on: ${{ matrix.runs_on || matrix.runner }} + runs-on: ${{ matrix.runner }} timeout-minutes: 180 defaults: run: working-directory: codex-rs env: - # Use sccache on Linux; disable caching on Windows toolchains. - USE_SCCACHE: ${{ startsWith(matrix.runner, 'windows') && 'false' || 'true' }} + # Speed up repeated builds across CI runs by caching compiled objects. + USE_SCCACHE: "true" CARGO_INCREMENTAL: "0" SCCACHE_CACHE_SIZE: 10G @@ -138,41 +136,17 @@ jobs: - runner: ubuntu-24.04 target: x86_64-unknown-linux-gnu profile: dev - - runner: ubuntu-24.04-arm - target: aarch64-unknown-linux-musl - profile: dev - - runner: ubuntu-24.04-arm - target: aarch64-unknown-linux-gnu - profile: dev - - runner: windows-2025 - target: x86_64-pc-windows-msvc - profile: dev - - runner: windows-11-arm - target: aarch64-pc-windows-msvc - profile: dev - - # Also run representative release builds on Linux and Windows because - # there could be release-only build errors we want to catch. - # Hopefully this also pre-populates the build cache to speed up - # releases. - runner: ubuntu-24.04 target: x86_64-unknown-linux-musl profile: release - - runner: ubuntu-24.04-arm - target: aarch64-unknown-linux-musl - profile: release - - runner: windows-2025 - target: x86_64-pc-windows-msvc - profile: release - - runner: windows-11-arm - target: aarch64-pc-windows-msvc - profile: release - steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: persist-credentials: false - uses: ./.github/actions/setup-ci + - name: Prepare pinned GNU voice SDK + if: runner.os == 'Linux' && endsWith(matrix.target, '-linux-gnu') + uses: ./.github/actions/codefx-linux-voice-sdk - name: Install Linux build dependencies if: ${{ runner.os == 'Linux' }} shell: bash @@ -187,7 +161,7 @@ jobs: targets: ${{ matrix.target }} components: clippy - - if: ${{ matrix.target == 'x86_64-unknown-linux-musl' || matrix.target == 'aarch64-unknown-linux-musl'}} + - if: ${{ matrix.target == 'x86_64-unknown-linux-musl'}} name: Use hermetic Cargo home (musl) shell: bash run: | @@ -264,7 +238,7 @@ jobs: sccache-${{ matrix.runner }}-${{ matrix.target }}-${{ matrix.profile }}-${{ steps.lockhash.outputs.hash }}- sccache-${{ matrix.runner }}-${{ matrix.target }}-${{ matrix.profile }}- - - if: ${{ matrix.target == 'x86_64-unknown-linux-musl' || matrix.target == 'aarch64-unknown-linux-musl'}} + - if: ${{ matrix.target == 'x86_64-unknown-linux-musl'}} name: Prepare APT cache directories (musl) shell: bash run: | @@ -272,7 +246,7 @@ jobs: sudo mkdir -p /var/cache/apt/archives /var/lib/apt/lists sudo chown -R "$USER:$USER" /var/cache/apt /var/lib/apt/lists - - if: ${{ matrix.target == 'x86_64-unknown-linux-musl' || matrix.target == 'aarch64-unknown-linux-musl'}} + - if: ${{ matrix.target == 'x86_64-unknown-linux-musl'}} name: Restore APT cache (musl) id: cache_apt_restore uses: actions/cache/restore@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5.0.4 @@ -281,13 +255,13 @@ jobs: /var/cache/apt key: apt-${{ matrix.runner }}-${{ matrix.target }}-v1 - - if: ${{ matrix.target == 'x86_64-unknown-linux-musl' || matrix.target == 'aarch64-unknown-linux-musl'}} + - if: ${{ matrix.target == 'x86_64-unknown-linux-musl'}} name: Install Zig uses: mlugg/setup-zig@d1434d08867e3ee9daa34448df10607b98908d29 # v2.2.1 with: version: 0.14.0 - - if: ${{ matrix.target == 'x86_64-unknown-linux-musl' || matrix.target == 'aarch64-unknown-linux-musl'}} + - if: ${{ matrix.target == 'x86_64-unknown-linux-musl'}} name: Install musl build tools env: DEBIAN_FRONTEND: noninteractive @@ -373,7 +347,7 @@ jobs: } >> "$GITHUB_STEP_SUMMARY" - name: Save APT cache (musl) - if: always() && !cancelled() && (matrix.target == 'x86_64-unknown-linux-musl' || matrix.target == 'aarch64-unknown-linux-musl') && steps.cache_apt_restore.outputs.cache-hit != 'true' + if: always() && !cancelled() && (matrix.target == 'x86_64-unknown-linux-musl') && steps.cache_apt_restore.outputs.cache-hit != 'true' continue-on-error: true uses: actions/cache/save@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5.0.4 with: @@ -382,53 +356,17 @@ jobs: key: apt-${{ matrix.runner }}-${{ matrix.target }}-v1 tests_linux_x64_remote: - name: Tests — ubuntu-24.04 - x86_64-unknown-linux-gnu (remote) + name: Tests — ubuntu-24.04 - x86_64-unknown-linux-gnu (local) uses: ./.github/workflows/rust-ci-full-nextest-platform.yml with: runner: ubuntu-24.04 target: x86_64-unknown-linux-gnu profile: ci-test artifact_id: linux-x64-remote - remote_env: true - use_sccache: true - secrets: inherit - - tests_linux_arm64: - name: Tests — ubuntu-24.04-arm - aarch64-unknown-linux-gnu - uses: ./.github/workflows/rust-ci-full-nextest-platform.yml - with: - runner: ubuntu-24.04-arm - target: aarch64-unknown-linux-gnu - profile: ci-test - artifact_id: linux-arm64 - use_sccache: true - secrets: inherit - - tests_windows_x64: - name: Tests — windows-x64 - x86_64-pc-windows-msvc - uses: ./.github/workflows/rust-ci-full-nextest-platform.yml - with: - runner: windows-2025 - target: x86_64-pc-windows-msvc - profile: ci-test - artifact_id: windows-x64 - test_threads: 8 - secrets: inherit - - tests_windows_arm64: - name: Tests — windows-arm64 - aarch64-pc-windows-msvc - uses: ./.github/workflows/rust-ci-full-nextest-platform.yml - with: - runner: windows-11-arm - archive_runner: windows-2025 - target: aarch64-pc-windows-msvc - profile: ci-test - artifact_id: windows-arm64 - test_threads: 8 + remote_env: false use_sccache: true secrets: inherit - # --- Gatherer job for the full post-merge workflow -------------------------- results: name: Full CI results needs: @@ -439,9 +377,6 @@ jobs: argument_comment_lint_prebuilt, lint_build, tests_linux_x64_remote, - tests_linux_arm64, - tests_windows_x64, - tests_windows_arm64, ] if: always() runs-on: ubuntu-24.04 @@ -455,18 +390,12 @@ jobs: echo "shear : ${{ needs.cargo_shear.result }}" echo "lint : ${{ needs.lint_build.result }}" echo "test linux : ${{ needs.tests_linux_x64_remote.result }}" - echo "test arm64 : ${{ needs.tests_linux_arm64.result }}" - echo "test winx64: ${{ needs.tests_windows_x64.result }}" - echo "test winarm: ${{ needs.tests_windows_arm64.result }}" [[ '${{ needs.argument_comment_lint_package.result }}' == 'success' ]] || { echo 'argument_comment_lint_package failed'; exit 1; } [[ '${{ needs.argument_comment_lint_prebuilt.result }}' == 'success' ]] || { echo 'argument_comment_lint_prebuilt failed'; exit 1; } [[ '${{ needs.general.result }}' == 'success' ]] || { echo 'general failed'; exit 1; } [[ '${{ needs.cargo_shear.result }}' == 'success' ]] || { echo 'cargo_shear failed'; exit 1; } [[ '${{ needs.lint_build.result }}' == 'success' ]] || { echo 'lint_build failed'; exit 1; } [[ '${{ needs.tests_linux_x64_remote.result }}' == 'success' ]] || { echo 'tests_linux_x64_remote failed'; exit 1; } - [[ '${{ needs.tests_linux_arm64.result }}' == 'success' ]] || { echo 'tests_linux_arm64 failed'; exit 1; } - [[ '${{ needs.tests_windows_x64.result }}' == 'success' ]] || { echo 'tests_windows_x64 failed'; exit 1; } - [[ '${{ needs.tests_windows_arm64.result }}' == 'success' ]] || { echo 'tests_windows_arm64 failed'; exit 1; } - name: sccache summary note if: always() diff --git a/.github/workflows/rust-ci.yml b/.github/workflows/rust-ci.yml index db7eaf11f9a4..78be4273fb98 100644 --- a/.github/workflows/rust-ci.yml +++ b/.github/workflows/rust-ci.yml @@ -3,10 +3,6 @@ on: workflow_call: workflow_dispatch: -concurrency: - group: rust-ci::${{ github.event.pull_request.number || github.ref }}::scheduler-v4 - cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} - jobs: # --- Detect changed paths so the fast PR workflow only runs relevant jobs --- changed: @@ -82,6 +78,24 @@ jobs: - name: Rust benchmark smoke test run: just bench-smoke + - name: Check for a clean worktree + if: always() && !cancelled() + uses: ./.github/actions/check-clean-worktree + + cargo_shear: + name: cargo shear + runs-on: ubuntu-24.04 + needs: changed + if: ${{ needs.changed.outputs.codex == 'true' || needs.changed.outputs.workflows == 'true' }} + defaults: + run: + working-directory: codex-rs + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + - uses: ./.github/actions/setup-ci + - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 - uses: taiki-e/install-action@44c6d64aa62cd779e873306675c7a58e86d6d532 # v2.62.49 with: tool: cargo-shear@1.11.2 @@ -98,8 +112,8 @@ jobs: needs: changed if: ${{ needs.changed.outputs.argument_comment_lint_package == 'true' }} env: - CARGO_DYLINT_VERSION: 6.3.2 - DYLINT_LINK_VERSION: 6.3.2 + CARGO_DYLINT_VERSION: 6.1.0 + DYLINT_LINK_VERSION: 6.1.0 steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: @@ -149,7 +163,7 @@ jobs: argument_comment_lint_prebuilt: name: Argument comment lint - ${{ matrix.name }} - runs-on: ${{ matrix.runs_on || matrix.runner }} + runs-on: ${{ matrix.runner }} timeout-minutes: ${{ matrix.timeout_minutes }} needs: changed environment: @@ -157,15 +171,11 @@ jobs: deployment: false strategy: fail-fast: false - max-parallel: 1 matrix: include: - name: Linux runner: ubuntu-24.04 - timeout_minutes: 180 - - name: Windows - runner: windows-2025 - timeout_minutes: 180 + timeout_minutes: 360 steps: - name: Check whether argument comment lint should run id: argument_comment_lint_gate @@ -203,10 +213,11 @@ jobs: [ changed, general, + cargo_shear, argument_comment_lint_package, argument_comment_lint_prebuilt, ] - if: ${{ always() && !cancelled() }} + if: always() runs-on: ubuntu-24.04 steps: - name: Summarize @@ -215,6 +226,7 @@ jobs: echo "argpkg : ${{ needs.argument_comment_lint_package.result }}" echo "arglint: ${{ needs.argument_comment_lint_prebuilt.result }}" echo "general: ${{ needs.general.result }}" + echo "shear : ${{ needs.cargo_shear.result }}" # If nothing relevant changed (PR touching only root README, etc.), # declare success regardless of other jobs. @@ -233,6 +245,7 @@ jobs: if [[ "${NEEDS_CHANGED_OUTPUTS_CODEX}" == 'true' || "${NEEDS_CHANGED_OUTPUTS_WORKFLOWS}" == 'true' ]]; then [[ '${{ needs.general.result }}' == 'success' ]] || { echo 'general failed'; exit 1; } + [[ '${{ needs.cargo_shear.result }}' == 'success' ]] || { echo 'cargo_shear failed'; exit 1; } fi env: NEEDS_CHANGED_OUTPUTS_ARGUMENT_COMMENT_LINT: ${{ needs.changed.outputs.argument_comment_lint }} diff --git a/.github/workflows/rust-release-argument-comment-lint.yml b/.github/workflows/rust-release-argument-comment-lint.yml deleted file mode 100644 index c6b3dee31d0a..000000000000 --- a/.github/workflows/rust-release-argument-comment-lint.yml +++ /dev/null @@ -1,104 +0,0 @@ -name: rust-release-argument-comment-lint - -on: - workflow_call: - inputs: - publish: - required: true - type: boolean - -# Cargo's libgit2 transport has been flaky when fetching git dependencies with -# nested submodules. Prefer the system git CLI across every Cargo invocation. -env: - CARGO_NET_GIT_FETCH_WITH_CLI: "true" - -jobs: - skip: - if: ${{ !inputs.publish }} - runs-on: ubuntu-latest - steps: - - run: echo "Skipping argument-comment-lint release assets for prerelease tag" - - build: - if: ${{ inputs.publish }} - name: Build - ${{ matrix.runner }} - ${{ matrix.target }} - runs-on: ${{ matrix.runs_on || matrix.runner }} - timeout-minutes: 60 - env: - CARGO_DYLINT_VERSION: 6.3.2 - DYLINT_LINK_VERSION: 6.3.2 - - strategy: - fail-fast: false - matrix: - include: - - runner: ubuntu-24.04 - target: x86_64-unknown-linux-gnu - archive_name: argument-comment-lint-x86_64-unknown-linux-gnu.tar.gz - lib_name: libargument_comment_lint@nightly-2026-08-20-x86_64-unknown-linux-gnu.so - runner_binary: argument-comment-lint - cargo_dylint_binary: cargo-dylint - - runner: ubuntu-24.04-arm - target: aarch64-unknown-linux-gnu - archive_name: argument-comment-lint-aarch64-unknown-linux-gnu.tar.gz - lib_name: libargument_comment_lint@nightly-2026-08-20-aarch64-unknown-linux-gnu.so - runner_binary: argument-comment-lint - cargo_dylint_binary: cargo-dylint - - runner: windows-2025 - target: x86_64-pc-windows-msvc - archive_name: argument-comment-lint-x86_64-pc-windows-msvc.zip - lib_name: argument_comment_lint@nightly-2026-08-20-x86_64-pc-windows-msvc.dll - runner_binary: argument-comment-lint.exe - cargo_dylint_binary: cargo-dylint.exe - - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - persist-credentials: false - - - uses: dtolnay/rust-toolchain@3c5f7ea28cd621ae0bf5283f0e981fb97b8a7af9 # master - with: - toolchain: nightly-2026-08-20 - targets: ${{ matrix.target }} - components: llvm-tools-preview, rustc-dev, rust-src - - - name: Install tooling - shell: bash - run: | - install_root="${RUNNER_TEMP}/argument-comment-lint-tools" - cargo install --locked cargo-dylint --version "$CARGO_DYLINT_VERSION" --root "$install_root" - cargo install --locked dylint-link --version "$DYLINT_LINK_VERSION" - echo "INSTALL_ROOT=$install_root" >> "$GITHUB_ENV" - - - name: Cargo build - working-directory: tools/argument-comment-lint - shell: bash - run: cargo build --release --target ${{ matrix.target }} - - - name: Stage artifact - shell: bash - run: | - dest="dist/argument-comment-lint/${{ matrix.target }}" - mkdir -p "$dest" - package_root="${RUNNER_TEMP}/argument-comment-lint" - rm -rf "$package_root" - mkdir -p "$package_root/bin" "$package_root/lib" - - cp "tools/argument-comment-lint/target/${{ matrix.target }}/release/${{ matrix.runner_binary }}" \ - "$package_root/bin/${{ matrix.runner_binary }}" - cp "${INSTALL_ROOT}/bin/${{ matrix.cargo_dylint_binary }}" \ - "$package_root/bin/${{ matrix.cargo_dylint_binary }}" - cp "tools/argument-comment-lint/target/${{ matrix.target }}/release/${{ matrix.lib_name }}" \ - "$package_root/lib/${{ matrix.lib_name }}" - - archive_path="$dest/${{ matrix.archive_name }}" - if [[ "${{ runner.os }}" == "Windows" ]]; then - (cd "${RUNNER_TEMP}" && 7z a "$GITHUB_WORKSPACE/$archive_path" argument-comment-lint >/dev/null) - else - (cd "${RUNNER_TEMP}" && tar -czf "$GITHUB_WORKSPACE/$archive_path" argument-comment-lint) - fi - - - uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 - with: - name: argument-comment-lint-${{ matrix.target }} - path: dist/argument-comment-lint/${{ matrix.target }}/* diff --git a/.github/workflows/rust-release-provisioned-macos.yml b/.github/workflows/rust-release-provisioned-macos.yml deleted file mode 100644 index 3b2e57f1e53f..000000000000 --- a/.github/workflows/rust-release-provisioned-macos.yml +++ /dev/null @@ -1,13 +0,0 @@ -name: Disabled macOS release dependency -on: - workflow_call: -permissions: - contents: read -jobs: - disabled: - runs-on: ubuntu-24.04 - steps: - - name: Prevent macOS release dependency execution - run: | - echo "::error::Codefx releases are restricted to Linux and Windows." - exit 1 diff --git a/.github/workflows/rust-release-windows.yml b/.github/workflows/rust-release-windows.yml deleted file mode 100644 index ae435ae4af6e..000000000000 --- a/.github/workflows/rust-release-windows.yml +++ /dev/null @@ -1,728 +0,0 @@ -name: rust-release-windows - -on: - workflow_call: - -env: - WINDOWS_BINARIES: "codex codex-code-mode-host codex-exec-server codex-responses-api-proxy codex-windows-sandbox-setup codex-windows-sandbox-service codex-command-runner codex-app-server" - -jobs: - build-windows-binaries: - name: Build Windows binaries - ${{ matrix.runner }} - ${{ matrix.target }} - ${{ matrix.bundle }} - ${{ matrix.build-system }} - # Parallel Bazel artifacts are advisory while Cargo remains the release path. - continue-on-error: ${{ matrix.build-system == 'bazel' }} - runs-on: ${{ matrix.runs_on }} - environment: - name: bazel - deployment: false - # Temporary increase from 90 minutes while Cargo and Bazel build paths coexist. - # Reassess after the transition using Bazel release build timings. - timeout-minutes: 120 - permissions: - contents: read - defaults: - run: - working-directory: codex-rs - env: - # Preserve Cargo names while teams opt into the additional Bazel artifacts. - ARTIFACT_SUFFIX: ${{ matrix.build-system == 'bazel' && '-bazel' || '' }} - - strategy: - fail-fast: false - matrix: - build-system: [cargo, bazel] - target: - - x86_64-pc-windows-msvc - - aarch64-pc-windows-msvc - bundle: [primary, helpers, app-server] - include: - - runner: windows-x64 - target: x86_64-pc-windows-msvc - bundle: primary - binaries: "codex codex-code-mode-host codex-exec-server codex-responses-api-proxy" - runs_on: - group: ${{ github.event.repository.name }}-runners - labels: ${{ github.event.repository.name }}-windows-x64 - - runner: windows-arm64 - target: aarch64-pc-windows-msvc - bundle: primary - binaries: "codex codex-code-mode-host codex-exec-server codex-responses-api-proxy" - runs_on: - group: ${{ github.event.repository.name }}-runners - labels: ${{ github.event.repository.name }}-windows-arm64 - - runner: windows-x64 - target: x86_64-pc-windows-msvc - bundle: helpers - binaries: "codex-windows-sandbox-setup codex-windows-sandbox-service codex-command-runner" - runs_on: - group: ${{ github.event.repository.name }}-runners - labels: ${{ github.event.repository.name }}-windows-x64 - - runner: windows-arm64 - target: aarch64-pc-windows-msvc - bundle: helpers - binaries: "codex-windows-sandbox-setup codex-windows-sandbox-service codex-command-runner" - runs_on: - group: ${{ github.event.repository.name }}-runners - labels: ${{ github.event.repository.name }}-windows-arm64 - - runner: windows-x64 - target: x86_64-pc-windows-msvc - bundle: app-server - binaries: "codex-app-server codex-code-mode-host codex-exec-server" - runs_on: - group: ${{ github.event.repository.name }}-runners - labels: ${{ github.event.repository.name }}-windows-x64 - - runner: windows-arm64 - target: aarch64-pc-windows-msvc - bundle: app-server - binaries: "codex-app-server codex-code-mode-host codex-exec-server" - runs_on: - group: ${{ github.event.repository.name }}-runners - labels: ${{ github.event.repository.name }}-windows-arm64 - - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - persist-credentials: false - - uses: ./.github/actions/setup-ci - if: matrix.build-system == 'cargo' - - name: Print runner specs (Windows) - shell: powershell - run: | - $computer = Get-CimInstance Win32_ComputerSystem - $cpu = Get-CimInstance Win32_Processor | Select-Object -First 1 - $ramGiB = [math]::Round($computer.TotalPhysicalMemory / 1GB, 1) - Write-Host "Runner: $env:RUNNER_NAME" - Write-Host "OS: $([System.Environment]::OSVersion.VersionString)" - Write-Host "CPU: $($cpu.Name)" - Write-Host "Logical CPUs: $($computer.NumberOfLogicalProcessors)" - Write-Host "Physical CPUs: $($computer.NumberOfProcessors)" - Write-Host "Total RAM: $ramGiB GiB" - Write-Host "Disk usage:" - Get-PSDrive -PSProvider FileSystem | Format-Table -AutoSize Name, @{Name='Size(GB)';Expression={[math]::Round(($_.Used + $_.Free) / 1GB, 1)}}, @{Name='Free(GB)';Expression={[math]::Round($_.Free / 1GB, 1)}} - - name: Set up Rust toolchain - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 - with: - targets: ${{ matrix.build-system == 'cargo' && matrix.target || '' }} - - - name: Prepare Bazel release build - if: ${{ matrix.build-system == 'bazel' }} - uses: ./.github/actions/prepare-bazel-ci - with: - target: ${{ matrix.target }} - cache-scope: bazel-release-${{ matrix.bundle }} - - - name: Configure rusty_v8 artifact overrides and verify checksums - if: matrix.build-system == 'cargo' - uses: ./.github/actions/setup-rusty-v8 - with: - target: ${{ matrix.target }} - - - name: Configure MSVC environment - uses: ./.github/actions/setup-msvc-env - with: - target: ${{ matrix.target }} - - - name: Build Bazel release binaries and symbols - if: ${{ matrix.build-system == 'bazel' }} - uses: ./.github/actions/build-bazel-release - env: - BUILDBUDDY_API_KEY: ${{ secrets.BUILDBUDDY_API_KEY }} - with: - target: ${{ matrix.target }} - bundle: ${{ matrix.bundle }} - release-dir: ${{ env.CARGO_TARGET_DIR }}/${{ matrix.target }}/release - - - name: Cargo build (Windows binaries) - if: ${{ matrix.build-system == 'cargo' }} - shell: bash - run: | - target="${{ matrix.target }}" - if [[ "$target" == "x86_64-pc-windows-msvc" ]]; then - export LIBSQLITE3_FLAGS=SQLITE_DISABLE_INTRINSIC - fi - build_args=() - for binary in ${{ matrix.binaries }}; do - build_args+=(--bin "$binary") - done - STABLE_GIT_COMMIT="$(git rev-parse HEAD)" - export STABLE_GIT_COMMIT - cargo build --target "$target" --release --timings "${build_args[@]}" - - - name: Stage Windows binaries - shell: bash - run: | - release_dir="$CARGO_TARGET_DIR/${{ matrix.target }}/release" - output_dir="$release_dir/staged-${{ matrix.bundle }}" - mkdir -p "$output_dir" - for binary in ${{ matrix.binaries }}; do - pdb_name="${binary//-/_}" - pdb_path="$release_dir/${pdb_name}.pdb" - if [[ ! -f "$pdb_path" ]]; then - pdb_path="$release_dir/${binary}.pdb" - fi - if [[ ! -f "$pdb_path" ]]; then - echo "PDB for $binary not found at $release_dir/${pdb_name}.pdb or $release_dir/${binary}.pdb" >&2 - exit 1 - fi - - cp "$release_dir/${binary}.exe" "$output_dir/${binary}.exe" - cp "$pdb_path" "$output_dir/${binary}.pdb" - done - - - name: Upload Windows binaries - uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 - with: - name: windows-binaries-${{ matrix.target }}-${{ matrix.bundle }}${{ env.ARTIFACT_SUFFIX }} - path: | - ${{ env.CARGO_TARGET_DIR }}/${{ matrix.target }}/release/staged-${{ matrix.bundle }}/* - - build-windows-voice: - name: Build Windows voice - ${{ matrix.target }} - runs-on: ${{ matrix.runs_on }} - environment: - name: bazel - deployment: false - timeout-minutes: 120 - permissions: - contents: read - strategy: - fail-fast: false - matrix: - include: - - target: x86_64-pc-windows-msvc - arch: x86_64 - python_arch: x64 - runs_on: - group: ${{ github.event.repository.name }}-runners - labels: ${{ github.event.repository.name }}-windows-x64 - - target: aarch64-pc-windows-msvc - arch: aarch64 - python_arch: arm64 - runs_on: - group: ${{ github.event.repository.name }}-runners - labels: ${{ github.event.repository.name }}-windows-arm64 - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - persist-credentials: false - - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 - with: - python-version: "3.12" - architecture: ${{ matrix.python_arch }} - - name: Prepare Bazel CI - uses: ./.github/actions/prepare-bazel-ci - with: - target: ${{ matrix.target }} - cache-scope: release-voice-windows - - uses: ./.github/actions/setup-msvc-env - with: - target: ${{ matrix.target }} - - name: Refresh Bazel PATH for the selected MSVC target - shell: pwsh - run: ./.github/scripts/compute-bazel-windows-path.ps1 - - name: Download pinned Windows build inputs - shell: pwsh - env: - GH_TOKEN: ${{ github.token }} - run: | - $manifest = Get-Content -Raw .github/scripts/voice-cygwin-snapshot.json | ConvertFrom-Json - $pin = $manifest.archive - $source = $manifest.sourceArchive - $directory = Join-Path $env:RUNNER_TEMP "voice-cygwin-snapshot" - New-Item -ItemType Directory -Path $directory | Out-Null - gh release download $pin.tag --repo "${{ github.repository }}" --pattern $pin.name --pattern $source.name --dir $directory - if ($LASTEXITCODE -ne 0) { throw "Cannot obtain the public Cygwin inputs and source" } - $sourceFile = Join-Path $directory $source.name - if ((Get-Item $sourceFile).Length -ne $source.bytes -or - (Get-FileHash $sourceFile -Algorithm SHA256).Hash.ToLowerInvariant() -ne $source.sha256) { - throw "Public Cygwin source archive mismatch" - } - "VOICE_CYGWIN_ARCHIVE=$(Join-Path $directory $pin.name)" | Out-File $env:GITHUB_ENV -Encoding utf8 -Append - - name: Verify and install pinned public build tools - shell: pwsh - run: | - & ./.github/scripts/setup-voice-windows.ps1 -Target "${{ matrix.target }}" -SnapshotArchive $env:VOICE_CYGWIN_ARCHIVE - if (-not $env:SystemRoot) { throw "Windows SystemRoot is required for native audio actions" } - "VOICE_WINDOWS_SYSTEM_ROOT=$env:SystemRoot" | Out-File $env:GITHUB_ENV -Encoding utf8 -Append - $hostArch = $env:PROCESSOR_ARCHITEW6432 - if (-not $hostArch) { $hostArch = $env:PROCESSOR_ARCHITECTURE } - if (-not $hostArch) { throw "Windows host architecture is required" } - "VOICE_WINDOWS_HOST_ARCH=$hostArch" | Out-File $env:GITHUB_ENV -Encoding utf8 -Append - - name: Build same-commit native runtime and helper - shell: bash - env: - ARCH: ${{ matrix.arch }} - VOICE_ARCH: ${{ matrix.arch }} - BUILDBUDDY_API_KEY: ${{ secrets.BUILDBUDDY_API_KEY }} - run: | - (cd codex-rs && cargo update --workspace) - python .github/scripts/watch_voice_bazel.py "$(cygpath -w "$BASH")" ./.github/scripts/run-bazel-ci.sh \ - --remote-download-toplevel \ - --print-failed-action-summary \ - --windows-msvc-host-platform \ - -- \ - test --config=release \ - --platforms=//:local_windows_msvc \ - --extra_toolchains=@local_config_cc//:cc-toolchain-x64_windows,@local_config_cc//:cc-toolchain-arm64_windows,//third_party/voice:windows_pkg_config_toolchain,//third_party/voice:windows_cmake_toolchain \ - --repo_env=BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=0 \ - --repo_env=BAZEL_MSVC_RUNTIME_VISUAL_STUDIO_EULA=1 \ - --inject_repository="voice_windows_tools=$VOICE_WINDOWS_BAZEL_REPOSITORY" \ - --//third_party/voice:windows_installed_tools=@voice_windows_tools//:tools \ - --action_env="SystemRoot=$VOICE_WINDOWS_SYSTEM_ROOT" \ - --host_action_env="SystemRoot=$VOICE_WINDOWS_SYSTEM_ROOT" \ - --action_env="PROCESSOR_ARCHITECTURE=$VOICE_WINDOWS_HOST_ARCH" \ - --host_action_env="PROCESSOR_ARCHITECTURE=$VOICE_WINDOWS_HOST_ARCH" \ - --output_groups=default,receipt,sdk \ - --workspace_status_command=./scripts/workspace-status.cmd \ - --build_metadata=COMMIT_SHA="$GITHUB_SHA" \ - -- \ - "//third_party/voice:native_runtime_windows_$ARCH" \ - @rules_rust//cargo/private/cargo_build_script_runner:test \ - //codex-rs/voice-host:codex-voice-host - - name: Stage verified voice build output - shell: bash - env: - TARGET: ${{ matrix.target }} - ARCH: ${{ matrix.arch }} - run: | - set -euo pipefail - runtime="bazel-bin/third_party/voice/native_runtime_windows_${ARCH}" - PYTHONPATH=third_party/voice python - "$runtime" "$TARGET" <<'PY' - from pathlib import Path - import sys - from package_runtime import runtime_files - runtime_files(Path(sys.argv[1]).resolve(strict=True), sys.argv[2]) - PY - output="voice-unsigned/${TARGET}" - mkdir -p "$output" - cp -R "$runtime" "$output/runtime" - cp bazel-bin/codex-rs/voice-host/codex-voice-host.exe "$output/codex-voice-host.exe" - chmod -R u+w "$output" - tar -C "$output" -czf "voice-unsigned-${TARGET}.tar.gz" runtime codex-voice-host.exe - - uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 - with: - name: voice-${{ matrix.target }}-unsigned - path: voice-unsigned-${{ matrix.target }}.tar.gz - if-no-files-found: error - - build-windows-symbols: - needs: - - build-windows-binaries - name: Build Windows symbols - ${{ matrix.target }} - ${{ matrix.build-system }} - continue-on-error: ${{ matrix.build-system == 'bazel' }} - runs-on: ubuntu-24.04 - timeout-minutes: 15 - permissions: - contents: read - defaults: - run: - working-directory: codex-rs - env: - ARTIFACT_SUFFIX: ${{ matrix.build-system == 'bazel' && '-bazel' || '' }} - - strategy: - fail-fast: false - matrix: - build-system: [cargo, bazel] - target: - - aarch64-pc-windows-msvc - - x86_64-pc-windows-msvc - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - persist-credentials: false - - uses: ./.github/actions/setup-ci - - name: Download prebuilt Windows binaries - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - pattern: windows-binaries-${{ matrix.target }}-{primary,helpers,app-server}${{ env.ARTIFACT_SUFFIX }} - merge-multiple: true - path: ${{ env.CARGO_TARGET_DIR }}/${{ matrix.target }}/release - - name: Build symbols archive - shell: bash - run: | - bash "${GITHUB_WORKSPACE}/.github/scripts/archive-release-symbols-and-strip-binaries.sh" \ - --target "${{ matrix.target }}" \ - --artifact-name "${{ matrix.target }}" \ - --release-dir "${CARGO_TARGET_DIR}/${{ matrix.target }}/release" \ - --archive-dir "symbols-dist/${{ matrix.target }}" \ - --binaries "${WINDOWS_BINARIES}" - - name: Suffix Bazel artifact filenames - if: ${{ matrix.build-system == 'bazel' }} - shell: bash - run: | - set -euo pipefail - for artifact in "symbols-dist/${{ matrix.target }}"/*; do - name="${artifact##*/}" - stem="${name%%.*}" - mv "$artifact" "${artifact%/*}/${stem}-bazel${name#"$stem"}" - done - - - name: Upload symbols archive - uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 - with: - name: ${{ matrix.target }}-symbols${{ env.ARTIFACT_SUFFIX }} - path: codex-rs/symbols-dist/${{ matrix.target }}/* - if-no-files-found: error - - build-windows: - needs: - - build-windows-binaries - - build-windows-voice - name: Build - ${{ matrix.runner }} - ${{ matrix.target }} - ${{ matrix.build-system }} - continue-on-error: ${{ matrix.build-system == 'bazel' }} - runs-on: ${{ matrix.runs_on }} - environment: - name: azure-artifact-signing - deployment: false - timeout-minutes: 120 - permissions: - contents: read - id-token: write - defaults: - run: - working-directory: codex-rs - env: - ARTIFACT_SUFFIX: ${{ matrix.build-system == 'bazel' && '-bazel' || '' }} - - strategy: - fail-fast: false - matrix: - build-system: [cargo, bazel] - target: - - x86_64-pc-windows-msvc - - aarch64-pc-windows-msvc - include: - - runner: windows-x64 - target: x86_64-pc-windows-msvc - runs_on: - group: ${{ github.event.repository.name }}-runners - labels: ${{ github.event.repository.name }}-windows-x64 - - runner: windows-x64 - target: aarch64-pc-windows-msvc - runs_on: - group: ${{ github.event.repository.name }}-runners - labels: ${{ github.event.repository.name }}-windows-x64 - - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - persist-credentials: false - - - uses: ./.github/actions/setup-ci - - - name: Download prebuilt Windows primary binaries - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - name: windows-binaries-${{ matrix.target }}-primary${{ env.ARTIFACT_SUFFIX }} - path: ${{ env.CARGO_TARGET_DIR }}/${{ matrix.target }}/release - - - name: Download prebuilt Windows helper binaries - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - name: windows-binaries-${{ matrix.target }}-helpers${{ env.ARTIFACT_SUFFIX }} - path: ${{ env.CARGO_TARGET_DIR }}/${{ matrix.target }}/release - - - name: Download prebuilt Windows app-server binary - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - name: windows-binaries-${{ matrix.target }}-app-server${{ env.ARTIFACT_SUFFIX }} - path: ${{ env.CARGO_TARGET_DIR }}/${{ matrix.target }}/release - - - name: Verify binaries - shell: bash - run: | - set -euo pipefail - for binary in ${WINDOWS_BINARIES}; do - ls -lh "$CARGO_TARGET_DIR/${{ matrix.target }}/release/${binary}.exe" - done - - - name: Sign Windows release files with Azure Trusted Signing - uses: ./.github/actions/windows-code-sign - with: - target: ${{ matrix.target }} - binaries: ${{ env.WINDOWS_BINARIES }} - # The installer is architecture-independent; sign it only in the x64 job. - additional-files: ${{ matrix.target == 'x86_64-pc-windows-msvc' && format('{0}/scripts/install/install.ps1', github.workspace) || '' }} - client-id: ${{ secrets.AZURE_ARTIFACT_SIGNING_CLIENT_ID }} - tenant-id: ${{ secrets.AZURE_ARTIFACT_SIGNING_TENANT_ID }} - subscription-id: ${{ secrets.AZURE_ARTIFACT_SIGNING_SUBSCRIPTION_ID }} - endpoint: ${{ secrets.AZURE_ARTIFACT_SIGNING_ENDPOINT }} - account-name: ${{ secrets.AZURE_ARTIFACT_SIGNING_ACCOUNT_NAME }} - certificate-profile-name: ${{ secrets.AZURE_ARTIFACT_SIGNING_CERTIFICATE_PROFILE_NAME }} - - - name: Download matching native voice build - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - name: voice-${{ matrix.target }}-unsigned - path: ${{ runner.temp }}/unsigned-voice - - - name: Stage voice files for signing - id: voice_files - shell: bash - run: | - set -euo pipefail - target="${{ matrix.target }}" - unsigned="${RUNNER_TEMP}/unsigned-voice/extracted" - signed="${GITHUB_WORKSPACE}/signed-voice/${target}" - mkdir -p "$unsigned" "$signed" - tar -xzf "$(cygpath -u "${RUNNER_TEMP}/unsigned-voice/voice-unsigned-${target}.tar.gz")" -C "$(cygpath -u "$unsigned")" - python "${GITHUB_WORKSPACE}/third_party/voice/release_runtime.py" stage \ - --source "$unsigned/runtime" --target "$target" --output "$signed/runtime" - cp "$unsigned/codex-voice-host.exe" "$signed/codex-voice-host.exe" - chmod -R u+w "$signed" - { - echo 'files<> "$GITHUB_OUTPUT" - - - name: Sign Windows voice helper and native DLLs - uses: azure/trusted-signing-action@1d365fec12862c4aa68fcac418143d73f0cea293 # v0.5.11 - with: - endpoint: ${{ secrets.AZURE_ARTIFACT_SIGNING_ENDPOINT }} - trusted-signing-account-name: ${{ secrets.AZURE_ARTIFACT_SIGNING_ACCOUNT_NAME }} - certificate-profile-name: ${{ secrets.AZURE_ARTIFACT_SIGNING_CERTIFICATE_PROFILE_NAME }} - exclude-environment-credential: true - exclude-workload-identity-credential: true - exclude-managed-identity-credential: true - exclude-shared-token-cache-credential: true - exclude-visual-studio-credential: true - exclude-visual-studio-code-credential: true - exclude-azure-cli-credential: false - exclude-azure-powershell-credential: true - exclude-azure-developer-cli-credential: true - exclude-interactive-browser-credential: true - cache-dependencies: false - files: ${{ steps.voice_files.outputs.files }} - - - uses: ./.github/actions/setup-msvc-env - with: - target: ${{ matrix.target }} - - - name: Seal and verify signed voice output - shell: pwsh - run: | - $target = "${{ matrix.target }}" - $signed = Join-Path $env:GITHUB_WORKSPACE "signed-voice/$target" - python (Join-Path $env:GITHUB_WORKSPACE 'third_party/voice/windows_crt.py') --root (Join-Path $signed 'runtime') --target $target --helper (Join-Path $signed 'codex-voice-host.exe') - if ($LASTEXITCODE -ne 0) { throw 'Cannot stage verified Microsoft CRT' } - $files = @(Join-Path $signed "codex-voice-host.exe") + @( - Get-ChildItem (Join-Path $signed "runtime/bin") -Filter *.dll -File | - ForEach-Object FullName - ) - if ($files.Count -lt 8) { throw "Voice DLL closure is incomplete" } - foreach ($file in $files) { - $signature = Get-AuthenticodeSignature $file - if ($signature.Status -ne 'Valid') { throw "Unsigned voice file: $file ($($signature.Status))" } - } - python (Join-Path $env:GITHUB_WORKSPACE 'third_party/voice/release_runtime.py') seal --target $target --output (Join-Path $signed 'runtime') - if ($LASTEXITCODE -ne 0) { throw 'Cannot seal signed voice runtime' } - "VOICE_RELEASE_DIR=$signed" | Out-File $env:GITHUB_ENV -Encoding utf8 -Append - - - name: Stage artifacts - shell: bash - run: | - dest="dist/${{ matrix.target }}" - mkdir -p "$dest" - - for binary in ${WINDOWS_BINARIES}; do - cp "$CARGO_TARGET_DIR/${{ matrix.target }}/release/${binary}.exe" \ - "$dest/${binary}-${{ matrix.target }}.exe" - done - - - name: Build Codex package archives - shell: bash - run: | - set -euo pipefail - target="${{ matrix.target }}" - archive_script="${GITHUB_WORKSPACE}/.github/scripts/build-codex-package-archive.sh" - voice_args=(--voice-release-dir "$VOICE_RELEASE_DIR") - voice_args+=(--release-version "${GITHUB_REF_NAME#rust-v}") - bash "$archive_script" \ - --target "$target" --bundle primary \ - --entrypoint-dir "$CARGO_TARGET_DIR/$target/release" \ - --archive-dir "dist/$target" "${voice_args[@]}" - bash "$archive_script" \ - --target "$target" --bundle app-server \ - --entrypoint-dir "$CARGO_TARGET_DIR/$target/release" \ - --archive-dir "dist/$target" - - - name: Verify packaged executor signatures and bytes - shell: pwsh - run: | - $target = "${{ matrix.target }}" - $source = Join-Path $env:CARGO_TARGET_DIR "$target/release/codex-exec-server.exe" - foreach ($stem in @("codex-package", "codex-app-server-package")) { - $package = Join-Path $env:RUNNER_TEMP "verify-executor-$stem-$target" - New-Item -ItemType Directory -Path $package | Out-Null - tar -xzf "dist/$target/$stem-$target.tar.gz" -C $package - if ($LASTEXITCODE -ne 0) { throw "Cannot extract executor package" } - $binary = Join-Path $package "bin/codex-exec-server.exe" - if ((Get-FileHash $binary).Hash -ne (Get-FileHash $source).Hash) { - throw "Packaged executor differs from the signed input" - } - $signature = Get-AuthenticodeSignature $binary - if ($signature.Status -ne "Valid" -or $null -eq $signature.TimeStamperCertificate) { - throw "Invalid or untimestamped executor signature" - } - } - - - name: Verify packaged Windows voice closure - shell: pwsh - run: | - $target = "${{ matrix.target }}" - $package = Join-Path $env:RUNNER_TEMP "verify-voice-archive-$target" - New-Item -ItemType Directory -Path $package | Out-Null - tar -xzf "dist/$target/codex-package-$target.tar.gz" -C $package - if ($LASTEXITCODE -ne 0) { throw "Cannot extract the final Windows package" } - $voice = Join-Path $package 'codex-resources/voice' - $helper = Join-Path $voice 'bin/codex-voice-host.exe' - if (-not (Test-Path $helper) -or -not (Test-Path (Join-Path $voice 'bin/gstreamer-1.0-0.dll'))) { - throw 'Signed Windows voice files are missing from the canonical package' - } - $signature = Get-AuthenticodeSignature $helper - if ($signature.Status -ne 'Valid') { throw "Packaged helper signature: $($signature.Status)" } - python -c 'import sys; from pathlib import Path; sys.path.insert(0, sys.argv[3]); from package_runtime import runtime_files; runtime_files(Path(sys.argv[1]), sys.argv[2], public_release=True)' $voice $target (Join-Path $env:GITHUB_WORKSPACE 'third_party/voice') - if ($LASTEXITCODE -ne 0) { throw 'Packaged runtime receipt verification failed' } - - - name: Set up Python release tools - if: ${{ matrix.build-system == 'cargo' }} - uses: ./.github/actions/setup-python-release-tools - with: - group: runtime - - - name: Build Python runtime wheel - if: ${{ matrix.build-system == 'cargo' }} - shell: bash - run: | - set -euo pipefail - - case "${{ matrix.target }}" in - aarch64-pc-windows-msvc) - platform_tag="win_arm64" - ;; - x86_64-pc-windows-msvc) - platform_tag="win_amd64" - ;; - *) - echo "No Python runtime wheel platform tag for ${{ matrix.target }}" - exit 1 - ;; - esac - - # The wheel's Windows support floor predates the native voice - # runtime's verified device/VC++ prerequisites. Keep it voice-free. - wheel_package="${RUNNER_TEMP}/codex-package-${{ matrix.target }}" - python - "$wheel_package" <<'PY' - import sys - from pathlib import Path - assert not (Path(sys.argv[1]) / "codex-resources" / "voice").exists() - PY - stage_dir="${RUNNER_TEMP}/openai-codex-cli-bin-${{ matrix.target }}" - wheel_dir="${GITHUB_WORKSPACE}/python-runtime-dist/${{ matrix.target }}" - python "${GITHUB_WORKSPACE}/sdk/python/scripts/update_sdk_artifacts.py" \ - stage-runtime \ - "$stage_dir" \ - "$wheel_package" \ - --codex-version "${GITHUB_REF_NAME}" \ - --platform-tag "$platform_tag" - uv build --offline --no-build-isolation --no-create-gitignore \ - --python "${RUNNER_TEMP}/python-runtime-build-venv" --wheel --out-dir "$wheel_dir" "$stage_dir" - - - name: Upload Python runtime wheel - if: ${{ matrix.build-system == 'cargo' }} - uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 - with: - name: python-runtime-wheel-${{ matrix.target }} - path: python-runtime-dist/${{ matrix.target }}/*.whl - if-no-files-found: error - - - name: Compress artifacts - shell: bash - run: | - # Path that contains the uncompressed binaries for the current - # ${{ matrix.target }} - dest="dist/${{ matrix.target }}" - repo_root=$PWD - target="${{ matrix.target }}" - export dest repo_root target - - # For compatibility with environments that lack the `zstd` tool we - # additionally create a `.tar.gz` and `.zip` for every Windows binary. - # The end result is: - # codex-.zst - # codex-.tar.gz - # codex-.zip - # Variables in the single-quoted script expand in the child shell. - # shellcheck disable=SC2016 - # Start larger binaries first so both workers stay busy. - find "$dest" -maxdepth 1 -type f -printf '%s %p\0' | - sort -z -nr | - cut -z -d ' ' -f 2- | - xargs -0 -n1 -P2 bash -c ' - set -euo pipefail - f=$1 - base="$(basename "$f")" - # Skip files that are already archives (should not happen, but be - # safe). - if [[ "$base" == *.tar.gz || "$base" == *.tar.zst || "$base" == *.zip || "$base" == *.dmg ]]; then - exit 0 - fi - - # Do not try to compress signature bundles. - if [[ "$base" == *.sigstore ]]; then - exit 0 - fi - - # Create per-binary tar.gz - tar -C "$dest" -czf "$dest/${base}.tar.gz" "$base" - - # Create zip archive for Windows binaries. - # Must run from inside the dest dir so 7z does not embed the - # directory path inside the zip. - if [[ "$base" == "codex-${target}.exe" ]]; then - # Preserve WinGet executable paths while including the signed - # runtime, resources, and package metadata from the canonical tar. - bundle_dir="$(mktemp -d)" - tar -xzf "$dest/codex-package-${target}.tar.gz" -C "$bundle_dir" - python "${GITHUB_WORKSPACE}/scripts/build_winget_package.py" "$(cygpath -w "$bundle_dir")" - (cd "$bundle_dir" && 7z a "$repo_root/$dest/${base}.zip" .) - rm -rf "$bundle_dir" - else - (cd "$dest" && 7z a "${base}.zip" "$base") - fi - - # Keep raw executables and produce .zst alongside them. - "${GITHUB_WORKSPACE}/.github/workflows/zstd" -T0 -19 "$dest/$base" - ' _ - - - name: Verify and stage signed PowerShell installer - if: matrix.build-system == 'cargo' && matrix.target == 'x86_64-pc-windows-msvc' - shell: powershell - run: | - $installer = Join-Path $env:GITHUB_WORKSPACE 'scripts/install/install.ps1' - $signature = Get-AuthenticodeSignature $installer - if ($signature.Status -ne 'Valid' -or $null -eq $signature.TimeStamperCertificate) { - throw "Installer signature is invalid or missing a timestamp: $($signature.Status)" - } - # Stage after compression so the installer remains a plain script. - Copy-Item $installer 'dist/${{ matrix.target }}/install.ps1' - - - name: Suffix Bazel artifact filenames - if: ${{ matrix.build-system == 'bazel' }} - shell: bash - run: | - set -euo pipefail - for artifact in "dist/${{ matrix.target }}"/*; do - name="${artifact##*/}" - stem="${name%%.*}" - mv "$artifact" "${artifact%/*}/${stem}-bazel${name#"$stem"}" - done - - - uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 - with: - name: ${{ matrix.target }}${{ env.ARTIFACT_SUFFIX }} - path: | - codex-rs/dist/${{ matrix.target }}/* diff --git a/.github/workflows/rust-release.yml b/.github/workflows/rust-release.yml deleted file mode 100644 index 118279a3e76d..000000000000 --- a/.github/workflows/rust-release.yml +++ /dev/null @@ -1,13 +0,0 @@ -name: Disabled upstream Rust publisher (use Codefx verified release) -on: - workflow_dispatch: -permissions: - contents: read -jobs: - disabled: - runs-on: ubuntu-24.04 - steps: - - name: Block upstream artifact and macOS release path - run: | - echo "::error::Upstream Rust release including macOS is disabled in Codefx. Use codefx-rust-v0.166-release.yml." - exit 1 diff --git a/.github/workflows/rusty-v8-release.yml b/.github/workflows/rusty-v8-release.yml deleted file mode 100644 index 68a759c6c02a..000000000000 --- a/.github/workflows/rusty-v8-release.yml +++ /dev/null @@ -1,13 +0,0 @@ -name: Disabled upstream V8 publisher (Codefx Linux/Windows only) -on: - workflow_dispatch: -permissions: - contents: read -jobs: - disabled: - runs-on: ubuntu-24.04 - steps: - - name: Block upstream multi-OS publishing - run: | - echo "::error::Upstream V8 release workflow contains macOS release builds and is disabled in Codefx." - exit 1 diff --git a/.github/workflows/sdk.yml b/.github/workflows/sdk.yml index ea82ac692021..18545665d771 100644 --- a/.github/workflows/sdk.yml +++ b/.github/workflows/sdk.yml @@ -4,15 +4,9 @@ on: workflow_call: jobs: - sdks: - # Keep both SDK suites on one runner. They share checkout, Docker, and - # Bazel setup; running them in one job preserves every test while avoiding - # a second runner allocation and a second repository checkout. + python-sdk-installation: runs-on: ubuntu-24.04 - timeout-minutes: 120 - environment: - name: bazel - deployment: false + timeout-minutes: 10 steps: - name: Checkout repository uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 @@ -39,6 +33,15 @@ jobs: env -u PYTHONPATH -u CODEX_EXEC_PATH /tmp/installed/bin/python tests/installed_sdk_smoke.py ' + sdks: + runs-on: ubuntu-24.04 + timeout-minutes: 20 + steps: + - name: Checkout repository + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + - name: Install Linux bwrap build dependencies shell: bash run: | @@ -57,61 +60,17 @@ jobs: node-version-file: .nvmrc cache: pnpm - - name: Prepare Bazel CI - id: setup_bazel - uses: ./.github/actions/prepare-bazel-ci + - name: Download the same-run current source package + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: - target: x86_64-unknown-linux-gnu - cache-scope: bazel-target + name: codefx-source-x86_64-unknown-linux-musl + path: ${{ runner.temp }}/sdk-package - - name: Build codex and the code-mode host with Bazel - id: build_bazel - env: - BUILDBUDDY_API_KEY: ${{ secrets.BUILDBUDDY_API_KEY }} - shell: bash - run: | - set -euo pipefail - # Use the shared CI wrapper so fork PRs fall back cleanly when - # BuildBuddy credentials are unavailable. This workflow needs the - # built binaries on disk afterwards, so ask the wrapper to override - # CI's default remote_download_minimal behavior. - ./.github/scripts/run-bazel-ci.sh \ - --remote-download-toplevel \ - -- \ - build \ - --build_metadata=COMMIT_SHA=${GITHUB_SHA} \ - --build_metadata=TAG_job=sdk \ - -- \ - //codex-rs/cli:codex \ - //codex-rs/code-mode-host:codex-code-mode-host - - cquery_output="$( - ./.github/scripts/run-bazel-ci.sh \ - -- \ - cquery \ - --output=files \ - -- \ - 'set(//codex-rs/cli:codex //codex-rs/code-mode-host:codex-code-mode-host)' \ - | grep -E '^(/|bazel-out/)' - )" - mapfile -t bazel_output_paths <<< "${cquery_output}" - if [[ ${#bazel_output_paths[@]} -ne 2 ]]; then - echo "Expected both Bazel-built binaries, found ${#bazel_output_paths[@]}." >&2 - exit 1 - fi - - # Stage both binaries together so the CLI can discover its sibling - # code-mode host while the SDK tests spawn the CLI directly. - install_dir="${GITHUB_WORKSPACE}/.tmp/sdk-ci" - mkdir -p "${install_dir}" - install -m 755 "${bazel_output_paths[@]}" "${install_dir}" - echo "CODEX_EXEC_PATH=${install_dir}/codex" >> "$GITHUB_ENV" - - - name: Warm up Bazel-built codex - shell: bash - run: | - set -euo pipefail - "${CODEX_EXEC_PATH}" --version + - name: Verify candidate provenance and stage SDK executables + run: python3 scripts/install/prepare_sdk_package.py --directory "$RUNNER_TEMP/sdk-package" --output "$RUNNER_TEMP/sdk-runtime" + + - name: Warm up the current source CLI + run: '"${CODEX_EXEC_PATH}" --version' - name: Install dependencies run: pnpm install --frozen-lockfile @@ -123,7 +82,7 @@ jobs: run: pnpm -r --filter ./sdk/typescript run lint - name: Test SDK packages - run: pnpm -r --filter ./sdk/typescript run test + run: pnpm -r --filter ./sdk/typescript run test --runInBand - name: Install uv uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2 @@ -138,14 +97,6 @@ jobs: uv run --only-group dev --frozen --no-sync ruff format --check . uv run --only-group dev --frozen --no-sync pytest - - name: Save bazel repository cache - if: always() && !cancelled() && steps.build_bazel.outcome == 'success' && steps.setup_bazel.outputs.repository-cache-hit != 'true' - continue-on-error: true - uses: actions/cache/save@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5.0.4 - with: - path: ${{ steps.setup_bazel.outputs.repository-cache-path }} - key: ${{ steps.setup_bazel.outputs.repository-cache-key }} - - name: Check for a clean worktree if: always() && !cancelled() uses: ./.github/actions/check-clean-worktree diff --git a/.github/workflows/v8-canary.yml b/.github/workflows/v8-canary.yml index 36c4c3ccea11..8f0b531b866b 100644 --- a/.github/workflows/v8-canary.yml +++ b/.github/workflows/v8-canary.yml @@ -10,7 +10,7 @@ on: workflow_dispatch: concurrency: - group: ${{ github.workflow }}::${{ github.event.pull_request.number > 0 && format('pr-{0}', github.event.pull_request.number) || github.ref_name }}::scheduler-v4 + group: ${{ github.workflow }}::${{ github.event.pull_request.number > 0 && format('pr-{0}', github.event.pull_request.number) || github.ref_name }} cancel-in-progress: ${{ github.ref_name != 'main' }} jobs: @@ -83,7 +83,6 @@ jobs: deployment: false strategy: fail-fast: false - max-parallel: 1 matrix: include: - runner: ubuntu-24.04 @@ -98,18 +97,6 @@ jobs: sandbox: true target: x86_64-unknown-linux-gnu variant: ptrcomp-sandbox - - runner: ubuntu-24.04-arm - bazel_config: ci-v8 - platform: linux_arm64 - sandbox: false - target: aarch64-unknown-linux-gnu - variant: release - - runner: ubuntu-24.04-arm - bazel_config: ci-v8 - platform: linux_arm64 - sandbox: true - target: aarch64-unknown-linux-gnu - variant: ptrcomp-sandbox - runner: ubuntu-24.04 bazel_config: ci-v8 platform: linux_amd64_musl @@ -122,18 +109,6 @@ jobs: sandbox: true target: x86_64-unknown-linux-musl variant: ptrcomp-sandbox - - runner: ubuntu-24.04-arm - bazel_config: ci-v8 - platform: linux_arm64_musl - sandbox: false - target: aarch64-unknown-linux-musl - variant: release - - runner: ubuntu-24.04-arm - bazel_config: ci-v8 - platform: linux_arm64_musl - sandbox: true - target: aarch64-unknown-linux-musl - variant: ptrcomp-sandbox steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: @@ -243,7 +218,7 @@ jobs: exit 1 fi - cargo_args=(test -p codex-v8-poc --target "${TARGET}") + cargo_args=(test -p codex-v8-poc --no-default-features --target "${TARGET}") if [[ "${SANDBOX}" == "true" ]]; then cargo_args+=(--features sandbox) fi @@ -266,163 +241,3 @@ jobs: - name: Check for a clean worktree if: always() && !cancelled() uses: ./.github/actions/check-clean-worktree - - build-windows-source: - name: Build ptrcomp-sandbox ${{ matrix.target }} from source - needs: [metadata, build] - if: ${{ always() && !cancelled() && needs.metadata.outputs.windows_source_required == 'true' }} - runs-on: ${{ matrix.runner }} - permissions: - contents: read - strategy: - fail-fast: false - max-parallel: 1 - matrix: - include: - - runner: windows-2025 - target: x86_64-pc-windows-msvc - - runner: windows-2025 - target: aarch64-pc-windows-msvc - - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - with: - persist-credentials: false - - - id: setup_ci - uses: ./.github/actions/setup-ci - - - name: Configure git for upstream checkout - shell: bash - run: git config --global core.symlinks true - - - name: Check out upstream rusty_v8 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - with: - repository: denoland/rusty_v8 - ref: v${{ needs.metadata.outputs.v8_version }} - path: upstream-rusty-v8 - submodules: recursive - persist-credentials: false - - - name: Download upstream Windows build tools - shell: bash - working-directory: upstream-rusty-v8 - run: | - set -euo pipefail - # Upstream skips this submodule and downloads the pinned archive in CI. - mkdir -p tools/win - curl -fL https://chromium.googlesource.com/chromium/src/tools/win/+archive/faefd1b6fa9eeb033ad6fe60368ccb9bf908cbd0.tar.gz | - tar -xz -C tools/win - - - name: Set up Python - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6 - with: - python-version: "3.11" - architecture: x64 - - - name: Set up Codex Rust toolchain for Cargo smoke - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 - with: - toolchain: "1.95.0" - targets: ${{ matrix.target }} - - - name: Install rusty_v8 Rust toolchain - env: - TARGET: ${{ matrix.target }} - shell: bash - run: | - set -euo pipefail - rustup toolchain install 1.91.0 --profile minimal --no-self-update - rustup target add --toolchain 1.91.0 "${TARGET}" - - - name: Write upstream submodule status - shell: bash - working-directory: upstream-rusty-v8 - run: git submodule status --recursive > git_submodule_status.txt - - - name: Restore upstream source-build cache - uses: actions/cache@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5 - with: - path: | - ${{ steps.setup_ci.outputs.cargo-target-dir }}/sccache - ${{ steps.setup_ci.outputs.cargo-target-dir }}/${{ matrix.target }}/release/gn_out - key: rusty-v8-source-${{ matrix.target }}-${{ matrix.runner }}-sandbox-${{ hashFiles('upstream-rusty-v8/Cargo.lock', 'upstream-rusty-v8/build.rs', 'upstream-rusty-v8/git_submodule_status.txt', 'patches/v8_array_sort_elements_kind.patch') }} - restore-keys: | - rusty-v8-source-${{ matrix.target }}-${{ matrix.runner }}-sandbox- - - - name: Apply V8 Array.sort backport - shell: bash - working-directory: upstream-rusty-v8/v8 - run: git apply -p3 "${GITHUB_WORKSPACE}/patches/v8_array_sort_elements_kind.patch" - - - name: Install sccache - uses: taiki-e/install-action@44c6d64aa62cd779e873306675c7a58e86d6d532 # v2.62.49 - with: - tool: sccache@0.8.2 - - - name: Start sccache - shell: pwsh - env: - SCCACHE_CACHE_SIZE: 256M - SCCACHE_DIR: ${{ steps.setup_ci.outputs.cargo-target-dir }}/sccache - SCCACHE_IDLE_TIMEOUT: 0 - run: sccache --start-server - - - name: Install Chromium clang for ARM64 MSVC cross build - if: matrix.target == 'aarch64-pc-windows-msvc' - shell: bash - working-directory: upstream-rusty-v8 - run: python3 tools/clang/scripts/update.py - - - name: Build upstream rusty_v8 sandbox release pair - env: - SCCACHE_IDLE_TIMEOUT: 0 - TARGET: ${{ matrix.target }} - V8_FROM_SOURCE: "1" - shell: bash - working-directory: upstream-rusty-v8 - run: cargo +1.91.0 build --locked --release --target "${TARGET}" --features v8_enable_sandbox - - - name: Stage upstream sandbox release pair - env: - TARGET: ${{ matrix.target }} - shell: bash - run: | - set -euo pipefail - python3 .github/scripts/rusty_v8_bazel.py stage-upstream-release-pair \ - --target-dir "${CARGO_TARGET_DIR}" \ - --target "${TARGET}" \ - --output-dir "dist/${TARGET}" \ - --sandbox - - - name: Smoke link staged artifact with Cargo - env: - TARGET: ${{ matrix.target }} - shell: bash - run: | - set -euo pipefail - - archive="$(find "dist/${TARGET}" -maxdepth 1 -type f -name 'rusty_v8_*.lib.gz' -print -quit)" - binding="$(find "dist/${TARGET}" -maxdepth 1 -type f -name 'src_binding_*.rs' -print -quit)" - if [[ -z "${archive}" || -z "${binding}" ]]; then - echo "Missing staged archive or binding for ${TARGET}." >&2 - exit 1 - fi - - ( - cd codex-rs - RUSTY_V8_ARCHIVE="${GITHUB_WORKSPACE}/${archive}" \ - RUSTY_V8_SRC_BINDING_PATH="${GITHUB_WORKSPACE}/${binding}" \ - cargo +1.95.0 test -p codex-v8-poc --target "${TARGET}" --features sandbox --no-run - ) - - - name: Upload staged artifacts - uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7 - with: - name: v8-canary-${{ needs.metadata.outputs.v8_version }}-ptrcomp-sandbox-${{ matrix.target }} - path: dist/${{ matrix.target }}/* - - - name: Check for a clean worktree - if: always() && !cancelled() - uses: ./.github/actions/check-clean-worktree diff --git a/.gitignore b/.gitignore index dbcd8633154a..a9529eca2a25 100644 --- a/.gitignore +++ b/.gitignore @@ -42,6 +42,7 @@ AGENTS.override.md .nyc_output/ .jest/ *.tsbuildinfo +.zig-cache/ # logs *.log diff --git a/MODULE.bazel.lock b/MODULE.bazel.lock index 834f2c1f34e9..eb2ce849b8d1 100644 --- a/MODULE.bazel.lock +++ b/MODULE.bazel.lock @@ -1597,7 +1597,7 @@ "libm_0.2.16": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"no-panic\",\"req\":\"^0.1.35\"}],\"features\":{\"arch\":[],\"default\":[\"arch\"],\"force-soft-floats\":[],\"unstable\":[\"unstable-intrinsics\",\"unstable-float\"],\"unstable-float\":[],\"unstable-intrinsics\":[],\"unstable-public-internals\":[]}}", "libredox_0.1.12": "{\"dependencies\":[{\"name\":\"bitflags\",\"req\":\"^2\"},{\"name\":\"ioslice\",\"optional\":true,\"req\":\"^0.6\"},{\"name\":\"libc\",\"req\":\"^0.2\"},{\"name\":\"redox_syscall\",\"optional\":true,\"req\":\"^0.7\"}],\"features\":{\"call\":[],\"default\":[\"call\",\"std\",\"redox_syscall\"],\"mkns\":[\"ioslice\"],\"std\":[]}}", "libredox_0.1.14": "{\"dependencies\":[{\"name\":\"bitflags\",\"optional\":true,\"req\":\"^2\"},{\"name\":\"ioslice\",\"optional\":true,\"req\":\"^0.6\"},{\"name\":\"libc\",\"optional\":true,\"req\":\"^0.2\"},{\"name\":\"plain\",\"optional\":true,\"req\":\"^0.2\"},{\"name\":\"redox_syscall\",\"optional\":true,\"req\":\"^0.7\"}],\"features\":{\"base\":[\"libc\"],\"call\":[\"base\"],\"default\":[\"base\",\"call\",\"std\",\"redox_syscall\",\"protocol\"],\"mkns\":[\"ioslice\"],\"protocol\":[\"plain\",\"bitflags\",\"redox_syscall\"],\"std\":[\"base\"]}}", - "libsqlite3-sys_0.37.0": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"runtime\"],\"kind\":\"build\",\"name\":\"bindgen\",\"optional\":true,\"req\":\"^0.72\"},{\"kind\":\"build\",\"name\":\"cc\",\"optional\":true,\"req\":\"^1.2.27\"},{\"name\":\"openssl-sys\",\"optional\":true,\"req\":\"^0.9.103\"},{\"kind\":\"build\",\"name\":\"pkg-config\",\"optional\":true,\"req\":\"^0.3.19\"},{\"kind\":\"build\",\"name\":\"prettyplease\",\"optional\":true,\"req\":\"^0.2.20\"},{\"default_features\":false,\"kind\":\"build\",\"name\":\"quote\",\"optional\":true,\"req\":\"^1.0.36\"},{\"features\":[\"full\",\"extra-traits\",\"visit-mut\"],\"kind\":\"build\",\"name\":\"syn\",\"optional\":true,\"req\":\"^2.0.89\"},{\"kind\":\"build\",\"name\":\"vcpkg\",\"optional\":true,\"req\":\"^0.2.15\"}],\"features\":{\"buildtime_bindgen\":[\"bindgen\",\"pkg-config\",\"vcpkg\"],\"bundled\":[\"cc\",\"bundled_bindings\"],\"bundled-sqlcipher\":[\"bundled\"],\"bundled-sqlcipher-vendored-openssl\":[\"bundled-sqlcipher\",\"openssl-sys/vendored\"],\"bundled-windows\":[\"cc\",\"bundled_bindings\"],\"bundled_bindings\":[],\"column_metadata\":[],\"default\":[\"min_sqlite_version_3_34_1\"],\"in_gecko\":[],\"loadable_extension\":[\"prettyplease\",\"quote\",\"syn\"],\"min_sqlite_version_3_34_1\":[\"pkg-config\",\"vcpkg\"],\"preupdate_hook\":[\"buildtime_bindgen\"],\"session\":[\"preupdate_hook\",\"buildtime_bindgen\"],\"sqlcipher\":[],\"unlock_notify\":[],\"wasm32-wasi-vfs\":[],\"with-asan\":[]}}", + "libsqlite3-sys_0.39.1": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"runtime\"],\"kind\":\"build\",\"name\":\"bindgen\",\"optional\":true,\"req\":\"^0.73\"},{\"kind\":\"build\",\"name\":\"cc\",\"optional\":true,\"req\":\"^1.2.27\"},{\"name\":\"openssl-sys\",\"optional\":true,\"req\":\"^0.9.103\"},{\"kind\":\"build\",\"name\":\"pkg-config\",\"optional\":true,\"req\":\"^0.3.19\"},{\"kind\":\"build\",\"name\":\"prettyplease\",\"optional\":true,\"req\":\"^0.3.0\"},{\"default_features\":false,\"kind\":\"build\",\"name\":\"quote\",\"optional\":true,\"req\":\"^1.0.36\"},{\"kind\":\"build\",\"name\":\"sqlcipher-src\",\"optional\":true,\"req\":\"=419.0.6\"},{\"features\":[\"full\",\"extra-traits\",\"visit-mut\"],\"kind\":\"build\",\"name\":\"syn\",\"optional\":true,\"req\":\"^3.0.1\"},{\"kind\":\"build\",\"name\":\"vcpkg\",\"optional\":true,\"req\":\"^0.2.15\"}],\"features\":{\"buildtime_bindgen\":[\"bindgen\",\"pkg-config\",\"vcpkg\"],\"bundled\":[\"cc\",\"bundled_bindings\"],\"bundled-sqlcipher\":[\"bundled\",\"dep:sqlcipher-src\"],\"bundled-sqlcipher-vendored-openssl\":[\"bundled-sqlcipher\",\"openssl-sys/vendored\"],\"bundled-windows\":[\"cc\",\"bundled_bindings\"],\"bundled_bindings\":[],\"column_metadata\":[],\"default\":[\"min_sqlite_version_3_45_3\"],\"in_gecko\":[],\"loadable_extension\":[\"prettyplease\",\"quote\",\"syn\"],\"min_sqlite_version_3_45_3\":[\"pkg-config\",\"vcpkg\"],\"preupdate_hook\":[\"buildtime_bindgen\"],\"session\":[\"preupdate_hook\",\"buildtime_bindgen\"],\"sqlcipher\":[],\"unlock_notify\":[],\"wasm32-wasi-vfs\":[],\"with-asan\":[]}}", "libz-sys_1.1.25": "{\"dependencies\":[{\"kind\":\"build\",\"name\":\"cc\",\"req\":\"^1.0.98\"},{\"kind\":\"build\",\"name\":\"cmake\",\"optional\":true,\"req\":\"^0.1.50\"},{\"name\":\"libc\",\"optional\":true,\"req\":\"^0.2.43\"},{\"kind\":\"build\",\"name\":\"pkg-config\",\"req\":\"^0.3.9\"},{\"kind\":\"build\",\"name\":\"vcpkg\",\"req\":\"^0.2.11\"}],\"features\":{\"asm\":[],\"default\":[\"libc\",\"stock-zlib\"],\"static\":[],\"stock-zlib\":[],\"zlib-ng\":[\"libc\",\"cmake\"],\"zlib-ng-no-cmake-experimental-community-maintained\":[\"libc\"]}}", "libz-sys_1.1.31": "{\"dependencies\":[{\"kind\":\"build\",\"name\":\"cc\",\"req\":\"^1.0.98\"},{\"kind\":\"build\",\"name\":\"cmake\",\"optional\":true,\"req\":\"^0.1.50\"},{\"name\":\"libc\",\"optional\":true,\"req\":\"^0.2.43\"},{\"kind\":\"build\",\"name\":\"pkg-config\",\"req\":\"^0.3.9\"},{\"kind\":\"build\",\"name\":\"vcpkg\",\"req\":\"^0.2.11\"}],\"features\":{\"asm\":[],\"default\":[\"libc\",\"stock-zlib\"],\"static\":[],\"stock-zlib\":[],\"zlib-ng\":[\"libc\",\"cmake\"],\"zlib-ng-no-cmake-experimental-community-maintained\":[\"libc\"]}}", "line-clipping_0.3.7": "{\"dependencies\":[{\"name\":\"bitflags\",\"req\":\"^2.11\"},{\"kind\":\"dev\",\"name\":\"rstest\",\"req\":\"^0.26\"}],\"features\":{}}", @@ -1717,8 +1717,8 @@ "openssl-probe_0.1.6": "{\"dependencies\":[],\"features\":{}}", "openssl-probe_0.2.1": "{\"dependencies\":[],\"features\":{}}", "openssl-src_300.6.1+3.6.3": "{\"dependencies\":[{\"name\":\"cc\",\"req\":\"^1.0.79\"}],\"features\":{\"camellia\":[],\"default\":[],\"force-engine\":[],\"idea\":[],\"ktls\":[],\"legacy\":[],\"no-dso\":[],\"seed\":[],\"ssl3\":[],\"weak-crypto\":[]}}", - "openssl-sys_0.9.111": "{\"dependencies\":[{\"features\":[\"ssl\",\"bindgen\"],\"name\":\"aws-lc-fips-sys\",\"optional\":true,\"req\":\"^0.13\"},{\"features\":[\"ssl\"],\"name\":\"aws-lc-sys\",\"optional\":true,\"req\":\"^0.27\"},{\"features\":[\"experimental\"],\"kind\":\"build\",\"name\":\"bindgen\",\"optional\":true,\"req\":\"^0.72.0\"},{\"name\":\"bssl-sys\",\"optional\":true,\"req\":\"^0.1.0\"},{\"kind\":\"build\",\"name\":\"cc\",\"req\":\"^1.0.61\"},{\"name\":\"libc\",\"req\":\"^0.2\"},{\"features\":[\"legacy\"],\"kind\":\"build\",\"name\":\"openssl-src\",\"optional\":true,\"req\":\"^300.2.0\"},{\"kind\":\"build\",\"name\":\"pkg-config\",\"req\":\"^0.3.9\"},{\"kind\":\"build\",\"name\":\"vcpkg\",\"req\":\"^0.2.8\"}],\"features\":{\"aws-lc\":[\"dep:aws-lc-sys\"],\"aws-lc-fips\":[\"dep:aws-lc-fips-sys\"],\"unstable_boringssl\":[\"bssl-sys\"],\"vendored\":[\"openssl-src\"]}}", - "openssl_0.10.75": "{\"dependencies\":[{\"name\":\"bitflags\",\"req\":\"^2.2.1\"},{\"name\":\"cfg-if\",\"req\":\"^1.0\"},{\"name\":\"ffi\",\"package\":\"openssl-sys\",\"req\":\"^0.9.111\"},{\"name\":\"foreign-types\",\"req\":\"^0.3.1\"},{\"kind\":\"dev\",\"name\":\"hex\",\"req\":\"^0.4\"},{\"name\":\"libc\",\"req\":\"^0.2\"},{\"name\":\"once_cell\",\"req\":\"^1.5.2\"},{\"name\":\"openssl-macros\",\"req\":\"^0.1.1\"}],\"features\":{\"aws-lc\":[\"ffi/aws-lc\"],\"aws-lc-fips\":[\"ffi/aws-lc-fips\"],\"bindgen\":[\"ffi/bindgen\"],\"default\":[],\"unstable_boringssl\":[\"ffi/unstable_boringssl\"],\"v101\":[],\"v102\":[],\"v110\":[],\"v111\":[],\"vendored\":[\"ffi/vendored\"]}}", + "openssl-sys_0.9.116": "{\"dependencies\":[{\"features\":[\"ssl\",\"bindgen\"],\"name\":\"aws-lc-fips-sys\",\"optional\":true,\"req\":\"^0.13\"},{\"features\":[\"ssl\"],\"name\":\"aws-lc-sys\",\"optional\":true,\"req\":\"^0.39\"},{\"features\":[\"experimental\"],\"kind\":\"build\",\"name\":\"bindgen\",\"optional\":true,\"req\":\"^0.72.0\"},{\"name\":\"bssl-sys\",\"optional\":true,\"req\":\"^0.1.0\"},{\"kind\":\"build\",\"name\":\"cc\",\"req\":\"^1.0.61\"},{\"name\":\"libc\",\"req\":\"^0.2\"},{\"features\":[\"legacy\"],\"kind\":\"build\",\"name\":\"openssl-src\",\"optional\":true,\"req\":\"^300.2.0\"},{\"kind\":\"build\",\"name\":\"pkg-config\",\"req\":\"^0.3.9\"},{\"kind\":\"build\",\"name\":\"vcpkg\",\"req\":\"^0.2.8\"}],\"features\":{\"aws-lc\":[\"dep:aws-lc-sys\"],\"aws-lc-fips\":[\"dep:aws-lc-fips-sys\"],\"unstable_boringssl\":[\"bssl-sys\"],\"vendored\":[\"openssl-src\"]}}", + "openssl_0.10.80": "{\"dependencies\":[{\"name\":\"bitflags\",\"req\":\"^2.2.1\"},{\"name\":\"cfg-if\",\"req\":\"^1.0\"},{\"name\":\"ffi\",\"package\":\"openssl-sys\",\"req\":\"^0.9.116\"},{\"name\":\"foreign-types\",\"req\":\"^0.3.1\"},{\"kind\":\"dev\",\"name\":\"hex\",\"req\":\"^0.4\"},{\"name\":\"libc\",\"req\":\"^0.2\"},{\"name\":\"once_cell\",\"req\":\"^1.5.2\"},{\"name\":\"openssl-macros\",\"req\":\"^0.1.1\"}],\"features\":{\"aws-lc\":[\"ffi/aws-lc\"],\"aws-lc-fips\":[\"ffi/aws-lc-fips\"],\"bindgen\":[\"ffi/bindgen\"],\"default\":[],\"unstable_boringssl\":[\"ffi/unstable_boringssl\"],\"v101\":[],\"v102\":[],\"v110\":[],\"v111\":[],\"vendored\":[\"ffi/vendored\"]}}", "opentelemetry-appender-tracing_0.31.1": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5\"},{\"name\":\"log\",\"optional\":true,\"req\":\"^0.4.21\"},{\"kind\":\"dev\",\"name\":\"log\",\"req\":\"^0.4.21\"},{\"default_features\":false,\"features\":[\"logs\"],\"name\":\"opentelemetry\",\"req\":\"^0.31\"},{\"default_features\":false,\"features\":[\"logs\"],\"kind\":\"dev\",\"name\":\"opentelemetry-stdout\",\"req\":\"^0.31\"},{\"default_features\":false,\"features\":[\"logs\",\"testing\",\"internal-logs\"],\"kind\":\"dev\",\"name\":\"opentelemetry_sdk\",\"req\":\"^0.31\"},{\"features\":[\"flamegraph\",\"criterion\"],\"kind\":\"dev\",\"name\":\"pprof\",\"req\":\"^0.14\",\"target\":\"cfg(not(target_os = \\\"windows\\\"))\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"tracing\",\"req\":\">=0.1.40\"},{\"default_features\":false,\"features\":[\"std\"],\"kind\":\"dev\",\"name\":\"tracing\",\"req\":\">=0.1.40\"},{\"default_features\":false,\"name\":\"tracing-core\",\"req\":\">=0.1.33\"},{\"name\":\"tracing-log\",\"optional\":true,\"req\":\"^0.2\"},{\"kind\":\"dev\",\"name\":\"tracing-log\",\"req\":\"^0.2\"},{\"name\":\"tracing-opentelemetry\",\"optional\":true,\"req\":\"^0.32\"},{\"default_features\":false,\"features\":[\"registry\",\"std\"],\"name\":\"tracing-subscriber\",\"req\":\"^0.3\"},{\"default_features\":false,\"features\":[\"env-filter\",\"registry\",\"std\",\"fmt\"],\"kind\":\"dev\",\"name\":\"tracing-subscriber\",\"req\":\"^0.3\"}],\"features\":{\"default\":[],\"experimental_metadata_attributes\":[\"dep:tracing-log\"],\"experimental_use_tracing_span_context\":[\"tracing-opentelemetry\"],\"spec_unstable_logs_enabled\":[\"opentelemetry/spec_unstable_logs_enabled\"]}}", "opentelemetry-http_0.31.0": "{\"dependencies\":[{\"name\":\"async-trait\",\"req\":\"^0.1\"},{\"name\":\"bytes\",\"req\":\"^1\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"http\",\"req\":\"^1.1\"},{\"name\":\"http-body-util\",\"optional\":true,\"req\":\"^0.1\"},{\"default_features\":false,\"name\":\"hyper\",\"optional\":true,\"req\":\"^1.3\"},{\"features\":[\"client-legacy\",\"http1\",\"http2\"],\"name\":\"hyper-util\",\"optional\":true,\"req\":\"^0.1\"},{\"default_features\":false,\"features\":[\"trace\"],\"name\":\"opentelemetry\",\"req\":\"^0.31\"},{\"default_features\":false,\"name\":\"reqwest\",\"optional\":true,\"req\":\"^0.12\"},{\"default_features\":false,\"features\":[\"time\"],\"name\":\"tokio\",\"optional\":true,\"req\":\"^1\"}],\"features\":{\"default\":[\"internal-logs\"],\"hyper\":[\"dep:http-body-util\",\"dep:hyper\",\"dep:hyper-util\",\"dep:tokio\"],\"internal-logs\":[\"opentelemetry/internal-logs\"],\"reqwest\":[\"dep:reqwest\"],\"reqwest-blocking\":[\"dep:reqwest\",\"reqwest/blocking\"],\"reqwest-rustls\":[\"dep:reqwest\",\"reqwest/rustls-tls-native-roots\"],\"reqwest-rustls-webpki-roots\":[\"dep:reqwest\",\"reqwest/rustls-tls-webpki-roots\"]}}", "opentelemetry-otlp_0.31.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"async-trait\",\"req\":\"^0.1\"},{\"name\":\"flate2\",\"optional\":true,\"req\":\"^1.1.2\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"futures-util\",\"req\":\"^0.3\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"http\",\"optional\":true,\"req\":\"^1.1\"},{\"default_features\":false,\"name\":\"opentelemetry\",\"req\":\"^0.31\"},{\"default_features\":false,\"name\":\"opentelemetry-http\",\"optional\":true,\"req\":\"^0.31\"},{\"default_features\":false,\"name\":\"opentelemetry-proto\",\"req\":\"^0.31\"},{\"default_features\":false,\"name\":\"opentelemetry_sdk\",\"req\":\"^0.31\"},{\"default_features\":false,\"features\":[\"trace\",\"testing\"],\"kind\":\"dev\",\"name\":\"opentelemetry_sdk\",\"req\":\"^0.31\"},{\"name\":\"prost\",\"optional\":true,\"req\":\"^0.14\"},{\"default_features\":false,\"name\":\"reqwest\",\"optional\":true,\"req\":\"^0.12\"},{\"default_features\":false,\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"serde_json\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"temp-env\",\"req\":\"^0.3.6\"},{\"default_features\":false,\"name\":\"thiserror\",\"req\":\"^2\"},{\"default_features\":false,\"features\":[\"sync\",\"rt\"],\"name\":\"tokio\",\"optional\":true,\"req\":\"^1\"},{\"default_features\":false,\"features\":[\"macros\",\"rt-multi-thread\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"features\":[\"net\"],\"kind\":\"dev\",\"name\":\"tokio-stream\",\"req\":\"^0.1\"},{\"default_features\":false,\"name\":\"tonic\",\"optional\":true,\"req\":\"^0.14.1\"},{\"default_features\":false,\"features\":[\"router\",\"server\"],\"kind\":\"dev\",\"name\":\"tonic\",\"req\":\"^0.14.1\"},{\"default_features\":false,\"name\":\"tracing\",\"optional\":true,\"req\":\">=0.1.40\"},{\"name\":\"zstd\",\"optional\":true,\"req\":\"^0.13\"}],\"features\":{\"default\":[\"http-proto\",\"reqwest-blocking-client\",\"trace\",\"metrics\",\"logs\",\"internal-logs\"],\"grpc-tonic\":[\"tonic\",\"prost\",\"http\",\"tokio\",\"opentelemetry-proto/gen-tonic\"],\"gzip-http\":[\"flate2\"],\"gzip-tonic\":[\"tonic/gzip\"],\"http-json\":[\"serde_json\",\"prost\",\"opentelemetry-http\",\"opentelemetry-proto/gen-tonic-messages\",\"opentelemetry-proto/with-serde\",\"http\",\"trace\",\"metrics\"],\"http-proto\":[\"prost\",\"opentelemetry-http\",\"opentelemetry-proto/gen-tonic-messages\",\"http\",\"trace\",\"metrics\"],\"hyper-client\":[\"opentelemetry-http/hyper\"],\"integration-testing\":[\"tonic\",\"prost\",\"tokio/full\",\"trace\",\"logs\"],\"internal-logs\":[\"tracing\",\"opentelemetry_sdk/internal-logs\",\"opentelemetry-http/internal-logs\"],\"logs\":[\"opentelemetry/logs\",\"opentelemetry_sdk/logs\",\"opentelemetry-proto/logs\"],\"metrics\":[\"opentelemetry/metrics\",\"opentelemetry_sdk/metrics\",\"opentelemetry-proto/metrics\"],\"reqwest-blocking-client\":[\"reqwest/blocking\",\"opentelemetry-http/reqwest-blocking\"],\"reqwest-client\":[\"reqwest\",\"opentelemetry-http/reqwest\"],\"reqwest-rustls\":[\"reqwest\",\"opentelemetry-http/reqwest-rustls\"],\"reqwest-rustls-webpki-roots\":[\"reqwest\",\"opentelemetry-http/reqwest-rustls-webpki-roots\"],\"serialize\":[\"serde\",\"serde_json\"],\"tls\":[\"tonic/tls-ring\"],\"tls-roots\":[\"tls\",\"tonic/tls-native-roots\"],\"tls-webpki-roots\":[\"tls\",\"tonic/tls-webpki-roots\"],\"trace\":[\"opentelemetry/trace\",\"opentelemetry_sdk/trace\",\"opentelemetry-proto/trace\"],\"zstd-http\":[\"zstd\"],\"zstd-tonic\":[\"tonic/zstd\"]}}", @@ -1748,6 +1748,7 @@ "paste_1.0.15": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"paste-test-suite\",\"req\":\"^0\"},{\"kind\":\"dev\",\"name\":\"rustversion\",\"req\":\"^1.0\"},{\"features\":[\"diff\"],\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0.49\"}],\"features\":{}}", "pastey_0.2.1": "{\"dependencies\":[],\"features\":{}}", "pastey_0.2.3": "{\"dependencies\":[],\"features\":{}}", + "path+crates/../vendor/sqlx-sqlite_sqlx-sqlite": "{\"dependencies\":[{\"default_features\":true,\"features\":[],\"name\":\"atoi\",\"optional\":false,\"req\":\"2.0\"},{\"default_features\":false,\"features\":[\"std\",\"clock\"],\"name\":\"chrono\",\"optional\":true,\"req\":\"0.4.34\"},{\"default_features\":false,\"features\":[\"async\"],\"name\":\"flume\",\"optional\":false,\"req\":\"0.12.0\"},{\"default_features\":true,\"features\":[],\"name\":\"form_urlencoded\",\"optional\":false,\"req\":\"1.2.2\"},{\"default_features\":false,\"features\":[\"sink\",\"alloc\",\"std\"],\"name\":\"futures-channel\",\"optional\":false,\"req\":\"0.3.32\"},{\"default_features\":false,\"features\":[],\"name\":\"futures-core\",\"optional\":false,\"req\":\"0.3.32\"},{\"default_features\":true,\"features\":[],\"name\":\"futures-executor\",\"optional\":false,\"req\":\"0.3.32\"},{\"default_features\":true,\"features\":[],\"name\":\"futures-intrusive\",\"optional\":false,\"req\":\"0.5.0\"},{\"default_features\":false,\"features\":[\"alloc\",\"sink\"],\"name\":\"futures-util\",\"optional\":false,\"req\":\"0.3.32\"},{\"default_features\":false,\"features\":[\"pkg-config\",\"vcpkg\"],\"name\":\"libsqlite3-sys\",\"optional\":false,\"req\":\">=0.30.1, <0.40.0\"},{\"default_features\":true,\"features\":[],\"name\":\"log\",\"optional\":false,\"req\":\"0.4.18\"},{\"default_features\":true,\"features\":[],\"name\":\"percent-encoding\",\"optional\":false,\"req\":\"2.3.0\"},{\"default_features\":true,\"features\":[],\"name\":\"regex\",\"optional\":true,\"req\":\"1.6.0\"},{\"default_features\":true,\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"1.0.219\"},{\"default_features\":true,\"features\":[],\"name\":\"sqlx-core\",\"optional\":false,\"req\":\"=0.9.0\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"thiserror\",\"optional\":false,\"req\":\"2.0.18\"},{\"default_features\":true,\"features\":[\"formatting\",\"parsing\",\"macros\"],\"name\":\"time\",\"optional\":true,\"req\":\"0.3.47\"},{\"default_features\":true,\"features\":[\"log\"],\"name\":\"tracing\",\"optional\":false,\"req\":\"0.1.37\"},{\"default_features\":true,\"features\":[],\"name\":\"url\",\"optional\":false,\"req\":\"2.2.2\"},{\"default_features\":true,\"features\":[],\"name\":\"uuid\",\"optional\":true,\"req\":\"1.12.1\"}],\"features\":{\"_unstable-all-sqlite-features\":[\"deserialize\",\"load-extension\",\"preupdate-hook\",\"unlock-notify\"],\"_unstable-all-types\":[\"json\",\"chrono\",\"time\",\"uuid\"],\"_unstable-docs\":[\"bundled\",\"any\",\"_unstable-all-types\",\"_unstable-all-sqlite-features\"],\"any\":[\"sqlx-core/any\"],\"bigdecimal\":[],\"bundled\":[\"libsqlite3-sys/bundled\"],\"chrono\":[\"dep:chrono\",\"sqlx-core/chrono\"],\"deserialize\":[],\"json\":[\"sqlx-core/json\",\"serde\"],\"load-extension\":[],\"migrate\":[\"sqlx-core/migrate\"],\"offline\":[\"sqlx-core/offline\",\"serde\"],\"preupdate-hook\":[\"libsqlite3-sys/preupdate_hook\"],\"regexp\":[\"dep:regex\"],\"rust_decimal\":[],\"sqlx-toml\":[\"sqlx-core/sqlx-toml\"],\"time\":[\"dep:time\",\"sqlx-core/time\"],\"unbundled\":[\"libsqlite3-sys/buildtime_bindgen\"],\"unlock-notify\":[\"libsqlite3-sys/unlock_notify\"],\"uuid\":[\"dep:uuid\",\"sqlx-core/uuid\"]},\"strip_prefix\":\"\"}", "pathdiff_0.2.3": "{\"dependencies\":[{\"name\":\"camino\",\"optional\":true,\"req\":\"^1.0.5\"},{\"kind\":\"dev\",\"name\":\"cfg-if\",\"req\":\"^1.0.0\"}],\"features\":{}}", "pbkdf2_0.12.2": "{\"dependencies\":[{\"features\":[\"mac\"],\"name\":\"digest\",\"req\":\"^0.10.7\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.4.0\"},{\"default_features\":false,\"name\":\"hmac\",\"optional\":true,\"req\":\"^0.12\"},{\"kind\":\"dev\",\"name\":\"hmac\",\"req\":\"^0.12\"},{\"default_features\":false,\"features\":[\"rand_core\"],\"name\":\"password-hash\",\"optional\":true,\"req\":\"^0.5\"},{\"name\":\"rayon\",\"optional\":true,\"req\":\"^1.7\"},{\"default_features\":false,\"name\":\"sha1\",\"optional\":true,\"req\":\"^0.10\"},{\"kind\":\"dev\",\"name\":\"sha1\",\"req\":\"^0.10\"},{\"default_features\":false,\"name\":\"sha2\",\"optional\":true,\"req\":\"^0.10\"},{\"kind\":\"dev\",\"name\":\"sha2\",\"req\":\"^0.10\"},{\"kind\":\"dev\",\"name\":\"streebog\",\"req\":\"^0.10\"}],\"features\":{\"default\":[\"hmac\"],\"parallel\":[\"rayon\",\"std\"],\"simple\":[\"hmac\",\"password-hash\",\"sha2\"],\"std\":[\"password-hash/std\"]}}", "pbkdf2_0.13.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"belt-hash\",\"req\":\"^0.2\"},{\"features\":[\"mac\"],\"name\":\"digest\",\"req\":\"^0.11\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^1\"},{\"default_features\":false,\"name\":\"hmac\",\"optional\":true,\"req\":\"^0.13\"},{\"kind\":\"dev\",\"name\":\"hmac\",\"req\":\"^0.13\"},{\"name\":\"kdf\",\"optional\":true,\"req\":\"^0.1\"},{\"default_features\":false,\"features\":[\"base64\"],\"name\":\"mcf\",\"optional\":true,\"req\":\"^0.6\"},{\"default_features\":false,\"name\":\"password-hash\",\"optional\":true,\"req\":\"^0.6\"},{\"kind\":\"dev\",\"name\":\"sha1\",\"req\":\"^0.11\"},{\"default_features\":false,\"name\":\"sha2\",\"optional\":true,\"req\":\"^0.11\"},{\"kind\":\"dev\",\"name\":\"sha2\",\"req\":\"^0.11\"},{\"kind\":\"dev\",\"name\":\"streebog\",\"req\":\"^0.11\"}],\"features\":{\"alloc\":[\"mcf?/alloc\",\"password-hash?/alloc\"],\"default\":[\"hmac\"],\"getrandom\":[\"password-hash/getrandom\"],\"kdf\":[\"sha2\",\"dep:kdf\"],\"mcf\":[\"sha2\",\"password-hash\",\"dep:mcf\"],\"phc\":[\"password-hash/phc\",\"sha2\"],\"rand_core\":[\"password-hash/rand_core\"],\"sha2\":[\"hmac\",\"dep:sha2\"]}}", @@ -2050,7 +2051,6 @@ "sqlx-macros_0.9.0": "{\"dependencies\":[{\"default_features\":false,\"name\":\"proc-macro2\",\"req\":\"^1.0.83\"},{\"default_features\":false,\"name\":\"quote\",\"req\":\"^1.0.35\"},{\"features\":[\"any\"],\"name\":\"sqlx-core\",\"req\":\"=0.9.0\"},{\"name\":\"sqlx-macros-core\",\"req\":\"=0.9.0\"},{\"default_features\":false,\"features\":[\"parsing\",\"proc-macro\"],\"name\":\"syn\",\"req\":\"^2.0.87\"}],\"features\":{\"_rt-async-global-executor\":[\"sqlx-macros-core/_rt-async-global-executor\"],\"_rt-async-std\":[\"sqlx-macros-core/_rt-async-std\"],\"_rt-smol\":[\"sqlx-macros-core/_rt-smol\"],\"_rt-tokio\":[\"sqlx-macros-core/_rt-tokio\"],\"_tls-native-tls\":[\"sqlx-macros-core/_tls-native-tls\"],\"_tls-rustls-aws-lc-rs\":[\"sqlx-macros-core/_tls-rustls-aws-lc-rs\"],\"_tls-rustls-ring-native-roots\":[\"sqlx-macros-core/_tls-rustls-ring-native-roots\"],\"_tls-rustls-ring-webpki\":[\"sqlx-macros-core/_tls-rustls-ring-webpki\"],\"bigdecimal\":[\"sqlx-macros-core/bigdecimal\"],\"bit-vec\":[\"sqlx-macros-core/bit-vec\"],\"chrono\":[\"sqlx-macros-core/chrono\"],\"default\":[],\"derive\":[\"sqlx-macros-core/derive\"],\"ipnet\":[\"sqlx-macros-core/ipnet\"],\"ipnetwork\":[\"sqlx-macros-core/ipnetwork\"],\"json\":[\"sqlx-macros-core/json\"],\"mac_address\":[\"sqlx-macros-core/mac_address\"],\"macros\":[\"sqlx-macros-core/macros\"],\"migrate\":[\"sqlx-macros-core/migrate\"],\"mysql\":[\"sqlx-macros-core/mysql\"],\"mysql-rsa\":[\"sqlx-macros-core/mysql-rsa\"],\"postgres\":[\"sqlx-macros-core/postgres\"],\"rust_decimal\":[\"sqlx-macros-core/rust_decimal\"],\"sqlite\":[\"sqlx-macros-core/sqlite\"],\"sqlite-load-extension\":[\"sqlx-macros-core/sqlite-load-extension\"],\"sqlite-unbundled\":[\"sqlx-macros-core/sqlite-unbundled\"],\"sqlx-toml\":[\"sqlx-macros-core/sqlx-toml\"],\"time\":[\"sqlx-macros-core/time\"],\"uuid\":[\"sqlx-macros-core/uuid\"]}}", "sqlx-mysql_0.9.0": "{\"dependencies\":[{\"name\":\"bigdecimal\",\"optional\":true,\"req\":\"^0.4.0\"},{\"default_features\":false,\"name\":\"bitflags\",\"req\":\"^2.4\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"byteorder\",\"req\":\"^1.4.3\"},{\"name\":\"bytes\",\"req\":\"^1.2.0\"},{\"default_features\":false,\"features\":[\"std\",\"clock\"],\"name\":\"chrono\",\"optional\":true,\"req\":\"^0.4.34\"},{\"name\":\"crc\",\"optional\":true,\"req\":\"^3.0.0\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"digest\",\"req\":\"^0.11.2\"},{\"default_features\":false,\"name\":\"dotenvy\",\"req\":\"^0.15.7\"},{\"name\":\"either\",\"req\":\"^1.6.1\"},{\"default_features\":false,\"name\":\"futures-core\",\"req\":\"^0.3.32\"},{\"default_features\":false,\"features\":[\"alloc\",\"sink\",\"io\"],\"name\":\"futures-util\",\"req\":\"^0.3.32\"},{\"default_features\":false,\"name\":\"generic-array\",\"req\":\"^0.14.4\"},{\"name\":\"log\",\"req\":\"^0.4.18\"},{\"name\":\"percent-encoding\",\"req\":\"^2.3.0\"},{\"default_features\":false,\"features\":[\"thread_rng\"],\"name\":\"rand\",\"optional\":true,\"req\":\"^0.10.1\"},{\"name\":\"rsa\",\"optional\":true,\"req\":\"^0.10.0-rc.18\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"rust_decimal\",\"optional\":true,\"req\":\"^1.36.0\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.219\"},{\"default_features\":false,\"name\":\"sha1\",\"req\":\"^0.11.0\"},{\"default_features\":false,\"name\":\"sha2\",\"req\":\"^0.11.0\"},{\"name\":\"sqlx-core\",\"req\":\"=0.9.0\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"thiserror\",\"req\":\"^2.0.18\"},{\"features\":[\"formatting\",\"parsing\",\"macros\"],\"name\":\"time\",\"optional\":true,\"req\":\"^0.3.47\"},{\"features\":[\"log\"],\"name\":\"tracing\",\"req\":\"^0.1.37\"},{\"name\":\"uuid\",\"optional\":true,\"req\":\"^1.12.1\"}],\"features\":{\"any\":[\"sqlx-core/any\"],\"bigdecimal\":[\"dep:bigdecimal\",\"sqlx-core/bigdecimal\"],\"chrono\":[\"dep:chrono\",\"sqlx-core/chrono\"],\"default\":[],\"json\":[\"sqlx-core/json\",\"serde\"],\"migrate\":[\"sqlx-core/migrate\",\"dep:crc\"],\"offline\":[\"sqlx-core/offline\",\"serde/derive\",\"bitflags/serde\"],\"rsa\":[\"dep:rand\",\"dep:rsa\"],\"rust_decimal\":[\"dep:rust_decimal\",\"rust_decimal/maths\",\"sqlx-core/rust_decimal\"],\"time\":[\"dep:time\",\"sqlx-core/time\"],\"uuid\":[\"dep:uuid\",\"sqlx-core/uuid\"]}}", "sqlx-postgres_0.9.0": "{\"dependencies\":[{\"name\":\"atoi\",\"req\":\"^2.0\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"base64\",\"req\":\"^0.22.1\"},{\"name\":\"bigdecimal\",\"optional\":true,\"req\":\"^0.4.0\"},{\"name\":\"bit-vec\",\"optional\":true,\"req\":\"^0.8\"},{\"default_features\":false,\"name\":\"bitflags\",\"req\":\"^2.4\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"byteorder\",\"req\":\"^1.4.3\"},{\"default_features\":false,\"features\":[\"std\",\"clock\"],\"name\":\"chrono\",\"optional\":true,\"req\":\"^0.4.34\"},{\"name\":\"crc\",\"optional\":true,\"req\":\"^3.0.0\"},{\"default_features\":false,\"name\":\"dotenvy\",\"req\":\"^0.15.7\"},{\"name\":\"etcetera\",\"req\":\"^0.11.0\",\"target\":\"cfg(target_os = \\\"windows\\\")\"},{\"default_features\":false,\"features\":[\"sink\",\"alloc\",\"std\"],\"name\":\"futures-channel\",\"req\":\"^0.3.32\"},{\"default_features\":false,\"name\":\"futures-core\",\"req\":\"^0.3.32\"},{\"default_features\":false,\"features\":[\"alloc\",\"sink\",\"io\"],\"name\":\"futures-util\",\"req\":\"^0.3.32\"},{\"name\":\"hex\",\"req\":\"^0.4.3\"},{\"name\":\"hkdf\",\"req\":\"^0.13.0\"},{\"default_features\":false,\"name\":\"hmac\",\"req\":\"^0.13.0\"},{\"name\":\"ipnet\",\"optional\":true,\"req\":\"^2.3.0\"},{\"name\":\"ipnetwork\",\"optional\":true,\"req\":\"^0.21.1\"},{\"name\":\"itoa\",\"req\":\"^1.0.5\"},{\"name\":\"log\",\"req\":\"^0.4.18\"},{\"name\":\"mac_address\",\"optional\":true,\"req\":\"^1.1.5\"},{\"default_features\":false,\"name\":\"md-5\",\"req\":\"^0.11.0\"},{\"default_features\":false,\"name\":\"memchr\",\"req\":\"^2.5.0\"},{\"name\":\"num-bigint\",\"optional\":true,\"req\":\"^0.4.3\"},{\"default_features\":false,\"features\":[\"thread_rng\"],\"name\":\"rand\",\"req\":\"^0.10.1\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"rust_decimal\",\"optional\":true,\"req\":\"^1.36.0\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.219\"},{\"features\":[\"raw_value\"],\"name\":\"serde_json\",\"optional\":true,\"req\":\"^1.0.142\"},{\"default_features\":false,\"name\":\"sha2\",\"req\":\"^0.11.0\"},{\"name\":\"smallvec\",\"req\":\"^1.13.1\"},{\"name\":\"sqlx-core\",\"req\":\"=0.9.0\"},{\"name\":\"stringprep\",\"req\":\"^0.1.2\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"thiserror\",\"req\":\"^2.0.18\"},{\"features\":[\"formatting\",\"parsing\",\"macros\"],\"name\":\"time\",\"optional\":true,\"req\":\"^0.3.47\"},{\"features\":[\"log\"],\"name\":\"tracing\",\"req\":\"^0.1.37\"},{\"name\":\"uuid\",\"optional\":true,\"req\":\"^1.12.1\"},{\"default_features\":false,\"name\":\"whoami\",\"req\":\"^2.0.2\"}],\"features\":{\"any\":[\"sqlx-core/any\"],\"bigdecimal\":[\"dep:bigdecimal\",\"dep:num-bigint\",\"sqlx-core/bigdecimal\"],\"bit-vec\":[\"dep:bit-vec\",\"sqlx-core/bit-vec\"],\"chrono\":[\"dep:chrono\",\"sqlx-core/chrono\"],\"ipnet\":[\"dep:ipnet\",\"sqlx-core/ipnet\"],\"ipnetwork\":[\"dep:ipnetwork\",\"sqlx-core/ipnetwork\"],\"json\":[\"dep:serde\",\"dep:serde_json\",\"sqlx-core/json\"],\"mac_address\":[\"dep:mac_address\",\"sqlx-core/mac_address\"],\"migrate\":[\"sqlx-core/migrate\",\"dep:crc\"],\"offline\":[\"json\",\"sqlx-core/offline\",\"smallvec/serde\"],\"rust_decimal\":[\"dep:rust_decimal\",\"rust_decimal/maths\",\"sqlx-core/rust_decimal\"],\"time\":[\"dep:time\",\"sqlx-core/time\"],\"uuid\":[\"dep:uuid\",\"sqlx-core/uuid\"]}}", - "sqlx-sqlite_0.9.0": "{\"dependencies\":[{\"name\":\"atoi\",\"req\":\"^2.0\"},{\"default_features\":false,\"features\":[\"std\",\"clock\"],\"name\":\"chrono\",\"optional\":true,\"req\":\"^0.4.34\"},{\"default_features\":false,\"features\":[\"async\"],\"name\":\"flume\",\"req\":\"^0.12.0\"},{\"name\":\"form_urlencoded\",\"req\":\"^1.2.2\"},{\"default_features\":false,\"features\":[\"sink\",\"alloc\",\"std\"],\"name\":\"futures-channel\",\"req\":\"^0.3.32\"},{\"default_features\":false,\"name\":\"futures-core\",\"req\":\"^0.3.32\"},{\"name\":\"futures-executor\",\"req\":\"^0.3.32\"},{\"name\":\"futures-intrusive\",\"req\":\"^0.5.0\"},{\"default_features\":false,\"features\":[\"alloc\",\"sink\"],\"name\":\"futures-util\",\"req\":\"^0.3.32\"},{\"default_features\":false,\"features\":[\"pkg-config\",\"vcpkg\"],\"name\":\"libsqlite3-sys\",\"req\":\">=0.30.1, <0.38.0\"},{\"name\":\"log\",\"req\":\"^0.4.18\"},{\"name\":\"percent-encoding\",\"req\":\"^2.3.0\"},{\"name\":\"regex\",\"optional\":true,\"req\":\"^1.6.0\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.219\"},{\"name\":\"sqlx-core\",\"req\":\"=0.9.0\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"thiserror\",\"req\":\"^2.0.18\"},{\"features\":[\"formatting\",\"parsing\",\"macros\"],\"name\":\"time\",\"optional\":true,\"req\":\"^0.3.47\"},{\"features\":[\"log\"],\"name\":\"tracing\",\"req\":\"^0.1.37\"},{\"name\":\"url\",\"req\":\"^2.2.2\"},{\"name\":\"uuid\",\"optional\":true,\"req\":\"^1.12.1\"}],\"features\":{\"_unstable-all-sqlite-features\":[\"deserialize\",\"load-extension\",\"preupdate-hook\",\"unlock-notify\"],\"_unstable-all-types\":[\"json\",\"chrono\",\"time\",\"uuid\"],\"_unstable-docs\":[\"bundled\",\"any\",\"_unstable-all-types\",\"_unstable-all-sqlite-features\"],\"any\":[\"sqlx-core/any\"],\"bigdecimal\":[],\"bundled\":[\"libsqlite3-sys/bundled\"],\"chrono\":[\"dep:chrono\",\"sqlx-core/chrono\"],\"deserialize\":[],\"json\":[\"sqlx-core/json\",\"serde\"],\"load-extension\":[],\"migrate\":[\"sqlx-core/migrate\"],\"offline\":[\"sqlx-core/offline\",\"serde\"],\"preupdate-hook\":[\"libsqlite3-sys/preupdate_hook\"],\"regexp\":[\"dep:regex\"],\"rust_decimal\":[],\"sqlx-toml\":[\"sqlx-core/sqlx-toml\"],\"time\":[\"dep:time\",\"sqlx-core/time\"],\"unbundled\":[\"libsqlite3-sys/buildtime_bindgen\"],\"unlock-notify\":[\"libsqlite3-sys/unlock_notify\"],\"uuid\":[\"dep:uuid\",\"sqlx-core/uuid\"]}}", "sqlx_0.9.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"anyhow\",\"req\":\"^1.0.58\"},{\"features\":[\"attributes\"],\"kind\":\"dev\",\"name\":\"async-std\",\"req\":\"^1.13\"},{\"features\":[\"async_tokio\"],\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5.1\"},{\"kind\":\"dev\",\"name\":\"dotenvy\",\"req\":\"^0.15.7\"},{\"kind\":\"dev\",\"name\":\"env_logger\",\"req\":\"^0.11\"},{\"default_features\":false,\"features\":[\"alloc\"],\"kind\":\"dev\",\"name\":\"futures-util\",\"req\":\"^0.3.32\"},{\"kind\":\"dev\",\"name\":\"hex\",\"req\":\"^0.4.3\"},{\"kind\":\"dev\",\"name\":\"libsqlite3-sys\",\"req\":\"^0.37.0\"},{\"features\":[\"bundled-sqlcipher\"],\"kind\":\"dev\",\"name\":\"libsqlite3-sys\",\"req\":\"^0.37.0\",\"target\":\"cfg(sqlite_test_sqlcipher)\"},{\"kind\":\"dev\",\"name\":\"paste\",\"req\":\"^1.0.6\"},{\"default_features\":false,\"features\":[\"thread_rng\"],\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.10.1\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0.219\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.142\"},{\"features\":[\"migrate\"],\"name\":\"sqlx-core\",\"req\":\"=0.9.0\"},{\"name\":\"sqlx-macros\",\"optional\":true,\"req\":\"=0.9.0\"},{\"default_features\":false,\"name\":\"sqlx-mysql\",\"optional\":true,\"req\":\"=0.9.0\"},{\"name\":\"sqlx-postgres\",\"optional\":true,\"req\":\"=0.9.0\"},{\"name\":\"sqlx-sqlite\",\"optional\":true,\"req\":\"=0.9.0\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3.10.1\"},{\"kind\":\"dev\",\"name\":\"time_\",\"package\":\"time\",\"req\":\"^0.3.47\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.25.0\"},{\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0.53\"},{\"kind\":\"dev\",\"name\":\"url\",\"req\":\"^2.2.2\"}],\"features\":{\"_rt-async-global-executor\":[],\"_rt-async-std\":[],\"_rt-smol\":[],\"_rt-tokio\":[],\"_sqlite\":[],\"_unstable-all-types\":[\"bigdecimal\",\"rust_decimal\",\"json\",\"time\",\"chrono\",\"ipnet\",\"ipnetwork\",\"mac_address\",\"uuid\",\"bit-vec\",\"bstr\"],\"_unstable-docs\":[\"all-databases\",\"_unstable-all-types\",\"sqlx-sqlite/_unstable-docs\"],\"all-databases\":[\"mysql\",\"sqlite\",\"postgres\",\"any\"],\"any\":[\"sqlx-core/any\",\"sqlx-mysql?/any\",\"sqlx-postgres?/any\",\"sqlx-sqlite?/any\"],\"bigdecimal\":[\"sqlx-core/bigdecimal\",\"sqlx-macros?/bigdecimal\",\"sqlx-mysql?/bigdecimal\",\"sqlx-postgres?/bigdecimal\"],\"bit-vec\":[\"sqlx-core/bit-vec\",\"sqlx-macros?/bit-vec\",\"sqlx-postgres?/bit-vec\"],\"bstr\":[\"sqlx-core/bstr\"],\"chrono\":[\"sqlx-core/chrono\",\"sqlx-macros?/chrono\",\"sqlx-mysql?/chrono\",\"sqlx-postgres?/chrono\",\"sqlx-sqlite?/chrono\"],\"default\":[\"any\",\"macros\",\"migrate\",\"json\"],\"derive\":[\"sqlx-macros/derive\"],\"ipnet\":[\"sqlx-core/ipnet\",\"sqlx-macros?/ipnet\",\"sqlx-postgres?/ipnet\"],\"ipnetwork\":[\"sqlx-core/ipnetwork\",\"sqlx-macros?/ipnetwork\",\"sqlx-postgres?/ipnetwork\"],\"json\":[\"sqlx-core/json\",\"sqlx-macros?/json\",\"sqlx-mysql?/json\",\"sqlx-postgres?/json\",\"sqlx-sqlite?/json\"],\"mac_address\":[\"sqlx-core/mac_address\",\"sqlx-macros?/mac_address\",\"sqlx-postgres?/mac_address\"],\"macros\":[\"derive\",\"sqlx-macros/macros\",\"sqlx-core/offline\",\"sqlx-mysql?/offline\",\"sqlx-postgres?/offline\",\"sqlx-sqlite?/offline\"],\"migrate\":[\"sqlx-core/migrate\",\"sqlx-macros?/migrate\",\"sqlx-mysql?/migrate\",\"sqlx-postgres?/migrate\",\"sqlx-sqlite?/migrate\"],\"mysql\":[\"sqlx-mysql\",\"sqlx-macros?/mysql\"],\"mysql-rsa\":[\"mysql\",\"sqlx-mysql/rsa\",\"sqlx-macros?/mysql-rsa\"],\"postgres\":[\"sqlx-postgres\",\"sqlx-macros?/postgres\"],\"regexp\":[\"sqlx-sqlite?/regexp\"],\"runtime-async-global-executor\":[\"_rt-async-global-executor\",\"sqlx-core/_rt-async-global-executor\",\"sqlx-macros?/_rt-async-global-executor\"],\"runtime-async-std\":[\"_rt-async-std\",\"sqlx-core/_rt-async-std\",\"sqlx-macros?/_rt-async-std\"],\"runtime-smol\":[\"_rt-smol\",\"sqlx-core/_rt-smol\",\"sqlx-macros?/_rt-smol\"],\"runtime-tokio\":[\"_rt-tokio\",\"sqlx-core/_rt-tokio\",\"sqlx-macros?/_rt-tokio\"],\"rust_decimal\":[\"sqlx-core/rust_decimal\",\"sqlx-macros?/rust_decimal\",\"sqlx-mysql?/rust_decimal\",\"sqlx-postgres?/rust_decimal\"],\"sqlite\":[\"sqlite-bundled\",\"sqlite-deserialize\",\"sqlite-load-extension\",\"sqlite-unlock-notify\"],\"sqlite-bundled\":[\"_sqlite\",\"sqlx-sqlite/bundled\",\"sqlx-macros?/sqlite\"],\"sqlite-deserialize\":[\"sqlx-sqlite/deserialize\"],\"sqlite-load-extension\":[\"sqlx-sqlite/load-extension\",\"sqlx-macros?/sqlite-load-extension\"],\"sqlite-preupdate-hook\":[\"sqlx-sqlite/preupdate-hook\"],\"sqlite-unbundled\":[\"_sqlite\",\"sqlx-sqlite/unbundled\",\"sqlx-macros?/sqlite-unbundled\"],\"sqlite-unlock-notify\":[\"sqlx-sqlite/unlock-notify\"],\"sqlx-toml\":[\"sqlx-core/sqlx-toml\",\"sqlx-macros?/sqlx-toml\",\"sqlx-sqlite?/sqlx-toml\"],\"time\":[\"sqlx-core/time\",\"sqlx-macros?/time\",\"sqlx-mysql?/time\",\"sqlx-postgres?/time\",\"sqlx-sqlite?/time\"],\"tls-native-tls\":[\"sqlx-core/_tls-native-tls\",\"sqlx-macros?/_tls-native-tls\"],\"tls-none\":[],\"tls-rustls\":[\"tls-rustls-ring\"],\"tls-rustls-aws-lc-rs\":[\"sqlx-core/_tls-rustls-aws-lc-rs\",\"sqlx-macros?/_tls-rustls-aws-lc-rs\"],\"tls-rustls-ring\":[\"tls-rustls-ring-webpki\"],\"tls-rustls-ring-native-roots\":[\"sqlx-core/_tls-rustls-ring-native-roots\",\"sqlx-macros?/_tls-rustls-ring-native-roots\"],\"tls-rustls-ring-webpki\":[\"sqlx-core/_tls-rustls-ring-webpki\",\"sqlx-macros?/_tls-rustls-ring-webpki\"],\"uuid\":[\"sqlx-core/uuid\",\"sqlx-macros?/uuid\",\"sqlx-mysql?/uuid\",\"sqlx-postgres?/uuid\",\"sqlx-sqlite?/uuid\"]}}", "sse-stream_0.2.5": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"anyhow\",\"req\":\"^1\"},{\"features\":[\"tracing\"],\"kind\":\"dev\",\"name\":\"axum\",\"req\":\"^0.8\"},{\"name\":\"bytes\",\"req\":\"^1\"},{\"name\":\"futures-util\",\"req\":\"^0.3\"},{\"name\":\"http-body\",\"req\":\"^1\"},{\"name\":\"http-body-util\",\"req\":\"^0.1\"},{\"features\":[\"client\",\"http1\"],\"kind\":\"dev\",\"name\":\"hyper\",\"req\":\"^1\"},{\"features\":[\"tokio\"],\"kind\":\"dev\",\"name\":\"hyper-util\",\"req\":\"^0.1\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2\"},{\"features\":[\"stream\"],\"kind\":\"dev\",\"name\":\"reqwest\",\"req\":\"^0.12\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"features\":[\"io\"],\"kind\":\"dev\",\"name\":\"tokio-util\",\"req\":\"^0.7\"},{\"name\":\"tracing\",\"optional\":true,\"req\":\"^0.1\"},{\"kind\":\"dev\",\"name\":\"tracing\",\"req\":\"^0.1\"},{\"features\":[\"env-filter\",\"std\",\"fmt\"],\"kind\":\"dev\",\"name\":\"tracing-subscriber\",\"req\":\"^0.3\"}],\"features\":{\"default\":[],\"tracing\":[\"dep:tracing\"]}}", "stable_deref_trait_1.2.1": "{\"dependencies\":[],\"features\":{\"alloc\":[],\"default\":[\"std\"],\"std\":[\"alloc\"]}}", diff --git a/README.md b/README.md index f028d7ba626c..a958d9940422 100644 --- a/README.md +++ b/README.md @@ -13,17 +13,15 @@ If you want Codex in your code editor (VS Code, Cursor, Windsurf), =8.2.0. "RUSTSEC-2026-0403", # zstd 0.13.3 pulls in zstd-safe 7.2.4. Codex, tonic and zip use read decoders or initialized output buffers and discard output on error. Remove when all paths use zstd-safe >=8.2.0. "RUSTSEC-2026-0410", # zstd-safe 7.2.4 pulls in zstd-sys 2.0.16. Its allocator bug only affects wasm32, and Codex ships native binaries. Remove when the lockfile uses zstd-sys >=2.1.2. + # Reviewed 2026-10-29: this libz-sys path is Windows-only in Codex and + # skips the affected probe; remove when libz-sys >=1.1.31. + "RUSTSEC-2026-0418", # Reviewed 2026-11-05: unmaintained only; no known exploitable issue or fixed upstream release. "RUSTSEC-2026-0441", # pin-utils 0.1.0 via aws-smithy-http 0.62.6 -> aws-config 1.8.12 -> codex-aws-auth. Remove when AWS SDK dependencies drop pin-utils. + # Reviewed 2026-11-14; fixed releases are not yet in this Rust 1.95 + # branch's lockfile. Remove after the corresponding dependency updates. + "RUSTSEC-2026-0386", # tokio 1.52.3 AsyncFd constructors; upgrade to >=1.53.3 or fixed 1.51.6 line + "RUSTSEC-2026-0486", # rustix 1.1.4 xattr zero-length-buffer initialization; upgrade to >=1.1.6 + "RUSTSEC-2026-0523", # quinn-proto 0.11.18 stream-limit validation; upgrade to >=0.11.19 + "RUSTSEC-2026-0524", # quinn-proto 0.11.18 Retry-token allocation; upgrade to >=0.11.19 + "RUSTSEC-2026-0538", # quinn-udp 0.5.14/0.6.1 truncated-datagram loop; upgrade to >=0.5.16 or >=0.6.3 ] diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 35ced85bcc13..daf4b7e95eab 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -265,7 +265,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -276,7 +276,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -6813,7 +6813,7 @@ dependencies = [ "libc", "option-ext", "redox_users 0.5.2", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -7170,7 +7170,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -7322,7 +7322,7 @@ checksum = "0ce92ff622d6dadf7349484f42c93271a0d49b7cc4d466a936405bacbe10aa78" dependencies = [ "cfg-if", "rustix 1.1.4", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -7822,7 +7822,7 @@ dependencies = [ "gobject-sys", "libc", "system-deps", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -9246,7 +9246,7 @@ dependencies = [ "js-sys", "log", "wasm-bindgen", - "windows-core 0.58.0", + "windows-core 0.62.2", ] [[package]] @@ -9699,7 +9699,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" dependencies = [ "hermit-abi", "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -10062,9 +10062,9 @@ dependencies = [ [[package]] name = "libsqlite3-sys" -version = "0.37.0" +version = "0.39.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1f111c8c41e7c61a49cd34e44c7619462967221a6443b0ec299e0ac30cfb9b1" +checksum = "14a5f01b87b92705d07b433c06f96cbc764637d81a0bffb5734ce17cf0f9a2b3" dependencies = [ "cc", "pkg-config", @@ -10680,7 +10680,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -11178,15 +11178,14 @@ checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" [[package]] name = "openssl" -version = "0.10.75" +version = "0.10.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08838db121398ad17ab8531ce9de97b244589089e290a384c900cb9ff7434328" +checksum = "a45fa2aa886c42762255da344f0a0d313e254066c46aad76f300c3d3da62d967" dependencies = [ "bitflags 2.13.1", "cfg-if", "foreign-types", "libc", - "once_cell", "openssl-macros", "openssl-sys", ] @@ -11225,9 +11224,9 @@ dependencies = [ [[package]] name = "openssl-sys" -version = "0.9.111" +version = "0.9.116" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82cab2d520aa75e3c58898289429321eb788c3106963d0dc886ec7a5f4adc321" +checksum = "f28a22dc7140cda5f096e5e7724a6962ca81a7f8bfd2979f9b18c11af56318c4" dependencies = [ "cc", "libc", @@ -11410,7 +11409,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.48.0", + "windows-sys 0.61.2", ] [[package]] @@ -12346,7 +12345,7 @@ dependencies = [ "libc", "log", "socket2 0.6.3", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -13646,7 +13645,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.4.15", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -13659,7 +13658,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -13718,7 +13717,7 @@ dependencies = [ "security-framework 3.5.1", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -14530,7 +14529,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" dependencies = [ "libc", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -14795,8 +14794,6 @@ dependencies = [ [[package]] name = "sqlx-sqlite" version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "488e99c397a62007e4229aec669a179816339afc6d2620ca6fa420dbee2e982c" dependencies = [ "atoi", "chrono", @@ -15360,7 +15357,7 @@ dependencies = [ "getrandom 0.4.2", "once_cell", "rustix 1.1.4", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -15416,7 +15413,7 @@ dependencies = [ "parking_lot", "rustix 1.1.4", "signal-hook", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -17174,7 +17171,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.48.0", + "windows-sys 0.61.2", ] [[package]] diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index 85cd80b7c453..8038b977a9a8 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -422,7 +422,7 @@ lazy_static = "1" libc = "0.2.182" # Keep SQLx's bundled SQLite on a version containing the WAL-reset corruption fix: # https://www.sqlite.org/wal.html#the_wal_reset_bug -libsqlite3-sys = { version = "0.37", default-features = false } +libsqlite3-sys = { version = "=0.39.1", default-features = false } linkify = "0.11" log = "0.4" lru = "0.18.2" @@ -663,11 +663,15 @@ lto = false strip = false [profile.ci-test] -# Reduce binary size to reduce disk pressure. +# Keep test binaries and nextest archives within hosted-runner disk budgets. inherits = "test" opt-level = 0 +debug = 0 +incremental = false [patch.crates-io] +# Codefx security backport: widen SQLite range until SQLx publishes the upstream fix. +sqlx-sqlite = { path = "../vendor/sqlx-sqlite" } # Uncomment to debug local changes. # ratatui = { path = "../../ratatui" } crossterm = { git = "https://github.com/openai-oss-forks/crossterm", rev = "ed1cdab335221515706178d68495bba2aed1924f" } diff --git a/codex-rs/app-server/src/request_processors/plugins/reconcile.rs b/codex-rs/app-server/src/request_processors/plugins/reconcile.rs index 775c7dc7dcb1..873ac525c18d 100644 --- a/codex-rs/app-server/src/request_processors/plugins/reconcile.rs +++ b/codex-rs/app-server/src/request_processors/plugins/reconcile.rs @@ -18,6 +18,11 @@ impl PluginRequestProcessor { config_processor: ConfigRequestProcessor, request_serialization_queues: &RequestSerializationQueues, ) -> Result, JSONRPCErrorError> { + // Clients can send this automatically after login, even when all three + // remote feature flags are enabled. It must never mutate Codefx's local state. + if !codex_core_plugins::AUTOMATIC_PLUGIN_UPDATES_ENABLED { + return Ok(Some(PluginReconcileResponse::default().into())); + } let config = self.load_latest_config(/*fallback_cwd*/ None).await?; let plugins_input = config.plugins_config_input(); let auth = self.auth_manager.auth().await; diff --git a/codex-rs/app-server/src/turn_cost_worker.rs b/codex-rs/app-server/src/turn_cost_worker.rs index 1aa2c60c3d6e..9c7f780cbc25 100644 --- a/codex-rs/app-server/src/turn_cost_worker.rs +++ b/codex-rs/app-server/src/turn_cost_worker.rs @@ -16,9 +16,9 @@ use std::collections::HashMap; use std::collections::HashSet; use std::sync::Arc; use std::time::Duration; -use std::time::Instant; use tokio::sync::mpsc; use tokio::task::JoinHandle; +use tokio::time::Instant; use tokio_util::sync::CancellationToken; use tracing::warn; diff --git a/codex-rs/app-server/tests/suite/v2/curated_mcp_sync.rs b/codex-rs/app-server/tests/suite/v2/curated_mcp_sync.rs index cecf285620da..e744b5d42c4b 100644 --- a/codex-rs/app-server/tests/suite/v2/curated_mcp_sync.rs +++ b/codex-rs/app-server/tests/suite/v2/curated_mcp_sync.rs @@ -197,7 +197,7 @@ url = "{mcp_server_url}/mcp""# } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn existing_thread_loads_api_curated_mcp_after_auth_switch_sync() -> Result<()> { +async fn auth_switch_preserves_local_mcp_without_curated_sync() -> Result<()> { let mut fixture = CuratedMcpSyncFixture::set_up().await?; let thread_id = fixture .mcp @@ -226,9 +226,16 @@ async fn existing_thread_loads_api_curated_mcp_after_auth_switch_sync() -> Resul // The account-change refresh has completed without the API-curated bundle on disk. wait_for_mcp_ready(&mut fixture.mcp, REFRESH_PROBE_SERVER_NAME).await?; - // Let sync materialize the bundle; its completion callback must refresh this same thread. + // Releasing the old sync gate must not materialize anything after login. std::fs::write(&fixture.sync_barrier, "continue")?; - wait_for_mcp_ready(&mut fixture.mcp, TEST_SERVER_NAME).await?; + tokio::time::sleep(Duration::from_millis(200)).await; + assert!( + !fixture + ._fixture_root + .path() + .join("codex-home/plugins/cache/openai-api-curated/api-plugin",) + .exists() + ); ensure!( !fixture.malicious_git_helper_marker.exists(), "curated startup synchronization executed repository-local Git configuration" @@ -240,9 +247,9 @@ async fn existing_thread_loads_api_curated_mcp_after_auth_switch_sync() -> Resul request_id, params: McpServerToolCallParams { thread_id: thread_id.clone(), - server: TEST_SERVER_NAME.to_string(), + server: REFRESH_PROBE_SERVER_NAME.to_string(), tool: TEST_TOOL_NAME.to_string(), - arguments: Some(json!({"message": "available after sync"})), + arguments: Some(json!({"message": "local MCP remains available"})), meta: None, }, }) @@ -250,7 +257,7 @@ async fn existing_thread_loads_api_curated_mcp_after_auth_switch_sync() -> Resul assert_eq!( response.structured_content, Some(json!({ - "echoed": "available after sync", + "echoed": "local MCP remains available", "threadId": thread_id, "clientCapabilities": { "extensions": {}, diff --git a/codex-rs/app-server/tests/suite/v2/cyber_access_program.rs b/codex-rs/app-server/tests/suite/v2/cyber_access_program.rs index cae8a6bceda3..5e9d9a49d172 100644 --- a/codex-rs/app-server/tests/suite/v2/cyber_access_program.rs +++ b/codex-rs/app-server/tests/suite/v2/cyber_access_program.rs @@ -323,7 +323,22 @@ async fn api_key_cyber_access_program_server_rejection_does_not_fall_back() -> R let home = TempDir::new()?; let mut app = start_api_key_app(home.path(), &server).await?; set_api_key_cyber_access_programs(&mut app, /*enabled*/ true).await?; - let thread = app.start_thread(ThreadStartParams::default()).await?.thread; + let thread = app + .start_thread(ThreadStartParams { + config: Some(std::collections::HashMap::from([ + ( + "model_providers.openai.request_max_retries".to_owned(), + json!(0), + ), + ( + "model_providers.openai.stream_max_retries".to_owned(), + json!(0), + ), + ])), + ..Default::default() + }) + .await? + .thread; let completed = app .start_turn_and_wait_for_completion(TurnStartParams { thread_id: thread.id, diff --git a/codex-rs/app-server/tests/suite/v2/hooks_list.rs b/codex-rs/app-server/tests/suite/v2/hooks_list.rs index 4d62d910510d..aaf7613acbea 100644 --- a/codex-rs/app-server/tests/suite/v2/hooks_list.rs +++ b/codex-rs/app-server/tests/suite/v2/hooks_list.rs @@ -722,7 +722,7 @@ async fn loaded_session_refreshes_externally_updated_plugin_hooks() -> Result<() #[cfg(unix)] #[tokio::test] -async fn automatic_marketplace_upgrade_refreshes_hook_runtime_for_loaded_session() -> Result<()> { +async fn explicit_marketplace_upgrade_refreshes_hook_runtime_for_loaded_session() -> Result<()> { skip_if_host_windows!(Ok(())); skip_if_remote!(Ok(()), "command hooks use host-local script and log paths"); @@ -841,12 +841,18 @@ source = "{}" assert!(!new_plugin_root.exists()); std::fs::write(&upgrade_gate, "ready")?; - timeout(DEFAULT_TIMEOUT, async { - while !new_plugin_root.exists() || old_plugin_root.exists() { - tokio::time::sleep(Duration::from_millis(10)).await; - } - }) - .await?; + tokio::time::sleep(Duration::from_millis(200)).await; + assert!(old_plugin_root.exists()); + assert!(!new_plugin_root.exists()); + let upgrade = mcp + .send_marketplace_upgrade_request(codex_app_server_protocol::MarketplaceUpgradeParams { + marketplace_name: Some("test".to_string()), + }) + .await?; + let _: codex_app_server_protocol::MarketplaceUpgradeResponse = + timeout(DEFAULT_TIMEOUT, mcp.read_response(upgrade)).await??; + assert!(new_plugin_root.exists()); + assert!(!old_plugin_root.exists()); let hooks_list_id = mcp .send_hooks_list_request(HooksListParams { diff --git a/codex-rs/app-server/tests/suite/v2/marketplace_upgrade.rs b/codex-rs/app-server/tests/suite/v2/marketplace_upgrade.rs index e8c597ea8aa7..1a0c0416864f 100644 --- a/codex-rs/app-server/tests/suite/v2/marketplace_upgrade.rs +++ b/codex-rs/app-server/tests/suite/v2/marketplace_upgrade.rs @@ -208,7 +208,7 @@ async fn marketplace_upgrade_all_configured_git_marketplaces() -> Result<()> { #[test_case(false; "user config")] #[test_case(true; "invalid user config fallback")] #[tokio::test] -async fn automatic_upgrade_isolates_git_while_explicit_install_preserves_configuration( +async fn startup_skips_git_while_explicit_install_preserves_configuration( invalid_user_config: bool, ) -> Result<()> { let codex_home = TempDir::new()?; @@ -305,13 +305,12 @@ async fn automatic_upgrade_isolates_git_while_explicit_install_preserves_configu let plugin_root = codex_home .path() .join("plugins/cache/trusted/toolkit/1.0.0/.codex-plugin/plugin.json"); - timeout(DEFAULT_TIMEOUT, async { - while !plugin_root.exists() { - tokio::time::sleep(Duration::from_millis(10)).await; - } - }) - .await?; - assert!(!abandoned.exists()); + tokio::time::sleep(Duration::from_millis(200)).await; + assert!(!plugin_root.exists()); + assert!( + abandoned.exists(), + "startup must not clean or replace plugin state" + ); if invalid_user_config { // Subsequent explicit operations must pick up a repaired user config normally. @@ -319,6 +318,8 @@ async fn automatic_upgrade_isolates_git_while_explicit_install_preserves_configu } let marketplace_path = marketplace_install_root(codex_home.path()) .join("trusted/.agents/plugins/marketplace.json"); + // Stage the local marketplace fixture explicitly; startup performs no Git I/O. + std::fs::create_dir_all(marketplace_path.parent().expect("marketplace parent"))?; std::fs::write( &marketplace_path, serde_json::json!({ diff --git a/codex-rs/app-server/tests/suite/v2/mcp_resource/plugin_metadata_refresh.rs b/codex-rs/app-server/tests/suite/v2/mcp_resource/plugin_metadata_refresh.rs index 56c0006478d3..4c7f2db3dde8 100644 --- a/codex-rs/app-server/tests/suite/v2/mcp_resource/plugin_metadata_refresh.rs +++ b/codex-rs/app-server/tests/suite/v2/mcp_resource/plugin_metadata_refresh.rs @@ -1,4 +1,4 @@ -//! Exercises installed-metadata refreshes against live MCP and bundled plugin skills. +//! Reconciliation preserves locally installed skills and an existing MCP runtime. use super::*; use axum::Json; @@ -14,7 +14,7 @@ use pretty_assertions::assert_eq; use tokio::sync::RwLock; #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn signed_image_renewal_preserves_live_mcp_and_plugin_skills() -> Result<()> { +async fn remote_reconcile_preserves_local_skills_and_live_mcp() -> Result<()> { let responses_server = responses::start_mock_server().await; let listener = TcpListener::bind("127.0.0.1:0").await?; let base_url = format!("http://{}", listener.local_addr()?); @@ -64,6 +64,8 @@ async fn signed_image_renewal_preserves_live_mcp_and_plugin_skills() -> Result<( StreamableHttpServerConfig::default(), ); let server_installed = Arc::clone(&installed); + let bundle_requests = Arc::new(AtomicUsize::new(0)); + let server_bundle_requests = Arc::clone(&bundle_requests); let router = Router::new() .nest_service("/api/codex/ps/mcp", mcp_service) .route( @@ -78,7 +80,13 @@ async fn signed_image_renewal_preserves_live_mcp_and_plugin_skills() -> Result<( } }), ) - .route("/bundle", get(move || async move { bundle })); + .route( + "/bundle", + get(move || async move { + server_bundle_requests.fetch_add(1, Ordering::SeqCst); + bundle + }), + ); let server_handle = tokio::spawn(async move { let _ = axum::serve(listener, router).await; }); @@ -90,7 +98,7 @@ async fn signed_image_renewal_preserves_live_mcp_and_plugin_skills() -> Result<( .enable_feature(Feature::Plugins) .enable_feature(Feature::RemotePlugin) .disable_feature(Feature::PluginSharing) - .with_extra_config("[skills]\ninclude_instructions = true") + .with_extra_config("[skills]\ninclude_instructions = true\n[plugins.\"demo-plugin@openai-curated-remote\"]\nenabled = true") .write(codex_home.path())?; write_chatgpt_auth( codex_home.path(), @@ -100,6 +108,18 @@ async fn signed_image_renewal_preserves_live_mcp_and_plugin_skills() -> Result<( .chatgpt_account_id("account-123"), AuthCredentialsStoreMode::File, )?; + // Install the fixture locally; listing or reconciliation must never fetch it. + let plugin_root = codex_home + .path() + .join("plugins/cache/openai-curated-remote/demo-plugin/1.0.0"); + for (path, contents) in [ + (".codex-plugin/plugin.json", r#"{"name":"demo-plugin"}"#), + ("skills/deploy/SKILL.md", SKILL_CONTENTS), + ] { + let path = plugin_root.join(path); + std::fs::create_dir_all(path.parent().expect("local fixture parent"))?; + std::fs::write(path, contents)?; + } let mut app_server = TestAppServer::builder() .with_codex_home(codex_home.path()) .without_managed_config() @@ -138,7 +158,7 @@ async fn signed_image_renewal_preserves_live_mcp_and_plugin_skills() -> Result<( ); installed.write().await["release"]["interface"]["logo_url"] = json!(renewed_logo); - refresh_and_expect_logo(&mut app_server, renewed_logo).await?; + refresh_and_expect_logo(&mut app_server, original_logo).await?; read_mcp_skill_resource(&mut app_server, &thread.id).await?; assert_eq!(sessions.load(Ordering::SeqCst), warm_sessions); assert_eq!( @@ -148,7 +168,7 @@ async fn signed_image_renewal_preserves_live_mcp_and_plugin_skills() -> Result<( installed.write().await["release"]["interface"]["capabilities"] = json!(["Updated store badge"]); - refresh_and_expect_logo(&mut app_server, renewed_logo).await?; + refresh_and_expect_logo(&mut app_server, original_logo).await?; read_mcp_skill_resource(&mut app_server, &thread.id).await?; assert_eq!(sessions.load(Ordering::SeqCst), warm_sessions); assert_eq!( @@ -156,14 +176,13 @@ async fn signed_image_renewal_preserves_live_mcp_and_plugin_skills() -> Result<( warm_skills ); - // Runtime metadata must update the cached skill catalog without changing the bundle. + // A later remote disablement must not change the local skill via reconciliation. installed.write().await["release"]["interface"]["logo_url"] = json!(changed_logo); installed.write().await["enabled"] = json!(false); - refresh_and_expect_logo(&mut app_server, changed_logo).await?; - assert!( - list_plugin_skills(&mut app_server, codex_home.path()) - .await? - .is_empty() + refresh_and_expect_logo(&mut app_server, original_logo).await?; + assert_eq!( + list_plugin_skills(&mut app_server, codex_home.path()).await?, + warm_skills, ); read_mcp_skill_resource(&mut app_server, &thread.id).await?; assert_eq!(sessions.load(Ordering::SeqCst), warm_sessions); @@ -172,13 +191,14 @@ async fn signed_image_renewal_preserves_live_mcp_and_plugin_skills() -> Result<( std::fs::read_to_string(warm_skills[0].path.as_str())?, SKILL_CONTENTS ); + assert_eq!(bundle_requests.load(Ordering::SeqCst), 0); server_handle.abort(); Ok(()) } async fn refresh_and_expect_logo(app_server: &mut TestAppServer, logo: &str) -> Result<()> { - // plugin/installed starts the real background sync with the production callback. - // Reconcile acquires the same gate, so its completion fences the background pass. + // Explicit metadata reads can use the existing cache. Reconcile is a no-op + // even when the server offers a different bundle or updated remote state. let request = app_server .send_raw_request("plugin/installed", Some(json!({}))) .await?; @@ -213,7 +233,7 @@ async fn refresh_and_expect_logo(app_server: &mut TestAppServer, logo: &str) -> .and_then(|info| info.logo_url.as_deref()), Some(logo) ); - // Finish the follow-up read's background pass before changing the next snapshot. + // Repeated compatibility requests must also preserve the local installation. let request = app_server .send_raw_request("plugin/reconcile", Some(json!({}))) .await?; diff --git a/codex-rs/app-server/tests/suite/v2/plugin_install.rs b/codex-rs/app-server/tests/suite/v2/plugin_install.rs index 87999efce1be..8bb588ce5385 100644 --- a/codex-rs/app-server/tests/suite/v2/plugin_install.rs +++ b/codex-rs/app-server/tests/suite/v2/plugin_install.rs @@ -2958,6 +2958,8 @@ chatgpt_base_url = "{base_url}" [features] plugins = true +remote_plugin = true +plugin_sharing = true "# ), ) diff --git a/codex-rs/app-server/tests/suite/v2/plugin_list.rs b/codex-rs/app-server/tests/suite/v2/plugin_list.rs index 956cb5d65213..704b446096ec 100644 --- a/codex-rs/app-server/tests/suite/v2/plugin_list.rs +++ b/codex-rs/app-server/tests/suite/v2/plugin_list.rs @@ -11,10 +11,6 @@ use app_test_support::to_response; use app_test_support::write_chatgpt_auth; use chrono::Duration as ChronoDuration; use chrono::Utc; -use codex_app_server_protocol::HookMetadata; -use codex_app_server_protocol::HookTrustStatus; -use codex_app_server_protocol::HooksListParams; -use codex_app_server_protocol::HooksListResponse; use codex_app_server_protocol::JSONRPCResponse; use codex_app_server_protocol::LoginAccountResponse; use codex_app_server_protocol::PluginAuthPolicy; @@ -84,6 +80,8 @@ fn write_plugins_enabled_config_with_base_url( [features] plugins = true +remote_plugin = true +plugin_sharing = true "#, ), ) @@ -298,6 +296,7 @@ async fn plugin_installed_prefers_remote_curated_conflicts_when_remote_plugin_en [features] plugins = true +remote_plugin = true plugin_sharing = false [plugins."linear@openai-curated"] @@ -415,6 +414,7 @@ async fn plugin_installed_prefers_api_curated_conflicts_after_switching_to_api_a [features] plugins = true +remote_plugin = true plugin_sharing = false [plugins."linear@openai-api-curated"] @@ -1131,13 +1131,13 @@ enum MarketplaceRefreshScenario { } #[test_case(true, true, MarketplaceRefreshScenario::Distinct; "forced")] -#[test_case(false, true, MarketplaceRefreshScenario::Distinct; "background")] +#[test_case(false, true, MarketplaceRefreshScenario::Distinct; "cached")] #[test_case(true, false, MarketplaceRefreshScenario::Distinct; "forced with project-enabled plugins")] -#[test_case(false, false, MarketplaceRefreshScenario::Distinct; "background with project-enabled plugins")] +#[test_case(false, false, MarketplaceRefreshScenario::Distinct; "cached with project-enabled plugins")] #[test_case(true, true, MarketplaceRefreshScenario::Duplicate; "forced preserves source precedence")] -#[test_case(false, true, MarketplaceRefreshScenario::Duplicate; "background preserves source precedence")] +#[test_case(false, true, MarketplaceRefreshScenario::Duplicate; "cached preserves source precedence")] #[test_case(true, true, MarketplaceRefreshScenario::DuplicateConfiguredInLaterCwd; "forced merges later repository configuration")] -#[test_case(false, true, MarketplaceRefreshScenario::DuplicateConfiguredInLaterCwd; "background merges later repository configuration")] +#[test_case(false, true, MarketplaceRefreshScenario::DuplicateConfiguredInLaterCwd; "cached merges later repository configuration")] #[tokio::test] async fn plugin_list_refreshes_plugins_from_each_cwd( force_refetch: bool, @@ -1187,6 +1187,12 @@ async fn plugin_list_refreshes_plugins_from_each_cwd( )?; set_project_trust_level(codex_home.path(), repo, TrustLevel::Trusted)?; write_installed_plugin_with_version(&codex_home, name, "sample", "1.0.0")?; + std::fs::write( + codex_home.path().join(format!( + "plugins/cache/{name}/sample/1.0.0/.codex-plugin/plugin.json" + )), + serde_json::to_vec(&serde_json::json!({"name": "sample", "version": "1.0.0"}))?, + )?; } let mut server = TestAppServer::builder() .with_codex_home(codex_home.path()) @@ -1214,15 +1220,17 @@ async fn plugin_list_refreshes_plugins_from_each_cwd( 1 }) .collect::>(); - for (name, version) in &expected_sources { + for (name, source_version) in &expected_sources { + let version = if force_refetch { + *source_version + } else { + "1.0.0" + }; let manifest = codex_home.path().join(format!( "plugins/cache/{name}/sample/{version}/.codex-plugin/plugin.json" )); - if !force_refetch { - wait_for_path_exists(&manifest).await?; - } let value: serde_json::Value = serde_json::from_slice(&std::fs::read(manifest)?)?; - assert_eq!(value["version"], *version); + assert_eq!(value["version"], version); } let id = server .send_plugin_installed_request(PluginInstalledParams { @@ -1961,8 +1969,7 @@ enabled = true } #[tokio::test] -async fn app_server_startup_downloads_installed_plugin_bundles_without_discovery_prefetch() --> Result<()> { +async fn app_server_startup_never_downloads_installed_plugin_bundles() -> Result<()> { let codex_home = TempDir::new()?; let server = MockServer::start().await; write_remote_plugin_catalog_config( @@ -2025,25 +2032,26 @@ async fn app_server_startup_downloads_installed_plugin_bundles_without_discovery .build_initialized_with_timeout(DEFAULT_TIMEOUT) .await?; - wait_for_path_exists(&installed_path.join(".codex-plugin/plugin.json")).await?; - let installed_plugin_manifest: serde_json::Value = serde_json::from_str( - &std::fs::read_to_string(installed_path.join(".codex-plugin/plugin.json"))?, - )?; - assert_eq!( - installed_plugin_manifest["version"], - serde_json::json!("1.2.3") + sleep(Duration::from_millis(200)).await; + assert!(!installed_path.exists()); + assert!( + server + .received_requests() + .await + .expect("wiremock records requests") + .iter() + .all(|request| { + !request.url.path().contains("/ps/plugins/") + && !request.url.path().starts_with("/bundles/") + }) ); - let installed_app_manifest: serde_json::Value = - serde_json::from_str(&std::fs::read_to_string(installed_path.join(".app.json"))?)?; - assert_eq!(installed_app_manifest, remote_app_manifest); - assert!(installed_path.join("skills/plan-work/SKILL.md").is_file()); let config = std::fs::read_to_string(codex_home.path().join("config.toml"))?; assert!(!config.contains("linear@openai-curated-remote")); Ok(()) } #[tokio::test] -async fn plugin_list_sync_upgrades_and_removes_remote_installed_plugin_bundles() -> Result<()> { +async fn plugin_list_never_upgrades_or_removes_remote_installed_plugin_bundles() -> Result<()> { let codex_home = TempDir::new()?; let server = MockServer::start().await; write_remote_plugin_catalog_config( @@ -2126,19 +2134,18 @@ async fn plugin_list_sync_upgrades_and_removes_remote_installed_plugin_bundles() vec![("linear@openai-curated-remote".to_string(), true, true)] ); - wait_for_path_exists(&new_path.join(".codex-plugin/plugin.json")).await?; - let installed_plugin_manifest: serde_json::Value = serde_json::from_str( - &std::fs::read_to_string(new_path.join(".codex-plugin/plugin.json"))?, - )?; - assert_eq!( - installed_plugin_manifest["version"], - serde_json::json!("1.2.3") - ); - let installed_app_manifest: serde_json::Value = - serde_json::from_str(&std::fs::read_to_string(new_path.join(".app.json"))?)?; - assert_eq!(installed_app_manifest, remote_app_manifest); - wait_for_path_missing(&old_path).await?; - wait_for_path_missing(&stale_path).await?; + sleep(Duration::from_millis(200)).await; + assert!(!new_path.exists()); + assert!(old_path.join(".codex-plugin/plugin.json").is_file()); + assert!(stale_path.join("1.0.0/.codex-plugin/plugin.json").is_file()); + assert!( + server + .received_requests() + .await + .expect("wiremock records requests") + .iter() + .all(|request| { !request.url.path().starts_with("/bundles/") }) + ); let config = std::fs::read_to_string(codex_home.path().join("config.toml"))?; assert!(!config.contains("linear@openai-curated-remote")); Ok(()) @@ -2643,7 +2650,17 @@ async fn plugin_list_honors_global_remote_catalog_cache_ttl() -> Result<()> { "linear@openai-curated-remote" ); - wait_for_remote_plugin_request_count(&server, "/ps/plugins/list", /*expected_count*/ 1).await?; + wait_for_remote_plugin_request_count(&server, "/ps/plugins/list", /*expected_count*/ 0).await?; + wait_for_cached_remote_catalog_plugin_ids(codex_home.path(), &[cached_remote_plugin_id]) + .await?; + let request_id = mcp + .send_plugin_list_request(PluginListParams { + cwds: None, + marketplace_kinds: None, + force_refetch: true, + }) + .await?; + let _: PluginListResponse = timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??; wait_for_cached_remote_catalog_plugin_ids(codex_home.path(), &[refreshed_remote_plugin_id]) .await?; sleep(Duration::from_millis(100)).await; @@ -2653,8 +2670,7 @@ async fn plugin_list_honors_global_remote_catalog_cache_ttl() -> Result<()> { } #[tokio::test] -async fn app_server_startup_refreshes_cached_remote_catalog_without_blocking_plugin_list() --> Result<()> { +async fn app_server_startup_preserves_cached_catalog_until_explicit_refetch() -> Result<()> { let codex_home = TempDir::new()?; let server = MockServer::start().await; write_remote_plugin_catalog_config( @@ -2737,7 +2753,8 @@ async fn app_server_startup_refreshes_cached_remote_catalog_without_blocking_plu .build() .await?; timeout(DEFAULT_TIMEOUT, app_server.initialize()).await??; - wait_for_remote_plugin_request_count(&server, "/ps/plugins/list", /*expected_count*/ 1).await?; + sleep(Duration::from_millis(200)).await; + wait_for_remote_plugin_request_count(&server, "/ps/plugins/list", /*expected_count*/ 0).await?; let request_id = app_server .send_plugin_list_request(PluginListParams { @@ -2763,13 +2780,13 @@ async fn app_server_startup_refreshes_cached_remote_catalog_without_blocking_plu "linear@openai-curated-remote" ); - wait_for_cached_remote_catalog_plugin_ids(codex_home.path(), &[refreshed_remote_plugin_id]) + wait_for_cached_remote_catalog_plugin_ids(codex_home.path(), &[cached_remote_plugin_id]) .await?; let request_id = app_server .send_plugin_list_request(PluginListParams { cwds: None, marketplace_kinds: None, - force_refetch: false, + force_refetch: true, }) .await?; let response: PluginListResponse = to_response( @@ -2795,7 +2812,7 @@ async fn app_server_startup_refreshes_cached_remote_catalog_without_blocking_plu } #[tokio::test] -async fn app_server_startup_skips_disabled_remote_plugin_catalog_scopes() -> Result<()> { +async fn app_server_startup_never_refreshes_remote_plugin_catalog_scopes() -> Result<()> { let codex_home = TempDir::new()?; let server = MockServer::start().await; let base_url = format!("{}/backend-api/", server.uri()); @@ -2883,12 +2900,7 @@ async fn app_server_startup_skips_disabled_remote_plugin_catalog_scopes() -> Res .build() .await?; timeout(DEFAULT_TIMEOUT, app_server.initialize()).await??; - wait_for_remote_plugin_list_scope_request_count( - &server, - "WORKSPACE", - /*expected_count*/ 1, - ) - .await?; + sleep(Duration::from_millis(200)).await; let requested_scopes = server .received_requests() @@ -2906,7 +2918,7 @@ async fn app_server_startup_skips_disabled_remote_plugin_catalog_scopes() -> Res .map(|(_, scope)| scope.into_owned()) }) .collect::>(); - assert_eq!(requested_scopes, vec!["WORKSPACE".to_string()]); + assert!(requested_scopes.is_empty()); Ok(()) } @@ -3771,6 +3783,7 @@ async fn plugin_installed_includes_created_by_me_when_remote_plugins_enabled() - [features] plugins = true +remote_plugin = true plugin_sharing = false "#, server.uri() @@ -3835,10 +3848,18 @@ plugin_sharing = false .collect::>(), vec![("private-linear@created-by-me-remote", true, true)] ); - wait_for_path_exists( - &codex_home.path().join( - "plugins/cache/created-by-me-remote/private-linear/1.2.3/.codex-plugin/plugin.json", - ), + assert!( + !codex_home + .path() + .join( + "plugins/cache/created-by-me-remote/private-linear/1.2.3/.codex-plugin/plugin.json", + ) + .exists() + ); + wait_for_remote_plugin_request_count( + &server, + "/bundles/private-linear.tar.gz", + /*expected_count*/ 0, ) .await?; wait_for_remote_installed_snapshot_request(&server).await?; @@ -3846,7 +3867,7 @@ plugin_sharing = false } #[tokio::test] -async fn plugin_installed_trusts_new_workspace_listed_plugin_hooks() -> Result<()> { +async fn plugin_installed_never_downloads_or_trusts_workspace_hooks() -> Result<()> { let codex_home = TempDir::new()?; let server = MockServer::start().await; let disabled_hook_key = "available-hooks@workspace-directory:hooks/hooks.json:pre_tool_use:0:0"; @@ -3902,72 +3923,38 @@ trusted_hash = "sha256:unrelated" .await?; trigger_plugin_installed_sync(&mut mcp).await?; - let plugin_ids = [ - "available-hooks@workspace-directory", - "default-hooks@workspace-directory", - ]; - let hooks = wait_for_plugin_hooks( - &mut mcp, - codex_home.path(), - &plugin_ids, - HookTrustStatus::Trusted, - ) - .await?; - for plugin_id in plugin_ids { - assert!( - hooks - .iter() - .any(|hook| hook.plugin_id.as_deref() == Some(plugin_id)) - ); - } - wait_for_path_exists( - &codex_home + sleep(Duration::from_millis(200)).await; + assert!( + !codex_home .path() - .join("plugins/cache/workspace-directory/no-hooks/1.2.3/.codex-plugin/plugin.json"), - ) - .await?; + .join("plugins/cache/workspace-directory") + .exists() + ); let config: toml::Value = toml::from_str(&std::fs::read_to_string( codex_home.path().join("config.toml"), )?)?; - let hook_states = config["hooks"]["state"].as_table().expect("hook states"); - for hook in &hooks { - let (declaration_hash, content_hash) = hook - .current_hash - .split_once('/') - .expect("declaration and content hashes"); - assert_eq!( - ( - hook_states[hook.key.as_str()]["trusted_hash"].as_str(), - hook_states[hook.key.as_str()]["trusted_content_hash"].as_str(), - ), - (Some(declaration_hash), Some(content_hash)) - ); - } - assert!( - !hooks - .iter() - .find(|hook| hook.key == disabled_hook_key) - .expect("disabled hook") - .enabled - ); - assert_eq!( - hook_states[disabled_hook_key]["enabled"].as_bool(), - Some(false) - ); + let states = config["hooks"]["state"].as_table().expect("hook states"); + assert_eq!(states.len(), 2); + assert_eq!(states[disabled_hook_key]["enabled"].as_bool(), Some(false)); + assert!(states[disabled_hook_key].get("trusted_hash").is_none()); assert_eq!( - hook_states[unrelated_hook_key]["trusted_hash"].as_str(), + states[unrelated_hook_key]["trusted_hash"].as_str(), Some("sha256:unrelated") ); - assert_eq!( - hook_states[unrelated_hook_key]["enabled"].as_bool(), - Some(false) + assert!( + server + .received_requests() + .await + .expect("wiremock records requests") + .iter() + .all(|request| { !request.url.path().starts_with("/bundles/") }) ); Ok(()) } #[cfg(unix)] #[tokio::test] -async fn plugin_installed_hook_trust_write_failure_stays_untrusted() -> Result<()> { +async fn plugin_installed_does_not_mutate_read_only_hook_config() -> Result<()> { use std::os::unix::fs::PermissionsExt; use std::os::unix::fs::symlink; @@ -4009,25 +3996,22 @@ async fn plugin_installed_hook_trust_write_failure_stays_untrusted() -> Result<( std::fs::set_permissions(config_target_dir.path(), read_only_permissions)?; trigger_plugin_installed_sync(&mut mcp).await?; - let plugin_ids = ["failed-trust@workspace-directory"]; - let before = wait_for_plugin_hooks( - &mut mcp, - codex_home.path(), - &plugin_ids, - HookTrustStatus::Untrusted, - ) - .await?; - sleep(Duration::from_millis(300)).await; - let after = wait_for_plugin_hooks( - &mut mcp, - codex_home.path(), - &plugin_ids, - HookTrustStatus::Untrusted, - ) - .await?; - - assert_eq!(after[0].current_hash, before[0].current_hash); + sleep(Duration::from_millis(200)).await; + assert!( + !codex_home + .path() + .join("plugins/cache/workspace-directory") + .exists() + ); assert!(!std::fs::read_to_string(config_target)?.contains("trusted_hash")); + assert!( + server + .received_requests() + .await + .expect("wiremock records requests") + .iter() + .all(|request| { !request.url.path().starts_with("/bundles/") }) + ); Ok(()) } @@ -4182,12 +4166,12 @@ async fn plugin_list_fetches_workspace_directory_kind_when_remote_plugin_disable wait_for_remote_plugin_list_scope_request_count( &server, "WORKSPACE", - /*expected_count*/ 1, + /*expected_count*/ 0, ) .await?; wait_for_cached_remote_catalog_plugin_ids( codex_home.path(), - &["plugins~Plugin_22222222222222222222222222222222"], + &["plugins~Plugin_11111111111111111111111111111111"], ) .await?; @@ -4195,7 +4179,7 @@ async fn plugin_list_fetches_workspace_directory_kind_when_remote_plugin_disable .send_plugin_list_request(PluginListParams { cwds: None, marketplace_kinds: Some(vec![PluginListMarketplaceKind::WorkspaceDirectory]), - force_refetch: false, + force_refetch: true, }) .await?; let response: PluginListResponse = to_response( @@ -4230,6 +4214,7 @@ async fn plugin_list_fetches_user_plugins_in_created_by_me_remote_marketplace() [features] plugins = true +remote_plugin = true plugin_sharing = false "#, server.uri() @@ -4561,7 +4546,16 @@ async fn plugin_list_fetches_shared_with_me_kind() -> Result<()> { share_context.discoverability, Some(PluginShareDiscoverability::Unlisted) ); - wait_for_remote_installed_snapshot_request(&server).await?; + // Shared-with-me listing fetches its requested workspace scope; it must + // not launch the former background full-account snapshot refresh. + let requests = server + .received_requests() + .await + .expect("wiremock records requests"); + assert!(requests.iter().all(|request| { + !request.url.path().ends_with("/ps/plugins/installed") + || request.url.query_pairs().any(|(name, _)| name == "scope") + })); wait_for_remote_plugin_request_count(&server, "/ps/plugins/list", /*expected_count*/ 0).await?; Ok(()) } @@ -4577,6 +4571,7 @@ async fn plugin_list_omits_shared_with_me_kind_when_plugin_sharing_disabled() -> [features] plugins = true +remote_plugin = true plugin_sharing = false "#, server.uri() @@ -4992,7 +4987,7 @@ async fn plugin_list_omits_featured_plugin_ids_without_chatgpt_auth() -> Result< } #[tokio::test] -async fn plugin_list_uses_warmed_featured_plugin_ids_cache_on_first_request() -> Result<()> { +async fn plugin_list_fetches_featured_ids_explicitly_without_startup_prefetch() -> Result<()> { let codex_home = TempDir::new()?; let server = MockServer::start().await; write_plugin_sync_config(codex_home.path(), &format!("{}/backend-api/", server.uri()))?; @@ -5012,7 +5007,8 @@ async fn plugin_list_uses_warmed_featured_plugin_ids_cache_on_first_request() -> .with_plugin_startup_tasks() .build_initialized_with_timeout(DEFAULT_TIMEOUT) .await?; - wait_for_featured_plugin_request_count(&server, /*expected_count*/ 1).await?; + sleep(Duration::from_millis(200)).await; + wait_for_featured_plugin_request_count(&server, /*expected_count*/ 0).await?; let request_id = mcp .send_plugin_list_request(PluginListParams { @@ -5192,19 +5188,6 @@ fn rewrite_cached_remote_catalog_fetched_at( Ok(()) } -async fn wait_for_path_exists(path: &std::path::Path) -> Result<()> { - timeout(DEFAULT_TIMEOUT, async { - loop { - if path.exists() { - return Ok::<(), anyhow::Error>(()); - } - tokio::time::sleep(Duration::from_millis(10)).await; - } - }) - .await??; - Ok(()) -} - async fn trigger_plugin_installed_sync(mcp: &mut TestAppServer) -> Result<()> { let request_id = mcp .send_plugin_installed_request(PluginInstalledParams { @@ -5217,56 +5200,6 @@ async fn trigger_plugin_installed_sync(mcp: &mut TestAppServer) -> Result<()> { Ok(()) } -async fn wait_for_plugin_hooks( - mcp: &mut TestAppServer, - cwd: &std::path::Path, - plugin_ids: &[&str], - expected_status: HookTrustStatus, -) -> Result> { - timeout(DEFAULT_TIMEOUT, async { - loop { - let request_id = mcp - .send_hooks_list_request(HooksListParams { - cwds: vec![cwd.to_path_buf()], - ..Default::default() - }) - .await?; - let HooksListResponse { data } = mcp.read_response(request_id).await?; - let hooks = data - .into_iter() - .flat_map(|entry| entry.hooks) - .filter(|hook| { - hook.plugin_id - .as_deref() - .is_some_and(|plugin_id| plugin_ids.contains(&plugin_id)) - }) - .collect::>(); - if hooks.len() == plugin_ids.len() - && hooks - .iter() - .all(|hook| hook.trust_status == expected_status) - { - return Ok::<_, anyhow::Error>(hooks); - } - sleep(Duration::from_millis(10)).await; - } - }) - .await? -} - -async fn wait_for_path_missing(path: &std::path::Path) -> Result<()> { - timeout(DEFAULT_TIMEOUT, async { - loop { - if !path.exists() { - return Ok::<(), anyhow::Error>(()); - } - tokio::time::sleep(Duration::from_millis(10)).await; - } - }) - .await??; - Ok(()) -} - async fn mount_remote_plugin_list(server: &MockServer, scope: &str, body: &str) { Mock::given(method("GET")) .and(path("/backend-api/ps/plugins/list")) @@ -5724,6 +5657,8 @@ chatgpt_base_url = "{base_url}" [features] plugins = true +remote_plugin = true +plugin_sharing = true "# ), ) @@ -5741,6 +5676,8 @@ fn write_remote_plugin_hook_config( [features] plugins = true +remote_plugin = true +plugin_sharing = true hooks = true {hook_state}"#, ), diff --git a/codex-rs/app-server/tests/suite/v2/plugin_read.rs b/codex-rs/app-server/tests/suite/v2/plugin_read.rs index f553cfe8e69f..4c1086071db6 100644 --- a/codex-rs/app-server/tests/suite/v2/plugin_read.rs +++ b/codex-rs/app-server/tests/suite/v2/plugin_read.rs @@ -2590,6 +2590,8 @@ chatgpt_base_url = "{base_url}" [features] plugins = true +remote_plugin = true +plugin_sharing = true "# ), ) diff --git a/codex-rs/app-server/tests/suite/v2/plugin_reconcile.rs b/codex-rs/app-server/tests/suite/v2/plugin_reconcile.rs index 0b65e2b294d0..343f35e327ba 100644 --- a/codex-rs/app-server/tests/suite/v2/plugin_reconcile.rs +++ b/codex-rs/app-server/tests/suite/v2/plugin_reconcile.rs @@ -1,332 +1,120 @@ -//! Exercises blocking plugin reconciliation through the public JSON-RPC API. +//! Account login and client reconciliation must not mutate local plugins or skills. use std::time::Duration; use anyhow::Result; use app_test_support::ChatGptAuthFixture; +use app_test_support::ChatGptIdTokenClaims; use app_test_support::MockResponsesConfig; use app_test_support::TestAppServer; +use app_test_support::encode_id_token; use app_test_support::write_chatgpt_auth; -use codex_app_server_protocol::PluginReconcileChangedPlugin; +use codex_app_server_protocol::LoginAccountResponse; use codex_app_server_protocol::PluginReconcileResponse; -use codex_app_server_protocol::TurnStartParams; -use codex_app_server_protocol::TurnStatus; -use codex_app_server_protocol::UserInput; use codex_config::types::AuthCredentialsStoreMode; use codex_features::Feature; -use core_test_support::responses; -use flate2::Compression; -use flate2::write::GzEncoder; use pretty_assertions::assert_eq; -use serde_json::Value; use serde_json::json; use tempfile::TempDir; use test_case::test_case; use tokio::time::timeout; -use wiremock::Mock; use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::header; -use wiremock::matchers::method; -use wiremock::matchers::path; -use wiremock::matchers::query_param; - -use super::analytics::wait_for_matching_analytics_event; const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30); -const REMOTE_PLUGIN_ID: &str = "plugins~Plugin_00000000000000000000000000000000"; -#[test_case("WORKSPACE", "workspace-directory"; "workspace")] -#[test_case("GLOBAL", "openai-curated-remote"; "global")] +#[test_case(false; "remote_features_disabled")] +#[test_case(true; "remote_features_enabled")] #[tokio::test] -async fn plugin_reconcile_syncs_bundles_and_reports_changes( - scope: &str, - marketplace: &str, +async fn login_and_reconcile_preserve_local_plugins_and_skills( + remote_features: bool, ) -> Result<()> { let server = MockServer::start().await; - // Both scopes must retain background-sync behavior with remote_plugin disabled. - let (mut app_server, codex_home) = start_app_server(&server).await?; - let thread = app_server.start_thread(Default::default()).await?.thread; - let bundle_url = format!("{}/bundle", server.uri()); - let plugin_id = format!("linear@{marketplace}"); - let first = PluginReconcileChangedPlugin { - id: plugin_id.clone(), - has_mcps: true, - has_apps: false, - has_hooks: true, - has_skills: true, - }; - let second = PluginReconcileChangedPlugin { - id: plugin_id.clone(), - has_mcps: false, - has_apps: true, - has_hooks: false, - has_skills: false, - }; - let updated = PluginReconcileChangedPlugin { - id: plugin_id, - has_mcps: true, - has_apps: true, - has_hooks: true, - has_skills: true, - }; - let failed_id = "plugins~Plugin_11111111111111111111111111111111"; - let mut missing_bundle = installed_plugin("1.0.0", &bundle_url, "WORKSPACE"); - missing_bundle["id"] = json!(failed_id); - missing_bundle["name"] = json!("missing-bundle"); - missing_bundle["release"]["bundle_download_url"] = Value::Null; - let mut first_pass_failure = Some(missing_bundle); - - // v1.1 drops hooks; v2 restores them and drops Apps. Both updates must report - // both sides, while uninstall below reports only v2's remaining capabilities. - // Enablement changes report cached capabilities without downloading the bundle again. - for (version, enabled, capabilities, expected_plugins, expected_downloads) in [ - ("1.0.0", true, &first, vec![first.clone()], 1), - ("1.0.0", true, &first, Vec::new(), 0), - ("1.0.0", false, &first, vec![first.clone()], 0), - ("1.0.0", true, &first, vec![first.clone()], 0), - ("1.1.0", true, &second, vec![updated.clone()], 1), - ("2.0.0", true, &first, vec![updated], 1), - ] { - let mut files = vec![( - ".codex-plugin/plugin.json", - json!({"name": "linear"}).to_string(), - )]; - if capabilities.has_mcps { - files.push(( - ".mcp.json", - json!({"mcpServers": {"example": {"command": "unused", "enabled": false}}}) - .to_string(), - )); - } - if capabilities.has_apps { - files.push(( - ".app.json", - json!({"apps": {"example": {"id": "connector_example"}}}).to_string(), - )); - } - if capabilities.has_hooks { - files.push(( - "hooks/hooks.json", - json!({"hooks": {"UserPromptSubmit": [{"hooks": [{ - "type": "command", "command": format!("echo hook {version}") - }]}]}}) - .to_string(), - )); - } - if capabilities.has_skills { - files.push(( - "skills/example/SKILL.md", - "---\nname: example\ndescription: Example skill\n---\nExample skill".to_string(), - )); - } - let mut archive = tar::Builder::new(GzEncoder::new(Vec::new(), Compression::default())); - for (path, contents) in files { - let mut header = tar::Header::new_gnu(); - header.set_size(contents.len() as u64); - header.set_mode(/*mode*/ 0o644); - header.set_cksum(); - archive.append_data(&mut header, path, contents.as_bytes())?; - } - let bundle = archive.into_inner()?.finish()?; - let mut plugin = installed_plugin(version, &bundle_url, scope); - plugin["enabled"] = json!(enabled); - let mut plugins = vec![plugin]; - let mut failures = Vec::new(); - if let Some(failure) = first_pass_failure.take() { - plugins.push(failure); - failures.push(failed_id.to_string()); - } - let expected = PluginReconcileResponse { - changed_plugins: expected_plugins, - failed_remote_plugin_ids: failures.clone(), - failed_materialization_remote_plugin_ids: failures, - }; - let active_plugin_ids = if enabled { - vec![REMOTE_PLUGIN_ID.to_string()] + let codex_home = TempDir::new()?; + let mut config = MockResponsesConfig::new(&server.uri()) + .with_root_config(&format!( + "chatgpt_base_url = '{}/backend-api/'", + server.uri() + )) + .enable_feature(Feature::Plugins); + for feature in [Feature::Apps, Feature::RemotePlugin, Feature::PluginSharing] { + config = if remote_features { + config.enable_feature(feature) } else { - Vec::new() + config.disable_feature(feature) }; - mount_installed_snapshot(&server, plugins).await; - Mock::given(method("GET")) - .and(path("/bundle")) - .respond_with(ResponseTemplate::new(200).set_body_bytes(bundle)) - .expect(expected_downloads) - .mount(&server) - .await; - assert_eq!(reconcile(&mut app_server).await?, expected); - // A turn exercises the loaded registry, not fresh hooks/list discovery. Hooks run - // on the app-server host even when the thread uses a remote executor. - assert_eq!( - turn_hook_runs( - &mut app_server, - &server, - thread.id.clone(), - active_plugin_ids - ) - .await?, - usize::from(scope == "WORKSPACE" && enabled && capabilities.has_hooks), - ); - server.verify().await; - server.reset().await; } - - // Uninstall must report removed capabilities and stop already-loaded hooks. - mount_installed_snapshot(&server, Vec::new()).await; - assert_eq!( - reconcile(&mut app_server).await?, - PluginReconcileResponse { - changed_plugins: vec![first], - ..Default::default() - } - ); - assert_eq!( - turn_hook_runs(&mut app_server, &server, thread.id.clone(), Vec::new()).await?, - 0 - ); - server.verify().await; - server.reset().await; - - // The next RPC must honor the latest config without contacting the plugin service. - let config_path = codex_home.path().join("config.toml"); - let config = std::fs::read_to_string(&config_path)?; - std::fs::write( - config_path, - config.replace("plugins = true", "plugins = false"), - )?; - assert_eq!( - reconcile(&mut app_server).await?, - PluginReconcileResponse::default() - ); - let requests = server.received_requests().await.expect("recorded requests"); - assert!(requests.iter().all(|request| { - !request.url.path().starts_with("/backend-api/ps/plugins/") - && request.url.path() != "/bundle" - })); - Ok(()) -} - -async fn turn_hook_runs( - app_server: &mut TestAppServer, - server: &MockServer, - thread_id: String, - active_plugin_ids: Vec, -) -> Result { - Mock::given(method("POST")) - .and(path("/backend-api/codex/analytics-events/events")) - .respond_with(ResponseTemplate::new(200)) - .mount(server) - .await; - let _response = responses::mount_sse_once( - server, - responses::sse(vec![ - responses::ev_response_created("response"), - responses::ev_completed("response"), - ]), - ) - .await; - app_server.clear_message_buffer(); - let completed = timeout( - DEFAULT_TIMEOUT, - app_server.start_turn_and_wait_for_completion(TurnStartParams { - thread_id: thread_id.clone(), - input: vec![UserInput::Text { - text: "run hooks".to_string(), - text_elements: Vec::new(), - }], - ..Default::default() - }), - ) - .await??; - assert_eq!(completed.turn.status, TurnStatus::Completed); - let event = wait_for_matching_analytics_event(server, DEFAULT_TIMEOUT, |event| { - event["event_type"] == "codex_turn_event" - && event["event_params"]["turn_id"] == completed.turn.id - }) - .await?; - assert_eq!(event["event_params"]["thread_id"], thread_id); - assert_eq!( - event["event_params"]["active_plugin_ids_at_turn_start"], - json!(active_plugin_ids) - ); - Ok(app_server - .pending_notification_methods() - .iter() - .filter(|method| method.as_str() == "hook/started") - .count()) -} - -async fn reconcile(app_server: &mut TestAppServer) -> Result { - let request = app_server - .send_raw_request( - "plugin/reconcile", - Some(json!({"reason": "tooling_changed"})), - ) - .await?; - timeout(DEFAULT_TIMEOUT, app_server.read_response(request)).await? -} - -async fn start_app_server(server: &MockServer) -> Result<(TestAppServer, TempDir)> { - let codex_home = TempDir::new()?; - let base_url = format!("{}/backend-api/", server.uri()); - MockResponsesConfig::new(&server.uri()) - .with_root_config(&format!("chatgpt_base_url = \"{base_url}\"")) - .disable_feature(Feature::Apps) - .enable_feature(Feature::Plugins) - .enable_feature(Feature::CodexHooks) - .disable_feature(Feature::RemotePlugin) - .disable_feature(Feature::PluginSharing) - .write(codex_home.path())?; + config.write(codex_home.path())?; write_chatgpt_auth( codex_home.path(), ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), + .account_id("account-original") + .chatgpt_user_id("user-original") + .chatgpt_account_id("account-original"), AuthCredentialsStoreMode::File, )?; - let app_server = TestAppServer::builder() + let skill = codex_home.path().join("skills/local/SKILL.md"); + let plugin = codex_home + .path() + .join("plugins/cache/local/sample/local/.codex-plugin/plugin.json"); + for (file, content) in [(&skill, "local skill"), (&plugin, "{\"name\":\"sample\"}")] { + std::fs::create_dir_all(file.parent().expect("local fixture has a parent"))?; + std::fs::write(file, content)?; + } + let original_config = std::fs::read(codex_home.path().join("config.toml"))?; + let mut app_server = TestAppServer::builder() .with_codex_home(codex_home.path()) .without_managed_config() - .with_env_overrides(&[( - "CODEX_TEST_ALLOW_HTTP_REMOTE_PLUGIN_BUNDLE_DOWNLOADS", - Some("1"), - )]) + .with_env_overrides(&[("OPENAI_API_KEY", None)]) .build_initialized_with_timeout(DEFAULT_TIMEOUT) .await?; - Ok((app_server, codex_home)) -} - -async fn mount_installed_snapshot(server: &MockServer, plugins: Vec) { - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/installed")) - .and(query_param("includeDownloadUrls", "true")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "plugins": plugins, - "pagination": { "limit": 200, "next_page_token": null }, - }))) - .expect(1) - .mount(server) - .await; -} - -fn installed_plugin(version: &str, bundle_url: &str, scope: &str) -> Value { - json!({ - "id": REMOTE_PLUGIN_ID, - "name": "linear", - "scope": scope, - "discoverability": (scope == "WORKSPACE").then_some("LISTED"), - "installation_policy": "AVAILABLE", - "authentication_policy": "ON_USE", - "release": { - "version": version, - "display_name": "Linear", - "description": "Track work in Linear", - "bundle_download_url": bundle_url, - "interface": {}, - }, - "enabled": true, - }) + for (account, reason) in [ + ("account-one", "startup"), + ("account-two", "account_changed"), + ] { + let token = encode_id_token( + &ChatGptIdTokenClaims::new() + .email("local@example.test") + .plan_type("enterprise") + .chatgpt_account_id(account), + )?; + let login = app_server + .send_chatgpt_auth_tokens_login_request( + token, + account.into(), + Some("enterprise".into()), + ) + .await?; + let _: LoginAccountResponse = + timeout(DEFAULT_TIMEOUT, app_server.read_response(login)).await??; + let reconcile = app_server + .send_raw_request("plugin/reconcile", Some(json!({"reason": reason}))) + .await?; + let response: PluginReconcileResponse = + timeout(DEFAULT_TIMEOUT, app_server.read_response(reconcile)).await??; + assert_eq!(response, PluginReconcileResponse::default()); + assert_eq!(std::fs::read_to_string(&skill)?, "local skill"); + assert_eq!(std::fs::read_to_string(&plugin)?, "{\"name\":\"sample\"}"); + assert_eq!( + std::fs::read(codex_home.path().join("config.toml"))?, + original_config + ); + } + assert!(!codex_home.path().join(".tmp/plugins").exists()); + assert!( + !codex_home + .path() + .join("plugins/cache/openai-curated-remote") + .exists() + ); + assert!( + server + .received_requests() + .await + .expect("wiremock records requests") + .iter() + .all(|request| { + !request.url.path().contains("/ps/plugins/") && request.url.path() != "/bundle" + }) + ); + Ok(()) } diff --git a/codex-rs/app-server/tests/suite/v2/plugin_share.rs b/codex-rs/app-server/tests/suite/v2/plugin_share.rs index 06ca0a5874ea..ba5fe2d7a2ba 100644 --- a/codex-rs/app-server/tests/suite/v2/plugin_share.rs +++ b/codex-rs/app-server/tests/suite/v2/plugin_share.rs @@ -1284,6 +1284,8 @@ chatgpt_base_url = "{base_url}" [features] plugins = true +remote_plugin = true +plugin_sharing = true "# ), ) diff --git a/codex-rs/app-server/tests/suite/v2/plugin_uninstall.rs b/codex-rs/app-server/tests/suite/v2/plugin_uninstall.rs index 1e0d5d83e8e0..c44504c6b3f1 100644 --- a/codex-rs/app-server/tests/suite/v2/plugin_uninstall.rs +++ b/codex-rs/app-server/tests/suite/v2/plugin_uninstall.rs @@ -596,6 +596,8 @@ chatgpt_base_url = "{base_url}" [features] plugins = true +remote_plugin = true +plugin_sharing = true "# ), ) diff --git a/codex-rs/app-server/tests/suite/v2/recommended_plugins.rs b/codex-rs/app-server/tests/suite/v2/recommended_plugins.rs index 0d8ddf5ac7f7..f5bb9acd207f 100644 --- a/codex-rs/app-server/tests/suite/v2/recommended_plugins.rs +++ b/codex-rs/app-server/tests/suite/v2/recommended_plugins.rs @@ -21,6 +21,7 @@ use serde_json::Value; use serde_json::json; use std::time::Duration; use tempfile::TempDir; +use test_case::test_case; use tokio::time::timeout; use wiremock::Mock; use wiremock::ResponseTemplate; @@ -36,19 +37,27 @@ enum ToolSuggestFeature { Disabled, } +#[test_case(false; "default remote features")] +#[test_case(true; "explicit remote features")] #[tokio::test] -async fn first_turn_after_external_login_waits_for_recommended_plugins() -> Result<()> { - recommended_plugins_after_external_login(ToolSuggestFeature::Enabled).await +async fn first_turn_after_external_login_preserves_local_plugins( + remote_features: bool, +) -> Result<()> { + recommended_plugins_after_external_login(ToolSuggestFeature::Enabled, remote_features).await } +#[test_case(false; "default remote features")] +#[test_case(true; "explicit remote features")] #[tokio::test] -async fn first_turn_after_external_login_waits_for_recommended_plugins_without_tool_suggest() --> Result<()> { - recommended_plugins_after_external_login(ToolSuggestFeature::Disabled).await +async fn first_turn_after_external_login_preserves_local_plugins_without_tool_suggest( + remote_features: bool, +) -> Result<()> { + recommended_plugins_after_external_login(ToolSuggestFeature::Disabled, remote_features).await } async fn recommended_plugins_after_external_login( tool_suggest_feature: ToolSuggestFeature, + remote_features: bool, ) -> Result<()> { let tool_suggest_enabled = matches!(tool_suggest_feature, ToolSuggestFeature::Enabled); let recommended_plugins_config = if tool_suggest_enabled { @@ -73,7 +82,7 @@ async fn recommended_plugins_after_external_login( }] })), ) - .expect(1) + .expect(u64::from(remote_features)) .mount(&server) .await; let response = responses::sse(vec![ @@ -92,12 +101,20 @@ async fn recommended_plugins_after_external_login( let config_path = codex_home.path().join("config.toml"); let config = std::fs::read_to_string(&config_path)?; std::fs::write( - config_path, + &config_path, format!( - "{config}\n[features]\napps = true\nplugins = true\ntool_suggest = {tool_suggest_enabled}\n{recommended_plugins_config}" + "{config}\n[features]\napps = true\nplugins = true\nremote_plugin = {remote_features}\nplugin_sharing = {remote_features}\ntool_suggest = {tool_suggest_enabled}\n{recommended_plugins_config}" ), )?; + let original_config = std::fs::read(&config_path)?; + let local_skill = codex_home.path().join("skills/local/SKILL.md"); + std::fs::create_dir_all(local_skill.parent().expect("skill parent"))?; + std::fs::write( + &local_skill, + "---\nname: local\ndescription: local only\n---\nbody\n", + )?; + let original_skill = std::fs::read(&local_skill)?; let sqlite_home = codex_home.path().to_string_lossy(); let mut app_server = TestAppServer::builder() .with_codex_home(codex_home.path()) @@ -130,8 +147,8 @@ async fn recommended_plugins_after_external_login( LoginAccountResponse::ChatgptAuthTokens {} ); - // Login clears the recommendation cache after its RPC response. Wait for completion so - // thread startup and the background refresh share the same cache generation. + // Wait for account completion before checking that optional catalog reads + // leave the local installation unchanged. let notification = timeout( DEFAULT_READ_TIMEOUT, app_server.read_stream_until_notification_message("account/login/completed"), @@ -199,14 +216,29 @@ async fn recommended_plugins_after_external_login( .into_iter() .filter(|text| text.starts_with("")) .collect::>(); - assert_eq!( - recommendations, - vec![concat!( - "\n", - "Here is a list of plugins that are available but not installed.\n\n", - "- GitHub (github@openai-curated-remote)\n", - "", - )] + assert_eq!(recommendations.is_empty(), !remote_features); + if remote_features { + assert!( + recommendations + .iter() + .any(|text| text.contains("GitHub (github@openai-curated-remote)")) + ); + } + assert_eq!(std::fs::read(&config_path)?, original_config); + assert_eq!(std::fs::read(&local_skill)?, original_skill); + assert!( + !codex_home + .path() + .join("plugins/cache/openai-curated-remote") + .exists() + ); + assert!( + server + .received_requests() + .await + .expect("requests") + .iter() + .all(|request| { request.url.path() != "/bundle" }) ); let body = request.body_json(); let tool_names = body @@ -216,10 +248,12 @@ async fn recommended_plugins_after_external_login( .flatten() .filter_map(|tool| tool.get("name").and_then(Value::as_str)) .collect::>(); - assert_eq!( - tool_names.contains(&"request_plugin_install"), - tool_suggest_enabled - ); - assert!(!tool_names.contains(&"list_available_plugins_to_install")); + if remote_features { + assert_eq!( + tool_names.contains(&"request_plugin_install"), + tool_suggest_enabled + ); + assert!(!tool_names.contains(&"list_available_plugins_to_install")); + } Ok(()) } diff --git a/codex-rs/app-server/tests/suite/v2/skills_list.rs b/codex-rs/app-server/tests/suite/v2/skills_list.rs index a72104a0b01d..d65dd7b9eba3 100644 --- a/codex-rs/app-server/tests/suite/v2/skills_list.rs +++ b/codex-rs/app-server/tests/suite/v2/skills_list.rs @@ -18,8 +18,6 @@ use codex_app_server_protocol::ExperimentalFeatureEnablementSetResponse; use codex_app_server_protocol::MergeStrategy; use codex_app_server_protocol::PermissionProfileListParams; use codex_app_server_protocol::PermissionProfileListResponse; -use codex_app_server_protocol::PluginListParams; -use codex_app_server_protocol::PluginListResponse; use codex_app_server_protocol::SkillScope; use codex_app_server_protocol::SkillsChangedNotification; use codex_app_server_protocol::SkillsExtraRootsSetParams; @@ -43,14 +41,7 @@ use pretty_assertions::assert_eq; use tempfile::TempDir; use test_case::test_case; use tokio::time::timeout; -use wiremock::Mock; use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::header; -use wiremock::matchers::method; -use wiremock::matchers::path; -use wiremock::matchers::query_param; -use wiremock::matchers::query_param_is_missing; const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30); const WATCHER_TIMEOUT: Duration = Duration::from_secs(20); @@ -365,7 +356,7 @@ async fn skills_list_runtime_enable_refreshes_shared_system_skill_cache() -> Res } #[tokio::test] -async fn runtime_remote_plugin_toggle_updates_local_curated_plugin_skills() -> Result<()> { +async fn runtime_remote_plugin_toggle_preserves_local_curated_plugin_skills() -> Result<()> { let codex_home = TempDir::new()?; let cwd = TempDir::new()?; let server = MockServer::start().await; @@ -472,26 +463,36 @@ enabled = true let SkillsListResponse { data } = timeout(DEFAULT_TIMEOUT, mcp.read_response(skills_list_request_id)).await??; - assert!(data.iter().all(|entry| { - entry - .skills - .iter() - .all(|skill| skill.name != "google-calendar:meeting-prep") + assert!(data.iter().any(|entry| { + entry.skills.iter().any(|skill| { + skill.name == "google-calendar:meeting-prep" + && skill.description == "Updated meeting preparation" + }) })); Ok(()) } #[tokio::test] -async fn skills_list_loads_remote_installed_plugin_skills_from_cache() -> Result<()> { +async fn skills_list_preserves_configured_cached_plugin_without_account_sync() -> Result<()> { let codex_home = TempDir::new()?; let cwd = TempDir::new()?; let server = MockServer::start().await; let expected_skill_path = std::fs::canonicalize(write_cached_remote_plugin_with_skill(codex_home.path())?)?; + let original_skill = std::fs::read(&expected_skill_path)?; write_plugins_enabled_config_with_base_url( codex_home.path(), &format!("{}/backend-api/", server.uri()), )?; + let config_path = codex_home.path().join("config.toml"); + let config = std::fs::read_to_string(&config_path)?; + std::fs::write( + &config_path, + format!( + "{config}remote_plugin = true\nplugin_sharing = true\napps = true\n\n[plugins.\"linear@openai-curated-remote\"]\nenabled = true\n" + ), + )?; + let original_config = std::fs::read(&config_path)?; write_chatgpt_auth( codex_home.path(), ChatGptAuthFixture::new("chatgpt-token") @@ -500,171 +501,56 @@ async fn skills_list_loads_remote_installed_plugin_skills_from_cache() -> Result .chatgpt_account_id("account-123"), AuthCredentialsStoreMode::File, )?; - - let global_directory_body = r#"{ - "plugins": [ - { - "id": "plugins~Plugin_linear", - "name": "linear", - "scope": "GLOBAL", - "installation_policy": "AVAILABLE", - "authentication_policy": "ON_USE", - "release": { - "display_name": "Linear", - "description": "Track work in Linear", - "app_ids": [], - "interface": {}, - "skills": [] - } - } - ], - "pagination": { - "limit": 50, - "next_page_token": null - } -}"#; - let global_installed_body = r#"{ - "plugins": [ - { - "id": "plugins~Plugin_linear", - "name": "linear", - "scope": "GLOBAL", - "installation_policy": "AVAILABLE", - "authentication_policy": "ON_USE", - "release": { - "display_name": "Linear", - "description": "Track work in Linear", - "app_ids": [], - "interface": {}, - "skills": [] - }, - "enabled": true, - "disabled_skill_names": [] - } - ], - "pagination": { - "limit": 50, - "next_page_token": null - } -}"#; - let empty_page_body = r#"{ - "plugins": [], - "pagination": { - "limit": 50, - "next_page_token": null - } -}"#; - - for (scope, body) in [ - ("GLOBAL", global_directory_body), - ("WORKSPACE", empty_page_body), - ] { - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/list")) - .and(query_param("scope", scope)) - .and(query_param("limit", "200")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .respond_with(ResponseTemplate::new(200).set_body_string(body)) - .mount(&server) - .await; - } let mut mcp = TestAppServer::builder() .with_codex_home(codex_home.path()) .without_auto_env() .build_initialized_with_timeout(DEFAULT_TIMEOUT) .await?; - - let stale_skills_list_request_id = mcp - .send_skills_list_request(SkillsListParams { - cwds: vec![cwd.path().to_path_buf()], - force_reload: true, - }) - .await?; - let SkillsListResponse { data } = timeout( - DEFAULT_TIMEOUT, - mcp.read_response(stale_skills_list_request_id), - ) - .await??; - assert_eq!(data.len(), 1); - assert!( - data[0] + for force_reload in [true, false, true] { + let request_id = mcp + .send_skills_list_request(SkillsListParams { + cwds: vec![cwd.path().to_path_buf()], + force_reload, + }) + .await?; + let SkillsListResponse { data } = + timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??; + assert_eq!(data.len(), 1); + assert_eq!(data[0].errors, Vec::new()); + let skill = data[0] .skills .iter() - .all(|skill| skill.name != "linear:triage-issues"), - "remote installed plugin cache has not been refreshed yet" - ); - - for (scope, body) in [ - ("GLOBAL", global_installed_body), - ("USER", empty_page_body), - ("WORKSPACE", empty_page_body), - ] { - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/installed")) - .and(query_param("scope", scope)) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .respond_with(ResponseTemplate::new(200).set_body_string(body)) - .mount(&server) - .await; + .find(|skill| skill.name == "linear:triage-issues") + .expect("configured cached plugin remains available without remote refresh"); + assert_eq!( + std::fs::canonicalize(skill.path.as_str())?, + expected_skill_path + ); + assert_eq!( + (skill.enabled, skill.plugin_id.as_deref()), + (true, Some("linear@openai-curated-remote")) + ); + let request_id = mcp + .send_raw_request("plugin/reconcile", Some(serde_json::json!({}))) + .await?; + let response: codex_app_server_protocol::PluginReconcileResponse = + timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??; + assert_eq!( + response, + codex_app_server_protocol::PluginReconcileResponse::default() + ); } - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/installed")) - .and(query_param_is_missing("scope")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .respond_with(ResponseTemplate::new(200).set_body_string(global_installed_body)) - .mount(&server) - .await; - - let plugin_list_request_id = mcp - .send_plugin_list_request(PluginListParams { - cwds: None, - marketplace_kinds: None, - force_refetch: false, - }) - .await?; - let _: PluginListResponse = - timeout(DEFAULT_TIMEOUT, mcp.read_response(plugin_list_request_id)).await??; - - let SkillsListResponse { data } = timeout(DEFAULT_TIMEOUT, async { - loop { - let skills_list_request_id = mcp - .send_skills_list_request(SkillsListParams { - cwds: vec![cwd.path().to_path_buf()], - force_reload: false, - }) - .await?; - let response: SkillsListResponse = - timeout(DEFAULT_TIMEOUT, mcp.read_response(skills_list_request_id)).await??; - if response.data.iter().any(|entry| { - entry - .skills - .iter() - .any(|skill| skill.name == "linear:triage-issues") - }) { - break Ok::(response); - } - tokio::time::sleep(Duration::from_millis(50)).await; - } - }) - .await??; - - assert_eq!(data.len(), 1); - assert_eq!(data[0].errors, Vec::new()); - let skill = data[0] - .skills - .iter() - .find(|skill| skill.name == "linear:triage-issues") - .expect("expected skill from cached remote plugin"); - assert_eq!( - std::fs::canonicalize(skill.path.as_str())?, - expected_skill_path - ); - assert_eq!( - (skill.enabled, skill.plugin_id.as_deref()), - (true, Some("linear@openai-curated-remote")), + assert_eq!(std::fs::read(&expected_skill_path)?, original_skill); + assert_eq!(std::fs::read(&config_path)?, original_config); + assert!( + server + .received_requests() + .await + .expect("requests") + .iter() + .all(|request| { + !request.url.path().contains("/ps/plugins/") && request.url.path() != "/bundle" + }) ); Ok(()) } diff --git a/codex-rs/app-server/tests/suite/v2/turn_cost_otel.rs b/codex-rs/app-server/tests/suite/v2/turn_cost_otel.rs index f9a06f2e47e3..0abb56f7d03a 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_cost_otel.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_cost_otel.rs @@ -1,6 +1,7 @@ //! Exercises the best-effort SiWC cost happy path through real app-server startup and OTLP. //! The public in-process transport permits advancing the production timer without test-only hooks. +use anyhow::Context; use anyhow::Result; use app_test_support::ChatGptAuthFixture; use app_test_support::write_chatgpt_auth; @@ -94,6 +95,9 @@ approval_policy = "never" responses_websockets = false responses_websockets_v2 = false runtime_metrics = true +[model_providers.openai] +request_max_retries = 0 +stream_max_retries = 0 [analytics] enabled = true [otel] @@ -141,39 +145,44 @@ metrics_exporter = {{ otlp-http = {{ endpoint = "{}/metrics", protocol = "json" } else { EnvironmentManager::default_for_tests() }; - let mut client = in_process::start(InProcessStartArgs { - arg0_paths: Arg0DispatchPaths::default(), - config, - cli_overrides: Vec::new(), - loader_overrides, - strict_config: false, - cloud_config_bundle: CloudConfigBundleLoader::default(), - embedded_network_policy: Default::default(), - thread_config_loader: Arc::new(NoopThreadConfigLoader), - feedback: CodexFeedback::new(), - log_db: None, - state_db: None, - environment_manager: Arc::new(environment_manager), - config_warnings: Vec::new(), - session_source: SessionSource::Cli, - enable_codex_api_key_env: false, - initialize: InitializeParams { - client_info: ClientInfo { - name: "codex-app-server-tests".to_string(), - title: None, - version: "test".to_string(), + let mut client = timeout( + Duration::from_secs(20), + in_process::start(InProcessStartArgs { + arg0_paths: Arg0DispatchPaths::default(), + config, + cli_overrides: Vec::new(), + loader_overrides, + strict_config: false, + cloud_config_bundle: CloudConfigBundleLoader::default(), + embedded_network_policy: Default::default(), + thread_config_loader: Arc::new(NoopThreadConfigLoader), + feedback: CodexFeedback::new(), + log_db: None, + state_db: None, + environment_manager: Arc::new(environment_manager), + config_warnings: Vec::new(), + session_source: SessionSource::Cli, + enable_codex_api_key_env: false, + initialize: InitializeParams { + client_info: ClientInfo { + name: "codex-app-server-tests".to_string(), + title: None, + version: "test".to_string(), + }, + capabilities: Some(InitializeCapabilities { + experimental_api: true, + ..Default::default() + }), }, - capabilities: Some(InitializeCapabilities { - experimental_api: true, - ..Default::default() - }), - }, - channel_capacity: in_process::DEFAULT_IN_PROCESS_CHANNEL_CAPACITY, - }) - .await?; + channel_capacity: in_process::DEFAULT_IN_PROCESS_CHANNEL_CAPACITY, + }), + ) + .await + .context("in-process startup timed out")??; wait_for_cost_queries(&server, /*count*/ 1).await; - let response = client - .request(ClientRequest::ThreadStart { + let response = timeout( + Duration::from_secs(20), + client.request(ClientRequest::ThreadStart { request_id: RequestId::Integer(1), params: ThreadStartParams { environments: Some(vec![TurnEnvironmentParams { @@ -183,12 +192,15 @@ metrics_exporter = {{ otlp-http = {{ endpoint = "{}/metrics", protocol = "json" }]), ..Default::default() }, - }) - .await? - .expect("thread/start"); + }), + ) + .await + .context("thread/start timed out")?? + .expect("thread/start"); let ThreadStartResponse { thread, .. } = serde_json::from_value(response)?; - let response = client - .request(ClientRequest::TurnStart { + let response = timeout( + Duration::from_secs(20), + client.request(ClientRequest::TurnStart { request_id: RequestId::Integer(2), params: TurnStartParams { thread_id: thread.id.clone(), @@ -198,11 +210,13 @@ metrics_exporter = {{ otlp-http = {{ endpoint = "{}/metrics", protocol = "json" }], ..Default::default() }, - }) - .await? - .expect("turn/start"); + }), + ) + .await + .context("turn/start timed out")?? + .expect("turn/start"); let TurnStartResponse { turn } = serde_json::from_value(response)?; - timeout(Duration::from_secs(/*secs*/ 30), async { + timeout(Duration::from_secs(/*secs*/ 20), async { while let Some(event) = client.next_event().await { if let InProcessServerEvent::ServerNotification(event) = event && let ServerNotification::TurnCompleted(event) = *event @@ -216,7 +230,8 @@ metrics_exporter = {{ otlp-http = {{ endpoint = "{}/metrics", protocol = "json" } } }) - .await?; + .await + .context("model turn did not complete")?; assert_eq!( model.single_request().header("authorization").as_deref(), Some("Bearer siwc-token") @@ -226,7 +241,7 @@ metrics_exporter = {{ otlp-http = {{ endpoint = "{}/metrics", protocol = "json" tokio::time::resume(); wait_for_cost_queries(&server, /*count*/ 2).await; // Synchronize with actual recording, not just the backend receiving a request. - timeout(Duration::from_secs(/*secs*/ 10), async { + timeout(Duration::from_secs(/*secs*/ 30), async { loop { if metrics .snapshot() @@ -240,12 +255,20 @@ metrics_exporter = {{ otlp-http = {{ endpoint = "{}/metrics", protocol = "json" tokio::task::yield_now().await; } }) - .await?; + .await + .context("turn cost metric was not recorded")?; tokio::time::pause(); tokio::time::advance(Duration::from_secs(/*secs*/ 301)).await; tokio::time::resume(); - client.shutdown().await?; - tokio::task::spawn_blocking(move || provider.shutdown()).await?; + timeout(Duration::from_secs(10), client.shutdown()) + .await + .context("app-server shutdown timed out")??; + timeout( + Duration::from_secs(10), + tokio::task::spawn_blocking(move || provider.shutdown()), + ) + .await + .context("OTLP shutdown timed out")??; let mut points = Vec::new(); for request in collector.received_requests().await.expect("OTLP requests") { let body: Value = serde_json::from_slice(&request.body)?; diff --git a/codex-rs/cli/src/mcp_login_tests.rs b/codex-rs/cli/src/mcp_login_tests.rs index 4ee245524de3..a83f1fa32785 100644 --- a/codex-rs/cli/src/mcp_login_tests.rs +++ b/codex-rs/cli/src/mcp_login_tests.rs @@ -36,11 +36,7 @@ fn callback_line_is_bounded_and_does_not_expose_input_in_errors() { read_callback_line(Cursor::new("")).unwrap_err().to_string(), "No OAuth callback URL received before input closed" ); - assert_eq!( - format!( - "{:?}", - read_callback_line(Cursor::new(b"sensitive\xff")).unwrap_err() - ), - "OAuth callback URL must be valid UTF-8" - ); + let error = read_callback_line(Cursor::new(b"sensitive\xff")).unwrap_err(); + assert_eq!(error.to_string(), "OAuth callback URL must be valid UTF-8"); + assert!(!format!("{error:?}").contains("sensitive")); } diff --git a/codex-rs/cli/tests/app_server_daemon/package.rs b/codex-rs/cli/tests/app_server_daemon/package.rs index 6c010c59d41e..6831fa938004 100644 --- a/codex-rs/cli/tests/app_server_daemon/package.rs +++ b/codex-rs/cli/tests/app_server_daemon/package.rs @@ -193,7 +193,8 @@ fn packaged_daemon_launch(action: &str, initial: InitialDaemon) -> Result<()> { assert_eq!(standalone.join("current").canonicalize()?, cli_selection); } if action == "bootstrap" { - assert_eq!(output["autoUpdateEnabled"], false); + // The daemon defaults to automatic updates unless overridden in settings. + assert_eq!(output["autoUpdateEnabled"], true); } Ok(()) } diff --git a/codex-rs/cli/tests/app_server_daemon/support.rs b/codex-rs/cli/tests/app_server_daemon/support.rs index 5a2a0d5170d7..b613c176475d 100644 --- a/codex-rs/cli/tests/app_server_daemon/support.rs +++ b/codex-rs/cli/tests/app_server_daemon/support.rs @@ -75,6 +75,7 @@ impl TestDaemon { pub(super) fn command(&self) -> Command { let mut command = Command::new(&self.codex); command.env("CODEX_HOME", self.home.path()); + command.env("RUST_LIB_BACKTRACE", "0"); command } diff --git a/codex-rs/cli/tests/cloud_auth.rs b/codex-rs/cli/tests/cloud_auth.rs index 01e7eb87e38f..6769c9485858 100644 --- a/codex-rs/cli/tests/cloud_auth.rs +++ b/codex-rs/cli/tests/cloud_auth.rs @@ -37,6 +37,7 @@ async fn cloud_list_only_allows_trusted_credential_destinations() -> Result<()> command .current_dir(codex_home.path()) .env("CODEX_HOME", codex_home.path()) + .env("RUST_LIB_BACKTRACE", "0") .env_remove("CODEX_ACCESS_TOKEN") .env_remove("OPENAI_API_KEY") .env_remove("CODEX_CLOUD_TASKS_MODE") diff --git a/codex-rs/cli/tests/features.rs b/codex-rs/cli/tests/features.rs index 6da9fd9325fe..00dc12f0bbe5 100644 --- a/codex-rs/cli/tests/features.rs +++ b/codex-rs/cli/tests/features.rs @@ -22,6 +22,7 @@ use wiremock::matchers::path; fn codex_command(codex_home: &Path) -> Result { let mut cmd = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?); cmd.env("CODEX_HOME", codex_home); + cmd.env("RUST_LIB_BACKTRACE", "0"); Ok(cmd) } diff --git a/codex-rs/cli/tests/mcp_add_remove.rs b/codex-rs/cli/tests/mcp_add_remove.rs index 16bb2c455ad0..0c690955b8f6 100644 --- a/codex-rs/cli/tests/mcp_add_remove.rs +++ b/codex-rs/cli/tests/mcp_add_remove.rs @@ -17,6 +17,7 @@ use wiremock::matchers::path; fn codex_command(codex_home: &Path) -> Result { let mut cmd = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?); cmd.env("CODEX_HOME", codex_home); + cmd.env("RUST_LIB_BACKTRACE", "0"); Ok(cmd) } diff --git a/codex-rs/codex-api/src/sse/responses.rs b/codex-rs/codex-api/src/sse/responses.rs index 67f627e60173..7baea6a10650 100644 --- a/codex-rs/codex-api/src/sse/responses.rs +++ b/codex-rs/codex-api/src/sse/responses.rs @@ -4,7 +4,6 @@ use crate::common::ResponseStream; use crate::common::SafetyBuffering; use crate::common::SafetyBufferingTreatment; use crate::error::ApiError; -use crate::error::parse_terminal_provider_error; use crate::guardian_assessment::parse_guardian_assessment; use crate::rate_limits::parse_all_rate_limits; use crate::safety_buffering::treatment_from_headers; @@ -377,11 +376,11 @@ pub fn process_responses_event( ) -> std::result::Result, ResponsesEventError> { match event.kind.as_str() { "error" => { - if let Some(error) = - parse_terminal_provider_error(event.error.as_ref(), /*status*/ None) - { - return Err(ResponsesEventError::Api(error)); - } + // Standalone error events carry the same provider error codes and + // Retry-After headers as response.failed events. Parse both alike. + return Err(ResponsesEventError::Api(parse_failed_response(Some( + serde_json::json!({ "error": event.error }), + )))); } "response.output_item.done" => { if let Some(item_val) = event.item { diff --git a/codex-rs/codex-api/src/sse/responses_error_tests.rs b/codex-rs/codex-api/src/sse/responses_error_tests.rs index 83c3533287b6..8bd998412382 100644 --- a/codex-rs/codex-api/src/sse/responses_error_tests.rs +++ b/codex-rs/codex-api/src/sse/responses_error_tests.rs @@ -72,6 +72,32 @@ async fn policy_capacity_classification_preserves_overload_retry_behavior() { } } +/// Standalone stream errors must preserve the provider's capacity classification +/// and retry deadline, including WebSocket events with a top-level HTTP status. +#[tokio::test(start_paused = true)] +async fn standalone_stream_overload_errors_keep_classification_and_retry_advice() { + for (code, expected) in [ + ("server_is_overloaded", CodexErrorInfo::ServerOverloaded), + ( + "policy_capacity_unavailable", + CodexErrorInfo::PolicyCapacityUnavailable, + ), + ] { + let event = serde_json::from_value(json!({ + "type": "error", + "status": 503, + "error": {"code": code, "headers": {"Retry-After": "4"}} + })) + .unwrap(); + let error = map_api_error(process_responses_event(event).unwrap_err().into_api_error()); + assert_eq!(error.to_codex_protocol_error(), expected); + assert_eq!( + error.retry_delay(/*retry_count*/ 1), + Some(Duration::from_secs(4)) + ); + } +} + /// Flex failures remain terminal even with retry headers and a later completed event. #[tokio::test(start_paused = true)] async fn flex_failure_with_retry_header_ends_stream_immediately() { diff --git a/codex-rs/config/src/config_toml.rs b/codex-rs/config/src/config_toml.rs index 2578c59d9c07..5b88c544faaa 100644 --- a/codex-rs/config/src/config_toml.rs +++ b/codex-rs/config/src/config_toml.rs @@ -945,6 +945,10 @@ pub fn validate_reserved_model_provider_ids( return provider != &ModelProviderInfo { model_catalog_url: provider.model_catalog_url.clone(), + request_max_retries: provider.request_max_retries, + stream_max_retries: provider.stream_max_retries, + stream_idle_timeout_ms: provider.stream_idle_timeout_ms, + websocket_connect_timeout_ms: provider.websocket_connect_timeout_ms, ..Default::default() }; } diff --git a/codex-rs/config/src/model_provider_requirements_tests.rs b/codex-rs/config/src/model_provider_requirements_tests.rs index 0862dcfdee6e..4c43f7fe504b 100644 --- a/codex-rs/config/src/model_provider_requirements_tests.rs +++ b/codex-rs/config/src/model_provider_requirements_tests.rs @@ -20,6 +20,33 @@ requires_openai_auth = true X-Managed = "yes" "#; +#[test] +fn openai_transport_budgets_load_without_allowing_provider_replacement() -> anyhow::Result<()> { + let config: crate::config_toml::ConfigToml = toml::from_str( + "[model_providers.openai]\nrequest_max_retries = 0\nstream_max_retries = 0\nstream_idle_timeout_ms = 250\nwebsocket_connect_timeout_ms = 100", + )?; + let provider = &config.model_providers["openai"]; + assert_eq!(provider.request_max_retries, Some(0)); + assert_eq!(provider.stream_max_retries, Some(0)); + assert_eq!(provider.stream_idle_timeout_ms, Some(250)); + assert_eq!(provider.websocket_connect_timeout_ms, Some(100)); + for replacement in [ + "name = 'Replacement'", + "base_url = 'https://example.test/v1'", + "env_key = 'OTHER_KEY'", + "supports_websockets = true", + ] { + assert!( + toml::from_str::(&format!( + "[model_providers.openai]\nrequest_max_retries = 0\n{replacement}" + )) + .is_err(), + "transport overrides must not allow {replacement}" + ); + } + Ok(()) +} + #[test] fn higher_requirements_merge_provider_fields_and_nested_tables() -> anyhow::Result<()> { let cloud_source = RequirementSource::EnterpriseManaged { diff --git a/codex-rs/core-plugins/src/lib.rs b/codex-rs/core-plugins/src/lib.rs index 8b8f57f836da..63480e4da4c0 100644 --- a/codex-rs/core-plugins/src/lib.rs +++ b/codex-rs/core-plugins/src/lib.rs @@ -13,6 +13,7 @@ pub mod installed_marketplaces; mod loaded_cache_metrics; pub mod loader; mod manager; +pub use manager::AUTOMATIC_PLUGIN_UPDATES_ENABLED; pub mod manifest; pub mod marketplace; pub mod marketplace_add; diff --git a/codex-rs/core-plugins/src/manager.rs b/codex-rs/core-plugins/src/manager.rs index 96833721c87f..a16e63341cd7 100644 --- a/codex-rs/core-plugins/src/manager.rs +++ b/codex-rs/core-plugins/src/manager.rs @@ -156,6 +156,11 @@ use tokio::sync::watch; use tracing::instrument; use tracing::warn; +/// Codefx never changes local plugins or skills as a side effect of authentication, +/// startup, discovery, or a client reconciliation request. Feature flags only opt +/// into explicitly requested remote operations; they cannot enable background sync. +pub const AUTOMATIC_PLUGIN_UPDATES_ENABLED: bool = false; + static CURATED_REPO_SYNC_STARTED: AtomicBool = AtomicBool::new(false); const FEATURED_PLUGIN_IDS_CACHE_TTL: std::time::Duration = std::time::Duration::from_secs(60 * 60 * 3); @@ -760,7 +765,11 @@ impl PluginsManager { } fn remote_global_catalog_active(&self, config: &PluginsConfigInput) -> bool { - config.remote_plugin_enabled && self.auth_mode().is_some_and(AuthMode::uses_codex_backend) + // Catalog opt-in must not replace or hide an already installed local + // curated plugin when Codefx has disabled automatic reconciliation. + AUTOMATIC_PLUGIN_UPDATES_ENABLED + && config.remote_plugin_enabled + && self.auth_mode().is_some_and(AuthMode::uses_codex_backend) } /// Starts the local curated marketplace sync when the remote catalog is unavailable. @@ -769,6 +778,10 @@ impl PluginsManager { config: &PluginsConfigInput, on_effective_plugins_changed: Option, ) { + if !AUTOMATIC_PLUGIN_UPDATES_ENABLED { + return; + } + if config.plugins_enabled && !self.remote_global_catalog_active(config) && MarketplacePolicy::from_requirements(config.config_layer_stack.requirements()) @@ -1597,6 +1610,10 @@ impl PluginsManager { prefetch_recommendations: bool, on_effective_plugins_changed: Option, ) { + if !AUTOMATIC_PLUGIN_UPDATES_ENABLED { + return; + } + self.maybe_start_remote_installed_plugins_cache_refresh_with_notify( config, auth.clone(), @@ -1667,6 +1684,10 @@ impl PluginsManager { auth: Option, on_effective_plugins_changed: Option, ) { + if !AUTOMATIC_PLUGIN_UPDATES_ENABLED { + return; + } + if !config.plugins_enabled { return; } @@ -1854,6 +1875,10 @@ impl PluginsManager { scopes: BTreeSet, mode: RemoteCatalogCacheRefreshMode, ) { + if !AUTOMATIC_PLUGIN_UPDATES_ENABLED { + return; + } + if !config.plugins_enabled || scopes.is_empty() { return; } @@ -1873,6 +1898,10 @@ impl PluginsManager { options: PluginListBackgroundTaskOptions, on_effective_plugins_changed: Option, ) { + if !AUTOMATIC_PLUGIN_UPDATES_ENABLED { + return; + } + self.maybe_start_non_curated_plugin_cache_refresh(context, &options.local_marketplaces); self.maybe_start_remote_catalog_cache_refresh( &context.global_config, @@ -2890,6 +2919,10 @@ impl PluginsManager { on_effective_plugins_changed: Option, upgrade_warnings: mpsc::UnboundedSender, ) { + if !AUTOMATIC_PLUGIN_UPDATES_ENABLED { + return; + } + if config.plugins_enabled { self.maybe_start_curated_repo_sync_for_config( config, @@ -3108,6 +3141,10 @@ impl PluginsManager { context: &PluginMarketplaceContext, marketplaces: &[ConfiguredMarketplace], ) { + if !AUTOMATIC_PLUGIN_UPDATES_ENABLED { + return; + } + if let Some(request) = context.non_curated_cache_refresh_request( self, marketplaces, diff --git a/codex-rs/core-plugins/src/manager_tests.rs b/codex-rs/core-plugins/src/manager_tests.rs index 7439f7b03850..6cc323a6b7a4 100644 --- a/codex-rs/core-plugins/src/manager_tests.rs +++ b/codex-rs/core-plugins/src/manager_tests.rs @@ -1664,12 +1664,15 @@ enabled = true } #[tokio::test] -async fn remote_global_catalog_ignores_local_curated_plugins() { +async fn remote_catalog_opt_in_preserves_locally_installed_curated_plugins() { let codex_home = TempDir::new().unwrap(); write_file( &codex_home.path().join(CONFIG_TOML_FILE), r#"[features] plugins = true +remote_plugin = true +plugin_sharing = true +apps = true [plugins."linear@openai-curated"] enabled = true @@ -1701,7 +1704,8 @@ enabled = true assert_eq!( loaded_plugin_names(&manager, &config).await, vec![ - "linear@openai-curated-remote".to_string(), + "calendar@openai-curated".to_string(), + "linear@openai-curated".to_string(), "remote-only@openai-curated-remote".to_string(), ] ); @@ -1737,7 +1741,10 @@ enabled = true manager.write_remote_installed_plugins_cache(vec![remote_installed_plugin("remote-only")]); assert_eq!( loaded_plugin_names(&manager, &config).await, - vec!["remote-only@openai-curated-remote".to_string()] + vec![ + "linear@openai-curated".to_string(), + "remote-only@openai-curated-remote".to_string(), + ] ); set_test_auth_mode(&auth_manager, /*auth_mode*/ None).await; @@ -1767,7 +1774,10 @@ enabled = true set_test_auth_mode(&auth_manager, Some(AuthMode::Chatgpt)).await; assert_eq!( loaded_plugin_names(&manager, &config).await, - vec!["remote-only@openai-curated-remote".to_string()] + vec![ + "linear@openai-curated".to_string(), + "remote-only@openai-curated-remote".to_string(), + ] ); } @@ -6117,7 +6127,7 @@ plugins = true } #[tokio::test] -async fn remote_plugin_caches_refresh_warms_recommended_plugins_cache() { +async fn explicit_recommendation_fetch_warms_recommended_plugins_cache() { let tmp = tempfile::tempdir().unwrap(); write_file( &tmp.path().join(CONFIG_TOML_FILE), @@ -6144,23 +6154,13 @@ plugins = true let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); let cache_key = recommended_plugins_cache_key(&config); - manager.maybe_start_remote_plugin_caches_refresh( - &config, - Some(auth.clone()), - /*prefetch_recommendations*/ true, - /*on_effective_plugins_changed*/ None, + let mode = manager + .recommended_plugins_mode_for_config(&config, Some(&auth)) + .await; + assert_eq!( + manager.cached_recommended_plugins_mode(&cache_key), + Some(mode.clone()) ); - - let mode = tokio::time::timeout(Duration::from_secs(2), async { - loop { - if let Some(mode) = manager.cached_recommended_plugins_mode(&cache_key) { - break mode; - } - tokio::time::sleep(Duration::from_millis(10)).await; - } - }) - .await - .expect("recommended plugins cache should be warmed"); assert_eq!( mode, RecommendedPluginsMode::Endpoint { @@ -6797,7 +6797,7 @@ enabled = true } #[tokio::test] -async fn non_curated_plugin_cache_refresh_preserves_manual_priority() { +async fn non_curated_background_refresh_never_replaces_manual_request() { let codex_home = TempDir::new().unwrap(); let marketplace_root = codex_home.path().join("marketplace"); fs::create_dir_all(marketplace_root.join(".git")).unwrap(); @@ -6905,12 +6905,12 @@ enabled = true .read() .expect("refresh state lock"); let request = state.requested.as_ref().expect("pending refresh"); - assert!(matches!(request.git_mode, PluginGitMode::Automatic)); + assert!(matches!(request.git_mode, PluginGitMode::Manual)); assert_eq!( request.configured_plugin_sources[0] .local_version .as_deref(), - Some("2.0.0") + Some("1.0.0") ); } @@ -7510,61 +7510,91 @@ fn remote_installed_plugins_cache_refresh_coalesces_materializations() { } #[tokio::test] -async fn background_remote_installed_bundle_sync_stays_deduped() { +async fn account_changes_never_start_plugin_sync_even_with_remote_features_enabled() { let codex_home = TempDir::new().unwrap(); + let config_path = codex_home.path().join(CONFIG_TOML_FILE); + let original_config = "[features]\nplugins = true\nremote_plugin = true\nplugin_sharing = true\napps = true\n[marketplaces.local]\nsource_type = 'git'\nsource = 'https://example.test/local.git'\n[plugins.\"sample@local\"]\nenabled = true\n"; + write_file(&config_path, original_config); + let skill = codex_home.path().join("skills/local/SKILL.md"); + write_file(&skill, "local skill must survive account changes"); + let plugin_root = codex_home.path().join("plugins/cache/local/sample/local"); + write_plugin( + &codex_home.path().join("plugins/cache/local"), + "sample/local", + "sample", + ); write_file( - &codex_home.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true -remote_plugin = true -"#, + &plugin_root.join(".mcp.json"), + r#"{"mcpServers":{"local-tool":{"command":"echo"}}}"#, ); + let plugin_skill = plugin_root.join("skills/SKILL.md"); + let original_plugin_skill = fs::read(&plugin_skill).unwrap(); let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/installed")) - .and(query_param("includeDownloadUrls", "true")) - .respond_with( - ResponseTemplate::new(200) - .set_delay(Duration::from_millis(200)) - .set_body_json(serde_json::json!({ - "plugins": [], - "pagination": {"next_page_token": null}, - })), - ) - .expect(1) - .mount(&server) - .await; - let mut config = load_config(codex_home.path(), codex_home.path()).await; config.chatgpt_base_url = format!("{}/backend-api", server.uri()); - let first_manager = std::sync::Arc::new(test_plugins_manager_with_options( + let auth_manager = test_auth_manager(/*auth_mode*/ None); + let manager = Arc::new(test_plugins_manager_with_auth_manager( codex_home.path().to_path_buf(), Some(Product::Codex), - Some(AuthMode::Chatgpt), + Arc::clone(&auth_manager), )); - let second_manager = std::sync::Arc::new(test_plugins_manager_with_options( - codex_home.path().to_path_buf(), - Some(Product::Codex), + let (warnings, mut received_warnings) = tokio::sync::mpsc::unbounded_channel(); + for mode in [ + None, Some(AuthMode::Chatgpt), - )); - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - - first_manager.maybe_start_remote_installed_plugin_bundle_sync( - &config, - Some(auth.clone()), - /*on_effective_plugins_changed*/ None, + Some(AuthMode::ChatgptAuthTokens), + None, + ] { + set_test_auth_mode(&auth_manager, mode).await; + let loaded = manager.plugins_for_config(&config).await; + assert_eq!(loaded.plugins().len(), 1); + assert_eq!(loaded.plugins()[0].config_name, "sample@local"); + assert_eq!( + sorted_effective_mcp_server_names(&loaded), + vec!["local-tool".to_string()] + ); + assert_eq!(loaded.effective_plugin_skill_roots().len(), 1); + assert_eq!(fs::read(&plugin_skill).unwrap(), original_plugin_skill); + let auth = auth_manager.auth_cached(); + manager.maybe_start_curated_repo_sync_for_config( + &config, /*on_effective_plugins_changed*/ None, + ); + manager.maybe_start_remote_plugin_caches_refresh( + &config, + auth.clone(), + /*prefetch_recommendations*/ true, + /*on_effective_plugins_changed*/ None, + ); + manager.maybe_start_remote_installed_plugin_bundle_sync( + &config, auth, /*on_effective_plugins_changed*/ None, + ); + manager.maybe_start_plugin_startup_tasks_for_config( + &config, + /*prefetch_discovery*/ true, + Arc::new(|| panic!("automatic marketplace upgrade must not reload config")), + /*on_effective_plugins_changed*/ None, + warnings.clone(), + ); + } + tokio::time::sleep(Duration::from_millis(200)).await; + assert!(server.received_requests().await.unwrap().is_empty()); + assert_eq!(fs::read_to_string(&config_path).unwrap(), original_config); + assert_eq!( + fs::read_to_string(&skill).unwrap(), + "local skill must survive account changes" ); - second_manager.maybe_start_remote_installed_plugin_bundle_sync( - &config, - Some(auth), - /*on_effective_plugins_changed*/ None, + assert!(!codex_home.path().join(".tmp/plugins").exists()); + assert!( + !codex_home + .path() + .join("plugins/cache/openai-curated-remote") + .exists() ); - - let _guard = first_manager + assert!(received_warnings.try_recv().is_err()); + let _guard = manager .acquire_remote_installed_plugin_sync_guard() .await - .expect("background bundle sync should finish"); - server.verify().await; + .unwrap(); } #[tokio::test] @@ -7811,7 +7841,7 @@ remote_plugin = true } #[tokio::test] -async fn failed_installed_plugin_pagination_preserves_inventory_and_releases_mutation_gate() { +async fn disabled_background_sync_preserves_inventory_and_releases_mutation_gate() { let codex_home = TempDir::new().unwrap(); write_file( &codex_home.path().join(CONFIG_TOML_FILE), @@ -7823,14 +7853,14 @@ async fn failed_installed_plugin_pagination_preserves_inventory_and_releases_mut "retained", ); let server = MockServer::start().await; - // Both bundle sync and its metadata fallback must reject the incomplete inventory. + // Background triggers must not fetch even an incomplete account inventory. Mock::given(method("GET")) .and(path("/backend-api/ps/plugins/installed")) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ "plugins": [], "pagination": {"next_page_token": "next"}, }))) - .expect(4) + .expect(0) .mount(&server) .await; let mut config = load_config(codex_home.path(), codex_home.path()).await; @@ -7850,7 +7880,7 @@ async fn failed_installed_plugin_pagination_preserves_inventory_and_releases_mut Some(auth), /*on_effective_plugins_changed*/ None, ); - // Starting the sync acquires the gate synchronously, so this waits for its release. + // A disabled background trigger must leave the shared mutation gate available. let _guard = tokio::time::timeout( Duration::from_secs(5), manager.acquire_remote_installed_plugin_sync_guard(), @@ -7869,7 +7899,7 @@ async fn failed_installed_plugin_pagination_preserves_inventory_and_releases_mut } }) .await - .expect("fallback metadata refresh should finish"); + .expect("no background metadata refresh should remain active"); assert_eq!( manager diff --git a/codex-rs/core/src/config/config_tests.rs b/codex-rs/core/src/config/config_tests.rs index 309e2d3d5442..1f8afaa7760e 100644 --- a/codex-rs/core/src/config/config_tests.rs +++ b/codex-rs/core/src/config/config_tests.rs @@ -7507,17 +7507,17 @@ async fn to_mcp_config_preserves_apps_feature_from_config() -> std::io::Result<( config.apps_mcp_product_sku = Some("tpp".to_string()); let mcp_config = config.to_mcp_config(&plugins_manager).await; - assert!(mcp_config.apps_enabled); - assert_eq!(mcp_config.apps_mcp_product_sku.as_deref(), Some("tpp")); - - let _ = config.features.disable(Feature::Apps); - let mcp_config = config.to_mcp_config(&plugins_manager).await; assert!(!mcp_config.apps_enabled); + assert_eq!(mcp_config.apps_mcp_product_sku.as_deref(), Some("tpp")); let _ = config.features.enable(Feature::Apps); let mcp_config = config.to_mcp_config(&plugins_manager).await; assert!(mcp_config.apps_enabled); + let _ = config.features.disable(Feature::Apps); + let mcp_config = config.to_mcp_config(&plugins_manager).await; + assert!(!mcp_config.apps_enabled); + Ok(()) } diff --git a/codex-rs/core/src/guardian/tests.rs b/codex-rs/core/src/guardian/tests.rs index b09c5431aa40..a56f15e80a8f 100644 --- a/codex-rs/core/src/guardian/tests.rs +++ b/codex-rs/core/src/guardian/tests.rs @@ -3184,10 +3184,12 @@ async fn guardian_review_retries_transient_session_failure_then_approves() -> an }; assert_eq!(assessment.outcome, GuardianAssessmentOutcome::Allow); assert_eq!(assessment.rationale, "retry succeeded"); - assert_eq!(metadata.attempt_count, 2); + // The Responses stream layer handles this transient overload inside one + // guardian session; two backend requests still prove the retry happened. + assert_eq!(metadata.attempt_count, 1); assert!(matches!( metadata.guardian_session_kind, - Some(codex_analytics::GuardianReviewSessionKind::TrunkReused) + Some(codex_analytics::GuardianReviewSessionKind::TrunkNew) )); assert_eq!(request_log.requests().len(), 2); Ok(()) diff --git a/codex-rs/core/src/responses_retry.rs b/codex-rs/core/src/responses_retry.rs index 066bb7376f0e..af5a35543f17 100644 --- a/codex-rs/core/src/responses_retry.rs +++ b/codex-rs/core/src/responses_retry.rs @@ -128,7 +128,13 @@ pub(crate) async fn handle_response_stream_error( return Ok(()); } + // Capacity failures are model-specific; switching transports would only + // replay the same saturated request after exhausting its bounded retries. if retry_state.retries >= max_retries + && !matches!( + err.details(), + CodexErrorDetails::ServerOverloaded | CodexErrorDetails::PolicyCapacityUnavailable + ) && client_session.try_switch_fallback_transport( &turn_context.session_telemetry, turn_context.model_info(), diff --git a/codex-rs/core/src/session/turn.rs b/codex-rs/core/src/session/turn.rs index e4a092ed65e5..8c4c10cf0784 100644 --- a/codex-rs/core/src/session/turn.rs +++ b/codex-rs/core/src/session/turn.rs @@ -195,20 +195,38 @@ pub(crate) async fn run_turn( let mut client_session = prewarmed_client_session.unwrap_or_else(|| sess.services.model_client.new_session()); + // Validate the selected program before compaction can send a request using + // the previous model. Report policy rejection as a turn validation error. + let program_validation: CodexResult<()> = cyber_access_program::for_auth( + sess.services.auth_manager.auth().await.as_ref(), + turn_context.cyber_access_program, + cyber_access_program::ApiKeyCyberAccessPrograms::from_config(&turn_context.config), + ) + .map(|_| ()); // TODO(ccunningham): Pre-turn compaction runs before context updates and the // new user message are recorded. Estimate pending incoming items (context // diffs/full reinjection + user input) and trigger compaction preemptively // when they would push the thread over the compaction threshold. - if auto_compaction_enabled - && let Err(err) = run_pre_sampling_compact( + let (pre_sampling_result, message_prefix) = if let Err(err) = program_validation { + (Err(err), None) + } else if auto_compaction_enabled { + let result = run_pre_sampling_compact( &sess, &turn_context, &mut client_session, &cancellation_token, ) - .await - { - // Compaction runs before the new input is recorded, so preserve it on every failure. + .await; + let prefix = match turn_context.provider.capabilities().remote_compaction { + RemoteCompactionSupport::V2 => Some("Error running remote compact task".to_string()), + RemoteCompactionSupport::Unsupported => None, + }; + (result, prefix) + } else { + (Ok(()), None) + }; + if let Err(err) = pre_sampling_result { + // Turn preparation runs before input is recorded, so preserve it on failure. run_hooks_and_record_inputs( &sess, &turn_context, @@ -228,16 +246,12 @@ pub(crate) async fn run_turn( .await; // Publish the failure only after prompt hooks finish, so clients cannot react to // an error by steering follow-up input into a turn still preserving its prompt. - let message_prefix = match turn_context.provider.capabilities().remote_compaction { - RemoteCompactionSupport::V2 => Some("Error running remote compact task".to_string()), - RemoteCompactionSupport::Unsupported => None, - }; sess.send_event( turn_context.as_ref(), EventMsg::Error(err.to_error_event(message_prefix)), ) .await; - error!("Failed to run pre-sampling compact"); + error!("Failed to prepare turn"); return Ok(None); } diff --git a/codex-rs/core/src/shell_snapshot_sandbox_tests.rs b/codex-rs/core/src/shell_snapshot_sandbox_tests.rs index 312b802b95ea..2abd6bcc363f 100644 --- a/codex-rs/core/src/shell_snapshot_sandbox_tests.rs +++ b/codex-rs/core/src/shell_snapshot_sandbox_tests.rs @@ -135,7 +135,8 @@ async fn snapshot_failure_omits_credentials_and_stops_descendants( unreachable!("dropped captures have no result") } }; - assert_eq!(format!("{error:?}"), expected); + assert_eq!(error.to_string(), expected); + assert!(!format!("{error:?}").contains("ghp_abcdefghijklmnopqrstuvwxyz0123456789")); } tokio::time::sleep(Duration::from_millis(1_100)).await; assert!( diff --git a/codex-rs/core/tests/common/responses.rs b/codex-rs/core/tests/common/responses.rs index 672d9606606f..594721cb0dd6 100644 --- a/codex-rs/core/tests/common/responses.rs +++ b/codex-rs/core/tests/common/responses.rs @@ -1134,9 +1134,8 @@ pub async fn mount_response_once_match( where M: wiremock::Match + Send + Sync + 'static, { - let (mock, response_mock) = base_mock(); - mock.and(matcher) - .respond_with(response) + let (mock, response_mock) = base_mock_matching(matcher); + mock.respond_with(response) .up_to_n_times(1) .mount(server) .await; @@ -1144,9 +1143,19 @@ where } fn base_mock() -> (MockBuilder, ResponseMock) { + base_mock_matching(|_: &wiremock::Request| true) +} + +fn base_mock_matching(matcher: M) -> (MockBuilder, ResponseMock) +where + M: wiremock::Match + Send + Sync + 'static, +{ let response_mock = ResponseMock::new(); let mock = Mock::given(method("POST")) .and(path_regex(".*/responses$")) + // A rejected parent/child route must not capture the other thread's + // request or validate it as if this mock had served the response. + .and(matcher) .and(response_mock.clone()); (mock, response_mock) } @@ -1163,9 +1172,8 @@ pub async fn mount_sse_once_match(server: &MockServer, matcher: M, body: Stri where M: wiremock::Match + Send + Sync + 'static, { - let (mock, response_mock) = base_mock(); - mock.and(matcher) - .respond_with(sse_response(body)) + let (mock, response_mock) = base_mock_matching(matcher); + mock.respond_with(sse_response(body)) .up_to_n_times(1) .mount(server) .await; diff --git a/codex-rs/core/tests/common/test_codex_exec.rs b/codex-rs/core/tests/common/test_codex_exec.rs index 4020a4d9acf8..cf7c3c0b48f4 100644 --- a/codex-rs/core/tests/common/test_codex_exec.rs +++ b/codex-rs/core/tests/common/test_codex_exec.rs @@ -14,7 +14,17 @@ impl TestCodexExecBuilder { codex_utils_cargo_bin::cargo_bin("codex-exec") .expect("should find binary for codex-exec"), ); + // Report the child's captured stderr before nextest terminates the test. + cmd.timeout(std::time::Duration::from_secs(30)); cmd.current_dir(self.cwd.path()) + .args([ + "-c", + "features.api_key_model_discovery=false", + "-c", + "model_providers.openai.request_max_retries=0", + "-c", + "model_providers.openai.stream_max_retries=0", + ]) .env("CODEX_HOME", self.home.path()) .env("CODEX_SQLITE_HOME", self.home.path()) .env(CODEX_API_KEY_ENV_VAR, "dummy"); diff --git a/codex-rs/core/tests/suite/approvals.rs b/codex-rs/core/tests/suite/approvals.rs index 699d88133c4a..429c549be31c 100644 --- a/codex-rs/core/tests/suite/approvals.rs +++ b/codex-rs/core/tests/suite/approvals.rs @@ -3987,6 +3987,15 @@ async fn approving_fallback_rule_for_compound_command_works() -> Result<()> { ) .await; + mount_sse_once( + &server, + sse(vec![ + ev_assistant_message("first-compound-result", "done"), + ev_completed("first-compound-complete"), + ]), + ) + .await; + submit_turn( &test, "invalid-prefix-rule", diff --git a/codex-rs/core/tests/suite/cli_stream.rs b/codex-rs/core/tests/suite/cli_stream.rs index 26f1898d211a..7153a1cf11a2 100644 --- a/codex-rs/core/tests/suite/cli_stream.rs +++ b/codex-rs/core/tests/suite/cli_stream.rs @@ -71,7 +71,8 @@ async fn mount_personal_access_token_startup(server: &MockServer) { fn personal_access_token_exec_command(server: &MockServer, home: &TempDir) -> Command { let bin = codex_utils_cargo_bin::cargo_bin("codex").unwrap(); let mut cmd = Command::new(bin); - cmd.arg("exec") + cmd.arg("--no-daemon") + .arg("exec") .arg("--skip-git-repo-check") .arg("-c") .arg(format!("openai_base_url=\"{}/api/codex\"", server.uri())) @@ -118,6 +119,15 @@ impl Drop for ChildProcessCleanupGuard { // can spawn shell/Python grandchildren, so the timeout path must reap the whole // process group instead of only the direct CLI child. fn run_cli_command(command: &mut Command) -> io::Result { + // These fixtures test response streaming, not live API-key catalog discovery. + command.args([ + "-c", + "features.api_key_model_discovery=false", + "-c", + "model_providers.openai.request_max_retries=0", + "-c", + "model_providers.openai.stream_max_retries=0", + ]); #[cfg(unix)] command.process_group(0); @@ -136,7 +146,17 @@ fn run_cli_command(command: &mut Command) -> io::Result { match receiver.recv_timeout(CLI_TIMEOUT) { Ok(output) => output, Err(mpsc::RecvTimeoutError::Timeout) => { - Err(io::Error::new(io::ErrorKind::TimedOut, "process timed out")) + drop(_cleanup); + let diagnostic = receiver + .recv_timeout(Duration::from_secs(5)) + .ok() + .and_then(Result::ok) + .map(|output| String::from_utf8_lossy(&output.stderr).into_owned()) + .unwrap_or_default(); + Err(io::Error::new( + io::ErrorKind::TimedOut, + format!("process timed out; stderr:\n{diagnostic}"), + )) } Err(mpsc::RecvTimeoutError::Disconnected) => { Err(io::Error::other("process output reader thread exited")) @@ -148,7 +168,7 @@ fn run_cli_command(command: &mut Command) -> io::Result { async fn responses_mode_stream_cli_supports_personal_access_tokens() { skip_if_no_network!(); - let server = MockServer::start().await; + let server = responses::start_mock_server().await; mount_personal_access_token_startup(&server).await; let resp_mock = responses::mount_sse_once(&server, cli_sse_response()).await; let home = TempDir::new().unwrap(); @@ -180,7 +200,7 @@ async fn responses_mode_stream_cli_does_not_attempt_oauth_refresh_for_personal_a { skip_if_no_network!(); - let server = MockServer::start().await; + let server = responses::start_mock_server().await; mount_personal_access_token_startup(&server).await; Mock::given(method("POST")) .and(path("/api/codex/responses")) @@ -214,7 +234,7 @@ async fn responses_mode_stream_cli_does_not_attempt_oauth_refresh_for_personal_a async fn responses_mode_stream_cli() { skip_if_no_network!(); - let server = MockServer::start().await; + let server = responses::start_mock_server().await; let repo_root = repo_root(); let sse = responses::sse(vec![ responses::ev_response_created("resp-1"), @@ -230,7 +250,8 @@ async fn responses_mode_stream_cli() { ); let bin = codex_utils_cargo_bin::cargo_bin("codex").unwrap(); let mut cmd = Command::new(bin); - cmd.arg("exec") + cmd.arg("--no-daemon") + .arg("exec") .arg("--skip-git-repo-check") .arg("-c") .arg(&provider_override) @@ -260,7 +281,7 @@ async fn responses_mode_stream_cli() { async fn responses_mode_stream_cli_supports_openai_base_url_config_override() { skip_if_no_network!(); - let server = MockServer::start().await; + let server = responses::start_mock_server().await; let repo_root = repo_root(); let sse = responses::sse(vec![ responses::ev_response_created("resp-1"), @@ -272,7 +293,8 @@ async fn responses_mode_stream_cli_supports_openai_base_url_config_override() { let home = TempDir::new().unwrap(); let bin = codex_utils_cargo_bin::cargo_bin("codex").unwrap(); let mut cmd = Command::new(bin); - cmd.arg("exec") + cmd.arg("--no-daemon") + .arg("exec") .arg("--skip-git-repo-check") .arg("-c") .arg(format!("openai_base_url=\"{}/v1\"", server.uri())) @@ -298,7 +320,7 @@ async fn exec_cli_applies_model_instructions_file() { // Start mock server which will capture the request and return a minimal // SSE stream for a single turn. - let server = MockServer::start().await; + let server = responses::start_mock_server().await; let sse = concat!( "data: {\"type\":\"response.created\",\"response\":{}}\n\n", "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"r1\"}}\n\n" @@ -324,7 +346,8 @@ async fn exec_cli_applies_model_instructions_file() { let repo_root = repo_root(); let bin = codex_utils_cargo_bin::cargo_bin("codex").unwrap(); let mut cmd = Command::new(bin); - cmd.arg("exec") + cmd.arg("--no-daemon") + .arg("exec") .arg("--skip-git-repo-check") .arg("--model") .arg("gpt-5.5") @@ -363,7 +386,7 @@ async fn exec_cli_applies_model_instructions_file() { async fn exec_cli_profile_applies_model_instructions_file() { skip_if_no_network!(); - let server = MockServer::start().await; + let server = responses::start_mock_server().await; let sse = concat!( "data: {\"type\":\"response.created\",\"response\":{}}\n\n", "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"r1\"}}\n\n" @@ -391,7 +414,8 @@ async fn exec_cli_profile_applies_model_instructions_file() { let repo_root = repo_root(); let bin = codex_utils_cargo_bin::cargo_bin("codex").unwrap(); let mut cmd = Command::new(bin); - cmd.arg("exec") + cmd.arg("--no-daemon") + .arg("exec") .arg("--skip-git-repo-check") .arg("--model") .arg("gpt-5.5") @@ -426,14 +450,15 @@ async fn exec_cli_profile_applies_model_instructions_file() { async fn responses_api_stream_cli() { skip_if_no_network!(); - let server = MockServer::start().await; + let server = responses::start_mock_server().await; let resp_mock = responses::mount_sse_once(&server, cli_sse_response()).await; let repo_root = repo_root(); let home = TempDir::new().unwrap(); let bin = codex_utils_cargo_bin::cargo_bin("codex").unwrap(); let mut cmd = Command::new(bin); - cmd.arg("exec") + cmd.arg("--no-daemon") + .arg("exec") .arg("--skip-git-repo-check") .arg("-c") .arg(format!("openai_base_url=\"{}/v1\"", server.uri())) @@ -466,7 +491,7 @@ async fn integration_creates_and_checks_session_file() -> anyhow::Result<()> { let prompt = format!("echo {marker}"); // 3. Serve two hermetic SSE responses, one for the initial run and one for resume. - let server = MockServer::start().await; + let server = responses::start_mock_server().await; let resp_mock = responses::mount_sse_sequence(&server, vec![cli_sse_response(), cli_sse_response()]).await; let repo_root = repo_root(); @@ -474,7 +499,8 @@ async fn integration_creates_and_checks_session_file() -> anyhow::Result<()> { // 4. Run the codex CLI and invoke `exec`, which is what records a session. let bin = codex_utils_cargo_bin::cargo_bin("codex").unwrap(); let mut cmd = Command::new(bin); - cmd.arg("exec") + cmd.arg("--no-daemon") + .arg("exec") .arg("--skip-git-repo-check") .arg("-c") .arg(format!("openai_base_url=\"{}/v1\"", server.uri())) @@ -590,7 +616,8 @@ async fn integration_creates_and_checks_session_file() -> anyhow::Result<()> { let prompt2 = format!("echo {marker2}"); let bin2 = codex_utils_cargo_bin::cargo_bin("codex").unwrap(); let mut cmd2 = Command::new(bin2); - cmd2.arg("exec") + cmd2.arg("--no-daemon") + .arg("exec") .arg("--skip-git-repo-check") .arg("-c") .arg(format!("openai_base_url=\"{}/v1\"", server.uri())) diff --git a/codex-rs/core/tests/suite/compact_program_tests.rs b/codex-rs/core/tests/suite/compact_program_tests.rs index f1986403a752..cdf32240087e 100644 --- a/codex-rs/core/tests/suite/compact_program_tests.rs +++ b/codex-rs/core/tests/suite/compact_program_tests.rs @@ -80,6 +80,7 @@ async fn submit_pair( #[test_case(Compaction::LocalHash, History::ApiKeyCustomProviderResume, Some(CyberAccessProgram::DaybreakBlue); "api key custom provider local resume")] #[test_case(Compaction::RemoteHash, History::ApiKeyCustomProviderResume, Some(CyberAccessProgram::DaybreakBlue); "api key custom provider remote resume")] #[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[tracing_test::traced_test] async fn model_switch_program_pair( compaction: Compaction, history: History, @@ -246,6 +247,10 @@ async fn model_switch_program_pair( .enable(Feature::ApiKeyCyberAccessPrograms) .expect("enable API-key Cyber access programs"); } else if matches!(history, History::ApiKeyResume) { + config + .features + .disable(Feature::ApiKeyModelDiscovery) + .expect("disable API-key model discovery"); config .features .disable(Feature::ApiKeyCyberAccessPrograms) diff --git a/codex-rs/core/tests/suite/guardian_heartbeat_authorization.rs b/codex-rs/core/tests/suite/guardian_heartbeat_authorization.rs index 1af31a98d79b..6eae2227fca4 100644 --- a/codex-rs/core/tests/suite/guardian_heartbeat_authorization.rs +++ b/codex-rs/core/tests/suite/guardian_heartbeat_authorization.rs @@ -7,10 +7,39 @@ use codex_protocol::turn_input::TurnStartOptions; use core_test_support::responses::mount_sse_once; use pretty_assertions::assert_eq; +async fn mount_worker_completion_notice(server: &wiremock::MockServer, root_id: ThreadId) { + // Completion can reach an idle root or steer its next user turn. Either case + // can require one more sampling request after the explicit fixture response. + mount_sse_once_match( + server, + move |request: &wiremock::Request| { + is_root_request(request, root_id) + && request_body(request).is_some_and(|body| { + body["input"].as_array().is_some_and(|items| { + items.iter().any(|item| { + item["type"] == "agent_message" + && item["recipient"] == "/root" + && item["content"].as_array().is_some_and(|content| { + content.iter().any(|part| { + part["text"].as_str().is_some_and(|text| { + text.starts_with("Message Type: FINAL_ANSWER") + }) + }) + }) + }) + }) + }) + }, + sse(vec![ev_completed("worker-notice-acknowledged")]), + ) + .await; +} + #[test_case::test_case(0, None; "below_storage_limits")] #[test_case::test_case(18, None; "bounded_user_history")] #[test_case::test_case(0, Some("Should I pause restarting until you give final approval?"); "filtered_assistant_question")] #[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[tracing_test::traced_test] async fn heartbeat_keeps_user_restriction_after_status_questions( unrelated_turns: usize, restriction_question: Option<&str>, @@ -33,6 +62,7 @@ async fn heartbeat_keeps_user_restriction_after_status_questions( .build_with_auto_env(&server) .await?; let root_id = test.session_configured.thread_id; + mount_worker_completion_notice(&server, root_id).await; let mut created = test.thread_manager.subscribe_thread_created(); mount_sse_once( &server, @@ -188,6 +218,7 @@ async fn heartbeat_keeps_user_restriction_after_status_questions( #[test_case::test_case(&[Feature::GuardianRootHandoffContext], 1; "handoff_filter_first")] #[test_case::test_case(&[Feature::GuardianRootHandoffContext], 3; "handoff_filter_repeated")] #[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[tracing_test::traced_test] async fn heartbeat_root_projection_uses_latest_turn_skills( enabled_features: &'static [Feature], heartbeat_count: usize, @@ -206,6 +237,7 @@ async fn heartbeat_root_projection_uses_latest_turn_skills( .build_with_auto_env(&server) .await?; let root_id = test.session_configured.thread_id; + mount_worker_completion_notice(&server, root_id).await; let mut created = test.thread_manager.subscribe_thread_created(); let evidence = test .codex diff --git a/codex-rs/core/tests/suite/otel.rs b/codex-rs/core/tests/suite/otel.rs index 386312a2bf03..ccf0ce397654 100644 --- a/codex-rs/core/tests/suite/otel.rs +++ b/codex-rs/core/tests/suite/otel.rs @@ -221,6 +221,7 @@ async fn process_sse_emits_failed_event_on_parse_error() { let TestCodex { codex, .. } = test_codex() .with_config(move |config| { + config.model_provider.stream_max_retries = Some(0); config .features .disable(Feature::GhostCommit) @@ -262,6 +263,7 @@ async fn process_sse_records_failed_event_when_stream_closes_without_completed() let TestCodex { codex, .. } = test_codex() .with_config(move |config| { + config.model_provider.stream_max_retries = Some(0); config .features .disable(Feature::GhostCommit) @@ -428,6 +430,7 @@ async fn process_sse_failed_event_logs_missing_error() { let TestCodex { codex, .. } = test_codex() .with_config(move |config| { + config.model_provider.stream_max_retries = Some(0); config .features .disable(Feature::GhostCommit) diff --git a/codex-rs/core/tests/suite/plugins.rs b/codex-rs/core/tests/suite/plugins.rs index e60d60eb49c5..e6709987e639 100644 --- a/codex-rs/core/tests/suite/plugins.rs +++ b/codex-rs/core/tests/suite/plugins.rs @@ -1229,12 +1229,12 @@ async fn legacy_plugin_skill_prompt_remains_complete() -> Result<()> { Ok(()) } -#[test_case("sites", None, true, true, (true, false); "sites enabled remote supersedes bundled")] -#[test_case("sites", Some("tpp"), true, true, (true, false); "sites configured work sku")] -#[test_case("sites", None, false, true, (false, false); "sites disabled remote does not reactivate bundled")] +#[test_case("sites", None, true, true, (true, true); "sites enabled remote preserves bundled")] +#[test_case("sites", Some("tpp"), true, true, (true, true); "sites configured work sku")] +#[test_case("sites", None, false, true, (false, true); "sites disabled remote preserves bundled")] #[test_case("sites", None, true, false, (false, true); "sites missing remote bundle preserves bundled")] -#[test_case("visualize", None, true, true, (true, false); "visualize enabled remote supersedes bundled")] -#[test_case("visualize", None, false, true, (false, false); "visualize disabled remote does not reactivate bundled")] +#[test_case("visualize", None, true, true, (true, true); "visualize enabled remote preserves bundled")] +#[test_case("visualize", None, false, true, (false, true); "visualize disabled remote preserves bundled")] #[test_case("visualize", None, true, false, (false, true); "visualize missing remote bundle preserves bundled")] #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn bundled_plugin_compatibility_guard_in_agent_turn( @@ -1348,7 +1348,7 @@ enabled = true developer_text.contains(&format!("{plugin_name}:bundled-skill")), ), expected_skills, - "unexpected {plugin_name} skills in developer prompt: {developer_text:?}" + "unexpected remote/bundled {plugin_name} skill availability" ); Ok(()) } diff --git a/codex-rs/core/tests/suite/prompt_cache_key.rs b/codex-rs/core/tests/suite/prompt_cache_key.rs index 9a5037d390da..7af8000200db 100644 --- a/codex-rs/core/tests/suite/prompt_cache_key.rs +++ b/codex-rs/core/tests/suite/prompt_cache_key.rs @@ -105,6 +105,7 @@ async fn api_key_subagent_inherits_prompt_cache_key_policy(policy: PromptCacheKe let spawn_args = serde_json::to_string(&json!({ "message": CHILD_TASK, "task_name": "worker", + "fork_turns": "none", }))?; let root_request = mount_sse_once_match( &server, @@ -139,7 +140,10 @@ async fn api_key_subagent_inherits_prompt_cache_key_policy(policy: PromptCacheKe .await; mount_sse_once_match( &server, - |request: &wiremock::Request| body_contains(request, SPAWN_CALL_ID), + |request: &wiremock::Request| { + body_contains(request, SPAWN_CALL_ID) + && !request_has_input_type(request, "agent_message") + }, sse(vec![ ev_response_created("root-response-2"), ev_assistant_message("root-message", "worker finished"), @@ -147,10 +151,20 @@ async fn api_key_subagent_inherits_prompt_cache_key_policy(policy: PromptCacheKe ]), ) .await; + // Worker completion can arrive while the parent is still sampling. Its + // notification is unrelated to the cache policy and needs its own response. + mount_sse_once_match( + &server, + |request: &wiremock::Request| request_has_input_type(request, "agent_message"), + sse(vec![ev_completed("worker-notice-acknowledged")]), + ) + .await; let mut builder = test_codex() .with_auth(CodexAuth::from_api_key("dummy")) .with_config(|config| { + config.model_provider.request_max_retries = Some(0); + config.model_provider.stream_max_retries = Some(0); config .features .enable(Feature::Collab) @@ -164,7 +178,9 @@ async fn api_key_subagent_inherits_prompt_cache_key_policy(policy: PromptCacheKe start_with_prompt_cache_key(&mut test, policy.clone()).await?; let expected_session_id = test.session_configured.session_id.to_string(); let expected_cache_key = expected_prompt_cache_key(&policy, &expected_session_id); - test.submit_turn(ROOT_PROMPT).await?; + tokio::time::timeout(Duration::from_secs(20), test.submit_turn(ROOT_PROMPT)) + .await + .map_err(|_| anyhow!("cache policy parent turn did not complete"))??; let root_request = root_request .requests() diff --git a/codex-rs/core/tests/suite/retry_after.rs b/codex-rs/core/tests/suite/retry_after.rs index 81bc8bc349cb..7b5d6094b88c 100644 --- a/codex-rs/core/tests/suite/retry_after.rs +++ b/codex-rs/core/tests/suite/retry_after.rs @@ -500,7 +500,7 @@ async fn exhausted_http_retries_preserve_deadline_through_error_mapping() { } /// Retry advice changes delays but never extends either retry budget or its displayed count. -#[test_case::test_case(None, 2, 3; "without_advice")] +#[test_case::test_case(None, 2, 9; "without_advice")] #[test_case::test_case(Some("0"), 0, 3; "advice_without_stream_retries")] #[test_case::test_case(Some("0"), 2, 9; "advice_with_stream_retries")] #[tokio::test(flavor = "current_thread")] @@ -563,13 +563,9 @@ async fn responses_http_overload_respects_retry_limits( .expect("overload retries should finish the turn within 10 seconds"); assert_eq!(error_events, 1); - let expected_messages = if retry_after.is_some() { - (1..=stream_max_retries) - .map(|retry| format!("Reconnecting... {retry}/{stream_max_retries}")) - .collect::>() - } else { - Vec::new() - }; + let expected_messages = (1..=stream_max_retries) + .map(|retry| format!("Reconnecting... {retry}/{stream_max_retries}")) + .collect::>(); assert_eq!(reconnect_messages, expected_messages); let request_count = server .received_requests() @@ -965,7 +961,7 @@ async fn compact_v2_overload_without_retry_after_exhausts_request_retries() -> R .with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing()) .with_config(|config| { config.model_provider.request_max_retries = Some(2); - config.model_provider.stream_max_retries = Some(2); + config.model_provider.stream_max_retries = Some(0); }) .build_with_auto_env(&server) .await?; @@ -1290,7 +1286,8 @@ async fn sse_overload_with_retry_after_is_terminal() -> Result<()> { let test = test_codex() .with_config(|config| { config.model_provider.request_max_retries = Some(2); - config.model_provider.stream_max_retries = Some(2); + // This test checks terminal error attribution with retry explicitly disabled. + config.model_provider.stream_max_retries = Some(0); }) .build_with_auto_env(&server) .await?; @@ -1362,7 +1359,8 @@ async fn sse_overload_without_retry_after_is_terminal() -> Result<()> { let test = test_codex() .with_config(|config| { config.model_provider.request_max_retries = Some(2); - config.model_provider.stream_max_retries = Some(2); + // This test checks terminal error attribution with retry explicitly disabled. + config.model_provider.stream_max_retries = Some(0); }) .build_with_auto_env(&server) .await?; @@ -1821,7 +1819,7 @@ async fn websocket_upgrade_rejection_uses_retry_after() -> Result<()> { .respond_with( ResponseTemplate::new(/*s*/ 503) .insert_header("Retry-After", "1") - .set_body_json(json!({ "error": { "code": "server_is_overloaded" } })), + .set_body_json(json!({ "error": { "code": "upstream_unavailable" } })), ) .mount(&server) .await; @@ -1862,7 +1860,8 @@ async fn websocket_upgrade_rejection_uses_retry_after() -> Result<()> { submit_user_input(&test, "retry the rejected websocket upgrade").await?; wait_for_turn_completion(&test).await; - // Both WebSocket advice deadlines apply, including the one before transport fallback. + // Transport failures honor both WebSocket deadlines before HTTPS fallback. + // Model-capacity failures are covered separately and must not switch transports. assert!(start.elapsed() >= Duration::from_secs(2)); let requests = server.received_requests().await.unwrap_or_default(); let methods = requests @@ -2175,7 +2174,8 @@ async fn websocket_overload_without_retry_after_is_terminal() -> Result<()> { config.model_catalog = Some(bundled_models_response().expect("bundled models.json should parse")); config.model_provider.request_max_retries = Some(2); - config.model_provider.stream_max_retries = Some(2); + // This test checks terminal error attribution with retry explicitly disabled. + config.model_provider.stream_max_retries = Some(0); }) .build_with_websocket_server(&server) .await?; diff --git a/codex-rs/core/tests/suite/rollout_budget.rs b/codex-rs/core/tests/suite/rollout_budget.rs index c0c244ab4538..afdfe30ff724 100644 --- a/codex-rs/core/tests/suite/rollout_budget.rs +++ b/codex-rs/core/tests/suite/rollout_budget.rs @@ -1,3 +1,4 @@ +use anyhow::Context; use anyhow::Result; use codex_core::TurnInputRequest; use codex_core::config::RolloutBudgetConfig; @@ -52,8 +53,26 @@ fn rollout_budget_message(remaining_tokens: i64) -> String { ) } +fn wire_request_body(request: &wiremock::Request) -> Option { + let compressed = request + .headers + .get("content-encoding") + .and_then(|value| value.to_str().ok()) + .is_some_and(|value| { + value + .split(',') + .any(|entry| entry.trim().eq_ignore_ascii_case("zstd")) + }); + let bytes = if compressed { + zstd::stream::decode_all(std::io::Cursor::new(&request.body)).ok()? + } else { + request.body.clone() + }; + serde_json::from_slice(&bytes).ok() +} + fn wire_request_contains(request: &wiremock::Request, text: &str) -> bool { - std::str::from_utf8(&request.body).is_ok_and(|body| body.contains(text)) + wire_request_body(request).is_some_and(|body| body.to_string().contains(text)) } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] @@ -174,6 +193,7 @@ async fn invalid_provider_rollout_budget_units_fail_without_retry() -> Result<() } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[tracing_test::traced_test] async fn subagent_usage_draws_from_the_shared_budget() -> Result<()> { skip_if_no_network!(Ok(())); @@ -186,8 +206,34 @@ async fn subagent_usage_draws_from_the_shared_budget() -> Result<()> { let spawn_args = json!({ "message": CHILD_PROMPT, "task_name": "budget_worker", + "fork_turns": "none", }) .to_string(); + // A worker completion can wake the root after its explicit response or + // steer the following user turn. Acknowledge that notice without usage. + mount_sse_once_match( + &server, + |request: &wiremock::Request| { + wire_request_body(request).is_some_and(|body| { + body["client_metadata"]["x-codex-parent-thread-id"].is_null() + && body["input"].as_array().is_some_and(|items| { + items.iter().any(|item| { + item["type"] == "agent_message" + && item["recipient"] == "/root" + && item["content"].as_array().is_some_and(|parts| { + parts.iter().any(|part| { + part["text"].as_str().is_some_and(|text| { + text.starts_with("Message Type: FINAL_ANSWER") + }) + }) + }) + }) + }) + }) + }, + sse(vec![ev_completed("worker-notice-acknowledged")]), + ) + .await; mount_sse_once_match( &server, |request: &wiremock::Request| wire_request_contains(request, ROOT_PROMPT), @@ -205,7 +251,10 @@ async fn subagent_usage_draws_from_the_shared_budget() -> Result<()> { .await; mount_sse_once_match( &server, - |request: &wiremock::Request| wire_request_contains(request, "\"type\":\"agent_message\""), + |request: &wiremock::Request| { + wire_request_body(request) + .is_some_and(|body| body["client_metadata"]["x-codex-parent-thread-id"].is_string()) + }, sse(vec![ ev_response_created("child-1"), ev_completed_with_tokens("child-1", /*total_tokens*/ 30), @@ -216,7 +265,9 @@ async fn subagent_usage_draws_from_the_shared_budget() -> Result<()> { &server, |request: &wiremock::Request| { wire_request_contains(request, SPAWN_CALL_ID) - && !wire_request_contains(request, "\"type\":\"agent_message\"") + && wire_request_body(request).is_some_and(|body| { + body["client_metadata"]["x-codex-parent-thread-id"].is_null() + }) }, sse(vec![ ev_response_created("root-2"), @@ -242,19 +293,29 @@ async fn subagent_usage_draws_from_the_shared_budget() -> Result<()> { .enable(Feature::MultiAgentV2) .expect("test config should allow multi-agent v2"); config.rollout_budget = Some(rollout_budget()); + config.model_provider.request_max_retries = Some(0); + config.model_provider.stream_max_retries = Some(0); }) .build(&server) .await?; let mut created_threads = test.thread_manager.subscribe_thread_created(); - test.submit_turn(ROOT_PROMPT).await?; + timeout(Duration::from_secs(20), test.submit_turn(ROOT_PROMPT)) + .await + .context("initial root turn did not complete")??; let child_thread_id = timeout(Duration::from_secs(10), created_threads.recv()).await??; let child_thread = test.thread_manager.get_thread(child_thread_id).await?; - wait_for_event(child_thread.as_ref(), |event| { - matches!(event, EventMsg::TurnComplete(_)) - }) - .await; - test.submit_turn(FOLLOW_UP_PROMPT).await?; + timeout( + Duration::from_secs(20), + wait_for_event(child_thread.as_ref(), |event| { + matches!(event, EventMsg::TurnComplete(_)) + }), + ) + .await + .context("budget worker did not complete")?; + timeout(Duration::from_secs(20), test.submit_turn(FOLLOW_UP_PROMPT)) + .await + .context("budget follow-up did not complete")??; let requests = follow_up .requests() diff --git a/codex-rs/core/tests/suite/scenarios.rs b/codex-rs/core/tests/suite/scenarios.rs index ace972ff0ff0..2a601b0d0266 100644 --- a/codex-rs/core/tests/suite/scenarios.rs +++ b/codex-rs/core/tests/suite/scenarios.rs @@ -1557,6 +1557,52 @@ async fn astra_omits_disabled_executor_and_plugin_skills_from_model_context( Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn matched_response_mocks_capture_only_the_selected_thread() -> Result<()> { + use core_test_support::responses; + use wiremock::matchers::header; + + for use_sse in [false, true] { + let server = start_mock_server().await; + let mut routes = Vec::new(); + for thread in ["parent", "child"] { + let capture = if use_sse { + responses::mount_sse_once_match( + &server, + header("thread-id", thread), + sse(vec![ev_completed(thread)]), + ) + .await + } else { + responses::mount_response_once_match( + &server, + header("thread-id", thread), + responses::sse_response(sse(vec![ev_completed(thread)])), + ) + .await + }; + routes.push((thread, capture)); + } + let client = codex_http_client::HttpClientBuilder::new().build_direct()?; + for (thread, _) in &routes { + client + .post(format!("{}/responses", server.uri())) + .header("thread-id", *thread) + .json(&json!({"input": []})) + .send() + .await? + .error_for_status()?; + } + for (thread, capture) in routes { + assert_eq!( + capture.single_request().header("thread-id").as_deref(), + Some(thread) + ); + } + } + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn child_completion_wakes_parent_after_final_answer() -> Result<()> { use core_test_support::ThreadIdle; diff --git a/codex-rs/core/tests/suite/sqlite_state.rs b/codex-rs/core/tests/suite/sqlite_state.rs index db37580ee34b..249c76f5946a 100644 --- a/codex-rs/core/tests/suite/sqlite_state.rs +++ b/codex-rs/core/tests/suite/sqlite_state.rs @@ -201,6 +201,8 @@ async fn thread_creator_survives_resume_and_forks_use_current_auth() -> Result<( #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn new_thread_is_recorded_in_state_db() -> Result<()> { let server = start_mock_server().await; + let _response = + mount_sse_once(&server, responses::sse(vec![ev_completed("materialize")])).await; let mut builder = test_codex().with_config(|config| { config .features diff --git a/codex-rs/deny.toml b/codex-rs/deny.toml index 3d422deec3f2..edf8801883ca 100644 --- a/codex-rs/deny.toml +++ b/codex-rs/deny.toml @@ -82,6 +82,19 @@ ignore = [ { id = "RUSTSEC-2025-0141", reason = "bincode is unmaintained; pulled in via syntect v5.3.0 used by codex-tui for syntax highlighting; no fixed release yet" }, { id = "RUSTSEC-2026-0118", reason = "hickory-proto v0.25.2 is pulled in via rama-dns/rama-tcp used by codex-network-proxy; DNSSEC features are not enabled; remove when rama updates to hickory 0.26.1 or hickory-net" }, { id = "RUSTSEC-2026-0119", reason = "hickory-proto v0.25.2 is pulled in via rama-dns/rama-tcp used by codex-network-proxy; no fixed rama release is available yet; remove when rama updates to hickory 0.26.1 or hickory-net" }, + { id = "RUSTSEC-2026-0487", reason = "hickory-proto 0.25.2 via rama-dns/rama-tcp; temporarily accepted until the Rust/Rama upgrade brings hickory-proto >=0.26.2" }, + { id = "RUSTSEC-2026-0489", reason = "hickory-proto 0.25.2 via rama-dns/rama-tcp; temporarily accepted until the Rust/Rama upgrade brings hickory-proto >=0.26.2" }, + { id = "RUSTSEC-2026-0490", reason = "hickory-proto 0.25.2 via rama-dns/rama-tcp; temporarily accepted until the Rust/Rama upgrade brings hickory-proto >=0.26.2" }, + { id = "RUSTSEC-2026-0491", reason = "hickory-proto 0.25.2 via rama-dns/rama-tcp; temporarily accepted until the Rust/Rama upgrade brings hickory-proto >=0.26.2" }, + # DNSSEC-only advisories; DNSSEC is disabled in codex-network-proxy. + { id = "RUSTSEC-2026-0504", reason = "hickory-proto 0.25.2 via rama-dns/rama-tcp; DNSSEC is disabled; reassess after the Rust/Rama upgrade to Hickory >=0.26.2" }, + { id = "RUSTSEC-2026-0505", reason = "hickory-proto 0.25.2 via rama-dns/rama-tcp; DNSSEC is disabled; reassess after the Rust/Rama upgrade to Hickory >=0.26.2" }, + { id = "RUSTSEC-2026-0511", reason = "hickory-proto 0.25.2 via rama-dns/rama-tcp; DNSSEC is disabled; reassess after the Rust/Rama upgrade to Hickory >=0.26.2" }, + { id = "RUSTSEC-2026-0512", reason = "hickory-proto 0.25.2 via rama-dns/rama-tcp; DNSSEC is disabled; reassess after the Rust/Rama upgrade to Hickory >=0.26.2" }, + { id = "RUSTSEC-2026-0514", reason = "hickory-resolver 0.25.2 via rama-dns/rama-tcp; DNSSEC is disabled; reassess after the Rust/Rama upgrade to Hickory >=0.26.2" }, + { id = "RUSTSEC-2026-0530", reason = "hickory-proto 0.25.2 via rama-dns/rama-tcp; DNSSEC is disabled; reassess after the Rust/Rama upgrade to Hickory >=0.26.2" }, + { id = "RUSTSEC-2026-0531", reason = "hickory-proto 0.25.2 via rama-dns/rama-tcp; DNSSEC is disabled; reassess after the Rust/Rama upgrade to Hickory >=0.26.2" }, + { id = "RUSTSEC-2026-0532", reason = "hickory-proto 0.25.2 via rama-dns/rama-tcp; DNSSEC is disabled; reassess after the Rust/Rama upgrade to Hickory >=0.26.2" }, { id = "RUSTSEC-2026-0194", reason = "quick-xml v0.39.4 remains via plist/syntect and wayland-scanner; plist does not exercise the affected APIs and wayland-scanner parses trusted build-time XML; remove when rust-plist#191 and wayland-rs#938 are released" }, { id = "RUSTSEC-2026-0195", reason = "quick-xml v0.39.4 remains via plist/syntect and wayland-scanner; plist does not exercise the affected APIs and wayland-scanner parses trusted build-time XML; remove when rust-plist#191 and wayland-rs#938 are released" }, { id = "RUSTSEC-2026-0370", reason = "zvariant 4.2.0 is unmaintained; pulled in via zbus 4.4.0 by Linux TUI accessibility integration and keyring/secret-service; remove when those paths migrate off the retired standalone crates" }, @@ -95,8 +108,16 @@ ignore = [ { id = "RUSTSEC-2026-0398", reason = "zstd 0.13.3 pulls in zstd-safe 7.2.4 with the affected seekable feature disabled. Remove when all paths use zstd-safe >=8.2.0." }, { id = "RUSTSEC-2026-0403", reason = "zstd 0.13.3 pulls in zstd-safe 7.2.4. Codex, tonic and zip use read decoders or initialized output buffers and discard output on error. Remove when all paths use zstd-safe >=8.2.0." }, { id = "RUSTSEC-2026-0410", reason = "zstd-safe 7.2.4 pulls in zstd-sys 2.0.16. Its allocator bug only affects wasm32, and Codex ships native binaries. Remove when the lockfile uses zstd-sys >=2.1.2." }, + { id = "RUSTSEC-2026-0418", reason = "libz-sys 1.1.29 via curl-sys/curl in codex-http-client is Windows-only and skips the affected probe; cc is locked to 1.2.55 (<1.6.0). Remove when libz-sys >=1.1.31; reassess if used on Unix with cc >=1.6.0." }, # Reviewed 2026-11-05; unmaintained advisory, no known exploit or fixed upstream release. { id = "RUSTSEC-2026-0441", reason = "pin-utils 0.1.0 is unmaintained (upstream archived 2026-10-01), pulled in through aws-smithy-http 0.62.6 via aws-config 1.8.12 in codex-aws-auth; remove this exception when AWS SDK dependencies eliminate pin-utils" }, + # Reviewed 2026-11-14; fixed releases are not yet in this Rust 1.95 + # branch's lockfile. Remove each exception after the dependency update. + { id = "RUSTSEC-2026-0386", reason = "tokio 1.52.3 exposes unsound AsyncFd constructors; Codex uses the APIs through transitive workspace dependencies; remove when the lockfile uses tokio >=1.53.3 or the fixed 1.51.6 line" }, + { id = "RUSTSEC-2026-0486", reason = "rustix 1.1.4 has an xattr zero-length-buffer initialization bug; transitive Linux filesystem paths; remove when rustix >=1.1.6 reaches the lockfile" }, + { id = "RUSTSEC-2026-0523", reason = "quinn-proto 0.11.18 can bypass stream limits via MAX_STREAM_DATA; pulled in through codex-tcp-tunnel/h3-quinn; remove when quinn-proto >=0.11.19 is locked" }, + { id = "RUSTSEC-2026-0524", reason = "quinn-proto 0.11.18 can panic or allocate excessively on a malicious Retry token; pulled in through codex-tcp-tunnel/h3-quinn; remove when quinn-proto >=0.11.19 is locked" }, + { id = "RUSTSEC-2026-0538", reason = "quinn-udp 0.5.14 and 0.6.1 can spin after a truncated datagram on selected targets; retained through QUIC/WebRTC dependencies; remove when quinn-udp >=0.5.16 or >=0.6.3 is locked" }, ] # If this is true, then cargo deny will use the git executable to fetch advisory database. # If this is false, then it uses a built-in git library. @@ -168,6 +189,8 @@ confidence-threshold = 0.8 exceptions = [ # Each entry is the crate and version constraint, and its specific allow # list + { allow = ["0BSD"], crate = "managed@0.8.0" }, + { allow = ["0BSD"], crate = "smoltcp@0.14.0" }, #{ allow = ["Zlib"], crate = "adler32" }, ] @@ -335,6 +358,7 @@ allow-git = [ "https://github.com/openai-oss-forks/tokio-tungstenite", "https://github.com/openai-oss-forks/tungstenite-rs", "https://github.com/seanh-oai/rusty_v8.git", + "https://github.com/transact-rs/sqlx", ] [sources.allow-org] diff --git a/codex-rs/exec-server/src/shell_snapshot.rs b/codex-rs/exec-server/src/shell_snapshot.rs index 55a831c7cb07..187fc8428b50 100644 --- a/codex-rs/exec-server/src/shell_snapshot.rs +++ b/codex-rs/exec-server/src/shell_snapshot.rs @@ -371,6 +371,14 @@ impl ShellSnapshotCache { ) }; + if shell_type == ShellType::Bash { + // Bash's remote-daemon startup path can source .bashrc even with -p. + // Suppress it explicitly before restoring the captured, filtered state. + prepared + .command + .insert(shell_start + 1, "--norc".to_string()); + } + telemetry.shell_snapshot_command(wait, availability, "used"); Ok(reader) } diff --git a/codex-rs/exec-server/src/shell_snapshot_tests.rs b/codex-rs/exec-server/src/shell_snapshot_tests.rs index 7f5298fcb52e..375b015806b7 100644 --- a/codex-rs/exec-server/src/shell_snapshot_tests.rs +++ b/codex-rs/exec-server/src/shell_snapshot_tests.rs @@ -139,8 +139,8 @@ async fn snapshot_failure_retries_are_bounded_and_single_flight( for (prepared, reader) in [(&mut prepared, first), (&mut concurrent, second)] { if let Some(reader) = reader { let fd = std::os::fd::AsRawFd::as_raw_fd(&reader); - prepared.command[2] = - prepared.command[2].replace(&format!("/dev/fd/{fd}"), "/dev/fd/SNAPSHOT"); + let script = prepared.command.last_mut().expect("snapshot replay script"); + *script = script.replace(&format!("/dev/fd/{fd}"), "/dev/fd/SNAPSHOT"); } } assert_eq!( diff --git a/codex-rs/exec-server/tests/capability_discovery.rs b/codex-rs/exec-server/tests/capability_discovery.rs index 81d4987da4ce..5920829bc54b 100644 --- a/codex-rs/exec-server/tests/capability_discovery.rs +++ b/codex-rs/exec-server/tests/capability_discovery.rs @@ -6,7 +6,6 @@ mod fake_bwrap; #[path = "capability_discovery/mount_watch.rs"] mod mount_watch; -#[cfg(target_os = "linux")] use anyhow::Context as _; use base64::Engine as _; use base64::engine::general_purpose::STANDARD; @@ -1116,7 +1115,8 @@ async fn sandboxed_discovery_batches_roots_without_combining_different_permissio }, ], ) - .await?; + .await + .context("discover roots with shared sandbox permissions")?; assert_eq!( response .roots @@ -1172,7 +1172,8 @@ async fn sandboxed_discovery_batches_roots_without_combining_different_permissio }, ], ) - .await?; + .await + .context("discover roots after forced batch helper failure")?; assert_eq!( fallback .roots @@ -1232,7 +1233,8 @@ async fn sandboxed_discovery_batches_roots_without_combining_different_permissio }, ], ) - .await?; + .await + .context("discover roots with isolated sandbox permissions")?; assert_eq!( response .roots diff --git a/codex-rs/exec-server/tests/exec_process.rs b/codex-rs/exec-server/tests/exec_process.rs index 68235743d873..04f051bbd4a0 100644 --- a/codex-rs/exec-server/tests/exec_process.rs +++ b/codex-rs/exec-server/tests/exec_process.rs @@ -258,7 +258,7 @@ async fn shell_snapshot_v2_filters_profile_exports_and_stays_in_memory( let shadowed_builtins = if posix_shell { "" } else { - "unset() { exit 41; }\nbuiltin() { exit 41; }\nexec() { exit 41; }\n" + "unset() { printf 'shadowed unset: %s\\n' \"$*\" >> \"$HOME/startup-trace\"; exit 41; }\nbuiltin() { printf 'shadowed builtin: %s\\n' \"$*\" >> \"$HOME/startup-trace\"; exit 41; }\nexec() { printf 'shadowed exec: %s\\n' \"$*\" >> \"$HOME/startup-trace\"; exit 41; }\n" }; std::fs::write( &profile_path, @@ -352,9 +352,10 @@ async fn shell_snapshot_v2_filters_profile_exports_and_stays_in_memory( tty, pipe_stdin: false, arg0: (shell_name == "bash-sh").then(|| "sh".to_string()), - sandbox: (use_sandbox && attempt == 0).then(|| { + sandbox: use_sandbox.then(|| { FileSystemSandboxContext::from_permission_profile( - PermissionProfile::read_only(), + // The startup profile records capture counts under this cwd. + PermissionProfile::workspace_write(), cwd.clone(), ) }), @@ -367,7 +368,9 @@ async fn shell_snapshot_v2_filters_profile_exports_and_stays_in_memory( collect_process_output_from_events(started.process).await?; assert_eq!( (stdout, stderr, status, closed), - (expected_stdout.clone(), String::new(), Some(0), true,) + (expected_stdout.clone(), String::new(), Some(0), true,), + "startup diagnostics: {}", + std::fs::read_to_string(home.path().join("startup-trace")).unwrap_or_default() ); } @@ -1106,7 +1109,7 @@ async fn shell_snapshot_v2_capture_failure_falls_back_and_retries( std::fs::write( home.path().join(profile_name), - "printf x >> \"$HOME/captures\"\nprofile_helper() { printf recovered; }\n", + "printf 'flags=%s source=%s bash_env=%s argv0=%s\\n' \"$-\" \"${BASH_SOURCE[*]-}\" \"${BASH_ENV-}\" \"$0\" >> \"$HOME/startup-trace\"\nprintf x >> \"$HOME/captures\"\nprofile_helper() { printf recovered; }\n", )?; let (expected_output, expected_captures) = if failures_before_repair == 3 { ("original", "xxx") @@ -1123,7 +1126,9 @@ async fn shell_snapshot_v2_capture_failure_falls_back_and_retries( } assert_eq!( std::fs::read_to_string(home.path().join("captures"))?, - expected_captures + expected_captures, + "startup diagnostics: {}", + std::fs::read_to_string(home.path().join("startup-trace")).unwrap_or_default() ); Ok(()) } diff --git a/codex-rs/exec-server/tests/exec_process/shell_snapshot.rs b/codex-rs/exec-server/tests/exec_process/shell_snapshot.rs index 7d022116b128..17c6f0c335c7 100644 --- a/codex-rs/exec-server/tests/exec_process/shell_snapshot.rs +++ b/codex-rs/exec-server/tests/exec_process/shell_snapshot.rs @@ -6,7 +6,7 @@ use test_case::test_case; enum SnapshotSandbox { None, WorkspaceWrite, - DenyFdPath, + CloseDescriptors, } pub(super) struct StartupProcesses(pub(super) std::path::PathBuf); @@ -91,9 +91,9 @@ async fn shell_snapshot_preserves_successful_startup_output_and_services( #[test_case("bash", true, SnapshotSandbox::None; "bash_tty")] #[cfg_attr(target_os = "macos", test_case("zsh", false, SnapshotSandbox::None; "zsh"))] #[cfg_attr(target_os = "macos", test_case("zsh", true, SnapshotSandbox::None; "zsh_tty"))] -#[test_case("bash", false, SnapshotSandbox::DenyFdPath; "blocked_descriptor_path")] -#[cfg_attr(target_os = "macos", test_case("zsh", false, SnapshotSandbox::DenyFdPath; "zsh_blocked_descriptor_path"))] -#[cfg_attr(target_os = "macos", test_case("zsh", true, SnapshotSandbox::DenyFdPath; "zsh_blocked_descriptor_path_tty"))] +#[test_case("bash", false, SnapshotSandbox::CloseDescriptors; "closed_descriptor_transport")] +#[cfg_attr(target_os = "macos", test_case("zsh", false, SnapshotSandbox::CloseDescriptors; "zsh_closed_descriptor_transport"))] +#[cfg_attr(target_os = "macos", test_case("zsh", true, SnapshotSandbox::CloseDescriptors; "zsh_closed_descriptor_transport_tty"))] #[test_case("bash", false, SnapshotSandbox::WorkspaceWrite; "bash_protected_transport")] #[test_case("bash", true, SnapshotSandbox::WorkspaceWrite; "bash_protected_transport_tty")] #[cfg_attr(target_os = "macos", test_case("zsh", false, SnapshotSandbox::WorkspaceWrite; "zsh_protected_transport"))] @@ -105,7 +105,7 @@ async fn shell_snapshot_concurrent_replays_keep_independent_readers( tty: bool, sandbox_mode: SnapshotSandbox, ) -> Result<()> { - let deny_fd_path = sandbox_mode == SnapshotSandbox::DenyFdPath; + let close_descriptors = sandbox_mode == SnapshotSandbox::CloseDescriptors; let use_sandbox = sandbox_mode != SnapshotSandbox::None; if use_sandbox && let Some(warning) = codex_sandboxing::system_bwrap_warning( @@ -130,20 +130,20 @@ async fn shell_snapshot_concurrent_replays_keep_independent_readers( _server: None, } } else { - create_process_context(deny_fd_path).await? + create_process_context(close_descriptors).await? }; let home = TempDir::new()?; let cwd = PathUri::from_host_native_path(home.path())?; // Keep full-size state in a function, below the 512 KiB state + environment cap. // The blocked-path case still exercises the smaller environment fallback. - let payload_len = if deny_fd_path { 1 } else { 480 * 1024 }; + let payload_len = if close_descriptors { 1 } else { 480 * 1024 }; let payload = "x".repeat(payload_len); let source = if shell == "bash" { "${BASH_SOURCE[0]}" } else { "${(%):-%x}" }; - let source_check = if deny_fd_path { + let source_check = if close_descriptors { String::new() } else { format!("case \"{source}\" in /dev/fd/*) ;; *) return 42 ;; esac; ") @@ -159,6 +159,32 @@ async fn shell_snapshot_concurrent_replays_keep_independent_readers( "printf x >> \"$HOME/captures\"\nprofile_helper() {{ {source_check}local payload='{payload}'; [ \"${{#payload}}\" = {payload_len} ] || return 43; printf 'restored:%s' \"$1\"; }}\nexec() {{ exit 41; }}\nset -u\n{aliases}" ), )?; + let shell_path = if close_descriptors { + // Simulate a launcher that strips inherited readers. Mounting tmpfs on + // /dev/fd is invalid on Linux because it is a dynamic /proc/self/fd + // symlink; that fails before snapshot probing can exercise its fallback. + let wrapper = home.path().join("snapshot-shell"); + codex_utils_cargo_bin::write_executable( + &wrapper, + &format!( + r#"#!/usr/bin/python3 +import os +import sys +for descriptor in os.listdir('/dev/fd'): + try: + fd = int(descriptor) + if fd > 2: + os.close(fd) + except (OSError, ValueError): + pass +os.execv('/bin/{shell}', ['/bin/{shell}', *sys.argv[1:]]) +"# + ), + )?; + wrapper.to_string_lossy().into_owned() + } else { + format!("/bin/{shell}") + }; let protected_file = tempfile::NamedTempFile::new_in(codex_uds::prepare_shared_daemon_socket_directory()?)?; std::fs::write(protected_file.path(), "protected")?; @@ -181,12 +207,7 @@ async fn shell_snapshot_concurrent_replays_keep_independent_readers( cwd.clone().into(), FileSystemAccessMode::Write, )); - if deny_fd_path { - policy.entries.push(FileSystemSandboxEntry::new( - PathUri::from_host_native_path("/dev/fd")?.into(), - FileSystemAccessMode::Deny, - )); - } else { + if !close_descriptors { policy.entries.push(FileSystemSandboxEntry::new( PathUri::from_host_native_path(std::fs::canonicalize("/tmp")?)?.into(), FileSystemAccessMode::Write, @@ -205,45 +226,58 @@ async fn shell_snapshot_concurrent_replays_keep_independent_readers( let home = home.path(); let sandbox = sandbox.clone(); let command = command.clone(); + let shell_path = shell_path.clone(); let protected_path = protected_file.path(); async move { - let started = backend - .start(ExecParams { - metadata: Default::default(), - process_id: format!("parallel-{index}").into(), - argv: vec![format!("/bin/{shell}"), "-lc".to_string(), command], - cwd, - env: HashMap::new(), - env_policy: Some(ExecEnvPolicy { - inherit: ShellEnvironmentPolicyInherit::None, - ignore_default_excludes: false, - exclude: Vec::new(), - r#set: HashMap::from([ - ("HOME".to_string(), home.to_string_lossy().into_owned()), - ("PATH".to_string(), "/usr/bin:/bin".to_string()), - ( - "SNAPSHOT_TRANSPORT_PROBE".to_string(), - protected_path.to_string_lossy().into_owned(), - ), - ]), - include_only: Vec::new(), - }), - shell_snapshot: Some(ShellSnapshotRequest { - scope_id: "parallel".to_string(), - shell: ShellInfo { - name: shell.to_string(), - path: format!("/bin/{shell}"), - }, - }), - tty, - pipe_stdin: true, - arg0: None, - sandbox, - enforce_managed_network: false, - managed_network: None, - network_proxy: None, - }) - .await?; + let params = ExecParams { + metadata: Default::default(), + process_id: format!("parallel-{index}").into(), + argv: vec![shell_path.clone(), "-lc".to_string(), command], + cwd, + env: HashMap::new(), + env_policy: Some(ExecEnvPolicy { + inherit: ShellEnvironmentPolicyInherit::None, + ignore_default_excludes: false, + exclude: Vec::new(), + r#set: HashMap::from([ + ("HOME".to_string(), home.to_string_lossy().into_owned()), + ("PATH".to_string(), "/usr/bin:/bin".to_string()), + ( + "SNAPSHOT_TRANSPORT_PROBE".to_string(), + protected_path.to_string_lossy().into_owned(), + ), + ]), + include_only: Vec::new(), + }), + shell_snapshot: Some(ShellSnapshotRequest { + scope_id: "parallel".to_string(), + shell: ShellInfo { + name: shell.to_string(), + path: shell_path, + }, + }), + tty, + pipe_stdin: true, + arg0: None, + sandbox, + enforce_managed_network: false, + managed_network: None, + network_proxy: None, + }; + if close_descriptors && index == 0 { + let mut probe = params.clone(); + probe.process_id = "descriptor-sandbox-probe".into(); + probe.argv[2] = "printf sandbox-ready".to_string(); + probe.shell_snapshot = None; + probe.pipe_stdin = false; + let probe = backend.start(probe).await?; + assert_eq!( + collect_process_output_from_events(probe.process).await?, + ("sandbox-ready".to_string(), String::new(), Some(0), true), + "descriptor stripping must preserve ordinary sandboxed commands", + ); + } + let started = backend.start(params).await?; started .process .write(format!("input-{index}\n").into_bytes()) @@ -252,7 +286,7 @@ async fn shell_snapshot_concurrent_replays_keep_independent_readers( collect_process_output_from_events(started.process).await?; assert!( output.ends_with(&format!("restored:input-{index}")), - "{output:?}" + "stdout={output:?}, stderr={errors:?}, status={status:?}, closed={closed}" ); if shell == "zsh" { assert!( diff --git a/codex-rs/exec/src/main.rs b/codex-rs/exec/src/main.rs index 69d432acc090..13cc1e439bce 100644 --- a/codex-rs/exec/src/main.rs +++ b/codex-rs/exec/src/main.rs @@ -13,12 +13,15 @@ //! //! This allows us to ship a completely separate set of functionality as part //! of the `codex-exec` binary. +use clap::CommandFactory; use clap::Parser; use codex_arg0::Arg0DispatchPaths; use codex_arg0::arg0_dispatch_or_else; use codex_exec::Cli; use codex_exec::run_main; use codex_utils_cli::CliConfigOverrides; +use codex_utils_cli::collect_config_overrides; +use std::ffi::OsString; #[derive(Parser, Debug)] struct TopCli { @@ -31,18 +34,27 @@ struct TopCli { fn main() -> anyhow::Result<()> { arg0_dispatch_or_else(|arg0_paths: Arg0DispatchPaths| async move { - let top_cli = TopCli::parse(); - // Merge root-level overrides into inner CLI struct so downstream logic remains unchanged. - let mut inner = top_cli.inner; - inner - .config_overrides - .prepend_root_overrides(top_cli.config_overrides); - + let inner = parse_cli_from(std::env::args_os()).unwrap_or_else(|error| error.exit()); run_main(inner, arg0_paths).await?; Ok(()) }) } +fn parse_cli_from( + args: impl IntoIterator + Clone>, +) -> Result { + let args: Vec = args.into_iter().map(Into::into).collect(); + let mut top_cli = TopCli::try_parse_from(&args)?; + // As in the main CLI, preserve overrides on both sides of a subcommand. + // Clap's global append arguments otherwise retain only the deepest scope. + top_cli.config_overrides = collect_config_overrides(TopCli::command(), args)?; + let mut inner = top_cli.inner; + inner + .config_overrides + .prepend_root_overrides(top_cli.config_overrides); + Ok(inner) +} + #[cfg(test)] #[path = "main_tests.rs"] mod tests; diff --git a/codex-rs/exec/src/main_tests.rs b/codex-rs/exec/src/main_tests.rs index 5c0a8a3bfceb..6e8f82f3af6b 100644 --- a/codex-rs/exec/src/main_tests.rs +++ b/codex-rs/exec/src/main_tests.rs @@ -1,6 +1,34 @@ use super::*; use pretty_assertions::assert_eq; +#[test] +fn standalone_exec_preserves_config_order_across_resume_boundary() { + let cli = parse_cli_from([ + "codex-exec", + "-c", + "model_providers.openai.stream_max_retries=0", + "-c", + "model_reasoning_effort=low", + "resume", + "--last", + "--config", + "model_reasoning_effort=xhigh", + "--config", + "openai_base_url=\"http://127.0.0.1:1234/v1\"", + "continue", + ]) + .expect("parse standalone exec"); + assert_eq!( + cli.config_overrides.raw_overrides, + vec![ + "model_providers.openai.stream_max_retries=0", + "model_reasoning_effort=low", + "model_reasoning_effort=xhigh", + "openai_base_url=\"http://127.0.0.1:1234/v1\"", + ] + ); +} + #[test] fn top_cli_parses_resume_prompt_after_config_flag() { const PROMPT: &str = "echo resume-with-global-flags-after-subcommand"; diff --git a/codex-rs/exec/tests/suite/apply_patch.rs b/codex-rs/exec/tests/suite/apply_patch.rs index 71ab2483de3e..fbdd4309d133 100644 --- a/codex-rs/exec/tests/suite/apply_patch.rs +++ b/codex-rs/exec/tests/suite/apply_patch.rs @@ -217,7 +217,16 @@ async fn nested_apply_patch_alias_works_with_restricted_reads() -> anyhow::Resul let test = test_codex_exec(); let binary = codex_utils_cargo_bin::cargo_bin("codex-exec")?.canonicalize()?; let binary_dir = serde_json::to_string(binary.parent().expect("binary directory"))?; - let codex_home = serde_json::to_string(test.home_path())?; + // The generated executable aliases live below CODEX_HOME. Permit only that + // helper directory while keeping credentials and the sentinel unreadable + // through the restricted baseline. An explicit denial of all CODEX_HOME + // would also deny its helpers, taking precedence over this read grant. + let aliases = serde_json::to_string( + &test + .home_path() + .join("tmp") + .join(format!("arg0-{}", std::env::consts::OS)), + )?; fs::write( test.home_path().join("config.toml"), format!( @@ -230,7 +239,7 @@ shell_snapshot_v2 = false ":minimal" = "read" ":project_roots" = "write" {binary_dir} = "read" -{codex_home} = "none" +{aliases} = "read" "# ), )?; diff --git a/codex-rs/exec/tests/suite/resume.rs b/codex-rs/exec/tests/suite/resume.rs index 1594b6db661e..69cf2d859d96 100644 --- a/codex-rs/exec/tests/suite/resume.rs +++ b/codex-rs/exec/tests/suite/resume.rs @@ -636,7 +636,7 @@ async fn exec_resume_accepts_global_flags_after_subcommand() -> anyhow::Result<( .arg("--model") .arg("gpt-5.2-codex") .arg("--config") - .arg("reasoning_level=xhigh") + .arg("model_reasoning_effort=xhigh") .arg("--dangerously-bypass-approvals-and-sandbox") .arg("--skip-git-repo-check") .arg("echo resume-with-global-flags-after-subcommand") diff --git a/codex-rs/ext/skills/src/host_roots_tests.rs b/codex-rs/ext/skills/src/host_roots_tests.rs index c6fb5ec0967d..f213ddd62060 100644 --- a/codex-rs/ext/skills/src/host_roots_tests.rs +++ b/codex-rs/ext/skills/src/host_roots_tests.rs @@ -444,10 +444,18 @@ async fn repo_ancestry_without_project_marker_does_not_walk_parents() { let cwd = outer.join("nested/inner"); fs::create_dir_all(outer.join(".agents/skills")).expect("create outer skills"); fs::create_dir_all(cwd.join(".agents/skills")).expect("create cwd skills"); + let config = ConfigLayerEntry::new( + ConfigLayerSource::User { + file: outer.join("config.toml"), + profile: None, + }, + toml::from_str("project_root_markers = ['.codefx-test-root']") + .expect("valid project root marker config"), + ); let roots = repo_agents_skill_roots( Some(Arc::clone(&LOCAL_FS)), - &stack(Vec::new()), + &stack(vec![config]), &cwd, /*empty_remote_roots*/ None, ) diff --git a/codex-rs/features/src/lib.rs b/codex-rs/features/src/lib.rs index 129b09668c31..27d65b76bfa9 100644 --- a/codex-rs/features/src/lib.rs +++ b/codex-rs/features/src/lib.rs @@ -1623,7 +1623,7 @@ pub const FEATURES: &[FeatureSpec] = &[ id: Feature::Apps, key: "apps", stage: Stage::Stable, - default_enabled: true, + default_enabled: false, }, FeatureSpec { id: Feature::Psp, @@ -1839,7 +1839,7 @@ pub const FEATURES: &[FeatureSpec] = &[ id: Feature::RemotePlugin, key: "remote_plugin", stage: Stage::Stable, - default_enabled: true, + default_enabled: false, }, FeatureSpec { id: Feature::PluginDiscoveryPrefetch, @@ -1851,7 +1851,7 @@ pub const FEATURES: &[FeatureSpec] = &[ id: Feature::PluginSharing, key: "plugin_sharing", stage: Stage::Stable, - default_enabled: true, + default_enabled: false, }, FeatureSpec { id: Feature::ExternalMigration, diff --git a/codex-rs/features/src/tests.rs b/codex-rs/features/src/tests.rs index c791fb4684d2..8e4ac3692d48 100644 --- a/codex-rs/features/src/tests.rs +++ b/codex-rs/features/src/tests.rs @@ -571,12 +571,36 @@ fn codex_hooks_is_legacy_alias_for_hooks() { fn apps_require_feature_flag_and_chatgpt_auth() { let mut features = Features::with_defaults(); assert!(!features.apps_enabled_for_auth(/*has_chatgpt_auth*/ false)); + assert!(!features.apps_enabled_for_auth(/*has_chatgpt_auth*/ true)); features.enable(Feature::Apps); assert!(!features.apps_enabled_for_auth(/*has_chatgpt_auth*/ false)); assert!(features.apps_enabled_for_auth(/*has_chatgpt_auth*/ true)); } +#[test] +fn account_integrations_require_explicit_feature_opt_in() { + let mut features = Features::with_defaults(); + for feature in [Feature::Apps, Feature::RemotePlugin, Feature::PluginSharing] { + assert!( + !features.enabled(feature), + "{} must default off", + feature.key() + ); + } + let config: FeaturesToml = + toml::from_str("apps = true\nremote_plugin = true\nplugin_sharing = true\n") + .expect("explicit feature settings"); + features.apply_toml(&config); + for feature in [Feature::Apps, Feature::RemotePlugin, Feature::PluginSharing] { + assert!( + features.enabled(feature), + "{} can be explicitly enabled", + feature.key() + ); + } +} + #[test] fn from_sources_applies_base_profile_and_overrides() { let mut base_entries = BTreeMap::new(); diff --git a/codex-rs/http-client/Cargo.toml b/codex-rs/http-client/Cargo.toml index fa144cbb7005..f0906e962940 100644 --- a/codex-rs/http-client/Cargo.toml +++ b/codex-rs/http-client/Cargo.toml @@ -13,7 +13,7 @@ http-body = "1.0.1" httpdate = { workspace = true } native-tls = "0.2" opentelemetry = { workspace = true } -reqwest = { workspace = true, features = ["json", "rustls-tls", "rustls-tls-native-roots", "stream"] } +reqwest = { workspace = true, features = ["json", "native-tls", "rustls-tls", "rustls-tls-native-roots", "stream"] } rustls = { workspace = true } rustls-native-certs = { workspace = true } rustls-pki-types = { workspace = true } diff --git a/codex-rs/http-client/src/client_builder.rs b/codex-rs/http-client/src/client_builder.rs index 7de37b90ffee..e01791ce264b 100644 --- a/codex-rs/http-client/src/client_builder.rs +++ b/codex-rs/http-client/src/client_builder.rs @@ -392,6 +392,10 @@ impl HttpClientBuilder { if self.tls_backend == TlsBackend::Rustls || self.tls.client_identity.is_some() { ensure_rustls_crypto_provider(); builder = builder.use_rustls_tls(); + } else { + // Cargo feature unification can enable reqwest's rustls default through + // another workspace member. Keep our native-first fallback contract. + builder = builder.use_native_tls(); } if let Some(certificate) = self.tls.root_certificate { builder = builder diff --git a/codex-rs/http-client/src/route_aware_client_pool.rs b/codex-rs/http-client/src/route_aware_client_pool.rs index f327b1045f26..32923ec3662f 100644 --- a/codex-rs/http-client/src/route_aware_client_pool.rs +++ b/codex-rs/http-client/src/route_aware_client_pool.rs @@ -127,7 +127,15 @@ impl RouteAwareRequestError { if error.to_string() == "tunnel error: proxy authorization required" { return Some(RouteFailureClass::ProxyAuthenticationRequired); } - source = error.source(); + // io::Error::source skips the wrapped error itself. TLS transports + // can put their typed certificate error directly in that payload. + source = if let Some(error) = error.downcast_ref::() { + error + .get_ref() + .map(|error| error as &(dyn std::error::Error + 'static)) + } else { + error.source() + }; } match self { diff --git a/codex-rs/http-client/src/route_aware_client_pool_tests.rs b/codex-rs/http-client/src/route_aware_client_pool_tests.rs index 0c4a453976d9..bc52959f2f22 100644 --- a/codex-rs/http-client/src/route_aware_client_pool_tests.rs +++ b/codex-rs/http-client/src/route_aware_client_pool_tests.rs @@ -227,6 +227,15 @@ async fn direct_and_routed_clients_build_equivalent_requests() { #[tokio::test] async fn request_failures_classify_real_untrusted_certificate_handshakes() { + assert_untrusted_certificate_failure(/*rustls*/ false).await; +} + +#[tokio::test] +async fn request_failures_classify_real_untrusted_rustls_certificate_handshakes() { + assert_untrusted_certificate_failure(/*rustls*/ true).await; +} + +async fn assert_untrusted_certificate_failure(rustls: bool) { codex_utils_rustls_provider::ensure_rustls_crypto_provider(); let certificate = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]) .expect("self-signed certificate should generate"); @@ -252,9 +261,16 @@ async fn request_failures_classify_real_untrusted_certificate_handshakes() { .expect("TLS server connection should be created"); let _ = connection.complete_io(&mut stream); }); - let pool = RouteAwareClientPool::new_without_request_logging( + let builder = HttpClientBuilder::new().without_request_logging(); + let builder = if rustls { + builder.with_rustls_tls() + } else { + builder + }; + let pool = RouteAwareClientPool::with_builder( HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), ClientRouteClass::Api, + builder, ); let mut request = reqwest::Request::new( diff --git a/codex-rs/http-client/src/route_aware_redirect_integration_tests.rs b/codex-rs/http-client/src/route_aware_redirect_integration_tests.rs index 344e8a7f6b01..71df6ce7df4c 100644 --- a/codex-rs/http-client/src/route_aware_redirect_integration_tests.rs +++ b/codex-rs/http-client/src/route_aware_redirect_integration_tests.rs @@ -75,9 +75,13 @@ async fn route_aware_pool_re_resolves_redirects_and_logs_only_final_outcome() { let logs = String::from_utf8(log_buffer.lock().expect("log buffer lock").clone()) .expect("logs should be UTF-8"); - assert!(logs.contains(&initial_url)); - assert_eq!(logs.matches("Request completed").count(), 1); - assert!(!logs.contains("redirect-target-secret")); + // Bazel may compile DEBUG events out; request routing and header checks + // above continue to run in every configuration. + if tracing::enabled!(tracing::Level::DEBUG) { + assert!(logs.contains(&initial_url), "captured logs: {logs}"); + assert_eq!(logs.matches("Request completed").count(), 1); + assert!(!logs.contains("redirect-target-secret")); + } } fn spawn_response( diff --git a/codex-rs/http-client/src/route_aware_tls_fallback_tests.rs b/codex-rs/http-client/src/route_aware_tls_fallback_tests.rs index 8cdfae666300..4fc0a256c222 100644 --- a/codex-rs/http-client/src/route_aware_tls_fallback_tests.rs +++ b/codex-rs/http-client/src/route_aware_tls_fallback_tests.rs @@ -35,8 +35,40 @@ type SuccessfulTlsFallbackServer = ( mpsc::Receiver>>, ); +#[tokio::test] +async fn native_transport_protocol_error_remains_recognizable() { + if run_without_ca_overrides() { + return; + } + let (url, attempts, stop_server) = + spawn_protocol_version_rejection_server(/*maximum_attempts*/ 1).unwrap(); + let error = reqwest::Client::builder() + .use_native_tls() + .no_proxy() + .build() + .unwrap() + .get(url) + .send() + .await + .expect_err("protocol rejection"); + let _ = stop_server.send(()); + assert_eq!(attempts.recv().unwrap().unwrap(), 1); + assert!( + should_retry_with_rustls(&error), + "raw native TLS error: {error:?}" + ); + assert!( + std::env::var_os("CODEX_CA_CERTIFICATE").is_none() + && std::env::var_os("SSL_CERT_FILE").is_none(), + "native TLS fixture must not inherit custom CA settings" + ); +} + #[tokio::test] async fn default_pool_does_not_retry_a_native_tls_protocol_failure() { + if run_without_ca_overrides() { + return; + } let (url, attempts, stop_server) = spawn_protocol_version_rejection_server(/*maximum_attempts*/ 2) .expect("TLS rejection server should start"); @@ -67,6 +99,9 @@ async fn default_pool_does_not_retry_a_native_tls_protocol_failure() { #[tokio::test] async fn retries_a_native_tls_protocol_failure_once_with_rustls() { + if run_without_ca_overrides() { + return; + } let (url, attempts, stop_server) = spawn_protocol_version_rejection_server(/*maximum_attempts*/ 2) .expect("TLS rejection server should start"); @@ -108,6 +143,9 @@ async fn retries_a_native_tls_protocol_failure_once_with_rustls() { #[tokio::test] async fn retries_a_native_tls_failure_after_another_request_caches_rustls() { + if run_without_ca_overrides() { + return; + } let (url, attempts, stop_server) = spawn_protocol_version_rejection_server(/*maximum_attempts*/ 2) .expect("TLS rejection server should start"); @@ -167,6 +205,9 @@ async fn retries_a_native_tls_failure_after_another_request_caches_rustls() { #[tokio::test] async fn does_not_retry_a_cached_rustls_tls_protocol_failure() { + if run_without_ca_overrides() { + return; + } let (url, attempts, stop_server) = spawn_protocol_version_rejection_server(/*maximum_attempts*/ 2) .expect("TLS rejection server should start"); @@ -204,6 +245,9 @@ async fn does_not_retry_a_cached_rustls_tls_protocol_failure() { #[tokio::test] async fn successful_rustls_fallback_replays_the_request_and_reuses_the_destination() { + if run_without_ca_overrides() { + return; + } let (url, trusted_rustls_client, observed_requests) = spawn_successful_tls_fallback_server().expect("TLS fallback server should start"); let pool = RouteAwareClientPool::new( @@ -268,6 +312,9 @@ async fn successful_rustls_fallback_replays_the_request_and_reuses_the_destinati #[tokio::test] async fn retries_a_tls_protocol_failure_when_request_url_contains_certificate_markers() { + if run_without_ca_overrides() { + return; + } let (url, attempts, stop_server) = spawn_protocol_version_rejection_server(/*maximum_attempts*/ 2) .expect("TLS rejection server should start"); @@ -299,6 +346,9 @@ async fn retries_a_tls_protocol_failure_when_request_url_contains_certificate_ma #[tokio::test] async fn does_not_retry_a_non_replayable_streaming_request() { + if run_without_ca_overrides() { + return; + } let (url, attempts, stop_server) = spawn_protocol_version_rejection_server(/*maximum_attempts*/ 2) .expect("TLS rejection server should start"); @@ -341,6 +391,38 @@ async fn does_not_retry_a_non_replayable_streaming_request() { ); } +// Custom CA configuration intentionally selects rustls before the first request. +// These fixtures exercise native-first fallback and must not inherit that setting. +// Re-exec instead of mutating the environment of parallel Rust tests. +fn run_without_ca_overrides() -> bool { + if ["CODEX_CA_CERTIFICATE", "SSL_CERT_FILE"] + .iter() + .all(|name| std::env::var_os(name).is_none()) + { + return false; + } + assert!( + std::env::var_os("CODEX_TLS_FALLBACK_ISOLATED").is_none(), + "CA overrides must remain absent in the isolated fixture" + ); + let thread = std::thread::current(); + let test = thread.name().expect("named test thread"); + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", test, "--nocapture"]) + .env_remove("CODEX_CA_CERTIFICATE") + .env_remove("SSL_CERT_FILE") + .env("CODEX_TLS_FALLBACK_ISOLATED", "1") + .output() + .expect("isolated native TLS fixture should run"); + assert!( + output.status.success(), + "{test} failed without CA overrides\nstdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr), + ); + true +} + fn spawn_successful_tls_fallback_server() -> io::Result { codex_utils_rustls_provider::ensure_rustls_crypto_provider(); let CertifiedKey { cert, signing_key } = diff --git a/codex-rs/linux-sandbox/tests/suite/managed_proxy.rs b/codex-rs/linux-sandbox/tests/suite/managed_proxy.rs index 49f47f342a70..1545566994a2 100644 --- a/codex-rs/linux-sandbox/tests/suite/managed_proxy.rs +++ b/codex-rs/linux-sandbox/tests/suite/managed_proxy.rs @@ -795,9 +795,18 @@ async fn managed_proxy_mode_routes_through_bridge_and_blocks_direct_egress() { format!("http://127.0.0.1:{proxy_port}"), ); - let sandbox_helper_dir = std::path::Path::new(env!("CARGO_BIN_EXE_codex-linux-sandbox")) + let sandbox_helper = Path::new(env!("CARGO_BIN_EXE_codex-linux-sandbox")); + let sandbox_helper_dir = sandbox_helper .parent() .expect("sandbox helper should have a parent"); + // Bazel may symlink the binary itself to another tree; expose both the + // logical executable and its real target to nested bubblewrap. + let resolved_sandbox_helper = sandbox_helper + .canonicalize() + .expect("sandbox helper path should resolve"); + let resolved_sandbox_helper_dir = resolved_sandbox_helper + .parent() + .expect("resolved sandbox helper should have a parent"); let file_system_sandbox_policy = FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry { path: FileSystemPath::Special { @@ -810,7 +819,14 @@ async fn managed_proxy_mode_routes_through_bridge_and_blocks_direct_egress() { std::env::current_dir() .expect("current directory should exist") .as_path(), - &[AbsolutePathBuf::try_from(sandbox_helper_dir).expect("absolute helper dir")], + &[ + AbsolutePathBuf::try_from(sandbox_helper_dir).expect("absolute helper dir"), + AbsolutePathBuf::try_from(resolved_sandbox_helper_dir) + .expect("absolute resolved helper dir"), + AbsolutePathBuf::try_from(sandbox_helper).expect("absolute helper executable"), + AbsolutePathBuf::try_from(resolved_sandbox_helper.as_path()) + .expect("absolute resolved helper executable"), + ], ); let permission_profile = PermissionProfile::from_runtime_permissions( &file_system_sandbox_policy, diff --git a/codex-rs/linux-sandbox/tests/suite/root_metadata_tests.rs b/codex-rs/linux-sandbox/tests/suite/root_metadata_tests.rs index fe7d4dcc2086..0f0c8b3078eb 100644 --- a/codex-rs/linux-sandbox/tests/suite/root_metadata_tests.rs +++ b/codex-rs/linux-sandbox/tests/suite/root_metadata_tests.rs @@ -35,6 +35,14 @@ async fn root_metadata_symlinks_cannot_reopen_approved_denials() { fs::write(private.join("sibling"), "sibling").unwrap(); codex_utils_cargo_bin::copy_executable(&codex_linux_sandbox_exe(), &work.join("sandbox")) .unwrap(); + // The outer namespace maps this user to root. System executable trust checks + // can then reject /usr/bin/bwrap, so model the real package's bundled fallback. + fs::create_dir(work.join("codex-resources")).unwrap(); + codex_utils_cargo_bin::copy_executable( + &codex_utils_cargo_bin::cargo_bin("bwrap").expect("built bubblewrap fixture"), + &work.join("codex-resources/bwrap"), + ) + .unwrap(); let path_entry = |path: &str, access| { FileSystemSandboxEntry::new( diff --git a/codex-rs/model-provider-info/src/lib.rs b/codex-rs/model-provider-info/src/lib.rs index 18a2a076233d..ad802a5673b6 100644 --- a/codex-rs/model-provider-info/src/lib.rs +++ b/codex-rs/model-provider-info/src/lib.rs @@ -782,7 +782,7 @@ pub fn built_in_model_providers( /// Merge configured providers into the built-in provider catalog. /// /// Configured providers extend the built-in set. Built-in providers are not -/// generally overridable. OpenAI allows a catalog URL override, while the +/// generally overridable. OpenAI allows retry/timeout settings and a catalog URL override, while the /// cloud-hosted OpenAI providers allow a limited /// set of endpoint, authentication, header, and cloud-specific overrides. pub fn merge_configured_model_providers( @@ -792,7 +792,23 @@ pub fn merge_configured_model_providers( for (key, mut provider) in configured_model_providers { if key == "openai" { // Keep the built-in identity, inference routing, and authentication. - // Only catalog routing is configurable through this provider entry. + // Only transport budgets and catalog routing are configurable here. + // Transport budgets do not change provider identity, routing, or auth. + // Preserve explicit zero values, including immediate WebSocket fallback. + if let Some(built_in_provider) = model_providers.get_mut(&key) { + built_in_provider.request_max_retries = provider + .request_max_retries + .or(built_in_provider.request_max_retries); + built_in_provider.stream_max_retries = provider + .stream_max_retries + .or(built_in_provider.stream_max_retries); + built_in_provider.stream_idle_timeout_ms = provider + .stream_idle_timeout_ms + .or(built_in_provider.stream_idle_timeout_ms); + built_in_provider.websocket_connect_timeout_ms = provider + .websocket_connect_timeout_ms + .or(built_in_provider.websocket_connect_timeout_ms); + } if let Some(catalog_url) = provider.model_catalog_url.take() && let Some(built_in_provider) = model_providers.get_mut(&key) { diff --git a/codex-rs/model-provider-info/src/model_provider_info_tests.rs b/codex-rs/model-provider-info/src/model_provider_info_tests.rs index 0d3742f81edc..0607cebbf88a 100644 --- a/codex-rs/model-provider-info/src/model_provider_info_tests.rs +++ b/codex-rs/model-provider-info/src/model_provider_info_tests.rs @@ -1017,6 +1017,35 @@ fn builtin_openai_catalog_override_preserves_inference_and_identity() { } } +#[test] +fn builtin_openai_transport_limits_preserve_routing_and_authentication() { + let configured = ModelProviderInfo { + name: "Ignored name".to_string(), + base_url: Some("https://ignored.example/v1".to_string()), + requires_openai_auth: false, + request_max_retries: Some(0), + stream_max_retries: Some(0), + stream_idle_timeout_ms: Some(1234), + websocket_connect_timeout_ms: Some(5678), + ..Default::default() + }; + let builtins = built_in_model_providers(Some("https://api.openai.com/v1".to_string())); + let mut expected = builtins.clone(); + let openai = expected.get_mut("openai").unwrap(); + openai.request_max_retries = Some(0); + openai.stream_max_retries = Some(0); + openai.stream_idle_timeout_ms = Some(1234); + openai.websocket_connect_timeout_ms = Some(5678); + assert_eq!( + merge_configured_model_providers( + builtins, + HashMap::from([("openai".to_string(), configured)]), + ) + .unwrap(), + expected, + ); +} + #[test] fn builtin_openai_catalog_rejects_untrusted_destinations() { for url in [ diff --git a/codex-rs/tcp-tunnel/src/diagnostics_tests.rs b/codex-rs/tcp-tunnel/src/diagnostics_tests.rs index 7e9b86209457..e007491e1471 100644 --- a/codex-rs/tcp-tunnel/src/diagnostics_tests.rs +++ b/codex-rs/tcp-tunnel/src/diagnostics_tests.rs @@ -113,7 +113,7 @@ fn legacy_errors_and_successful_shutdown_produce_no_json() { fn handshake_timeout_preserves_legacy_debug_output() { let error = anyhow!(Code::HandshakeTimeout); assert_eq!( - format!("{error:?}"), + error.to_string(), "QUIC handshake failed: QUIC handshake timed out" ); let mut output = Vec::new(); diff --git a/codex-rs/tui/src/app/tests/connector_policy.rs b/codex-rs/tui/src/app/tests/connector_policy.rs index a806e90e2234..fb85f84e8388 100644 --- a/codex-rs/tui/src/app/tests/connector_policy.rs +++ b/codex-rs/tui/src/app/tests/connector_policy.rs @@ -65,6 +65,8 @@ async fn installed_connector_mentions_ignore_stale_thread_workspace_and_account( #[tokio::test] async fn queued_connector_fetches_are_bound_to_their_original_account() -> Result<()> { let (mut app, mut app_event_rx, _op_rx) = make_test_app_with_channels().await; + app.chat_widget + .set_feature_enabled(Feature::Apps, /*enabled*/ true); let cwd = app.chat_widget.config_ref().cwd.to_path_buf(); app.chat_widget .handle_thread_session(test_thread_session(ThreadId::new(), cwd)); @@ -102,6 +104,8 @@ async fn queued_connector_fetches_are_bound_to_their_original_account() -> Resul async fn app_list_notifications_revalidate_installed_mentions_and_the_current_directory() -> Result<()> { let (mut app, mut app_event_rx, _op_rx) = make_test_app_with_channels().await; + app.chat_widget + .set_feature_enabled(Feature::Apps, /*enabled*/ true); let thread_id = ThreadId::new(); let cwd = app.chat_widget.config_ref().cwd.to_path_buf(); app.chat_widget diff --git a/codex-rs/tui/src/app/tests/marketplace_upgrade_tests.rs b/codex-rs/tui/src/app/tests/marketplace_upgrade_tests.rs index 173268cb0dc1..2fbae10be0a9 100644 --- a/codex-rs/tui/src/app/tests/marketplace_upgrade_tests.rs +++ b/codex-rs/tui/src/app/tests/marketplace_upgrade_tests.rs @@ -1,4 +1,4 @@ -//! Marketplace startup failures reach the warning notice and its details view. +//! Warning notifications reach the warning notice and its details view. use super::*; use crate::app::owned_transcript::tests::buffer_text; @@ -9,7 +9,7 @@ use codex_config::MarketplaceConfigUpdate; use codex_config::record_user_marketplace; #[tokio::test] -async fn automatic_marketplace_upgrade_failure_shows_warning() -> Result<()> { +async fn marketplace_upgrade_warning_notification_shows_details() -> Result<()> { let (mut app, mut events, _ops) = make_test_app_with_channels().await; let source = tempdir()?; std::fs::create_dir_all(source.path().join(".agents/plugins"))?; @@ -65,18 +65,20 @@ async fn automatic_marketplace_upgrade_failure_shows_warning() -> Result<()> { while events.try_recv().is_ok() {} let mut server = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?; - let mut warnings_received = 0; - while warnings_received < marketplace_names.len() { - let event = server.next_event().await.expect("app-server notification"); - let is_warning = matches!( - &event.event, - AppServerEvent::ServerNotification(notification) - if matches!(notification.as_ref(), ServerNotification::Warning(_)) - ); - app.handle_backend_event(&server, event).await; - if is_warning { - warnings_received += 1; - } + // Automatic marketplace updates are disabled. Exercise the warning UI with + // explicit notifications instead of waiting for an automatic Git operation. + for marketplace in marketplace_names { + app.handle_app_server_event( + &server, + AppServerEvent::ServerNotification(Box::new(ServerNotification::Warning( + codex_app_server_protocol::WarningNotification { + thread_id: None, + message: format!( + "Codex could not update marketplace `{marketplace}`: upgraded marketplace name `other` does not match configured marketplace `{marketplace}`" + ), + }, + ))), + ).await; } let mut tui = crate::tui::test_support::make_test_tui()?; diff --git a/codex-rs/tui/src/chatwidget/tests/helpers.rs b/codex-rs/tui/src/chatwidget/tests/helpers.rs index 3ac0a5b8114b..8f8ee202f85e 100644 --- a/codex-rs/tui/src/chatwidget/tests/helpers.rs +++ b/codex-rs/tui/src/chatwidget/tests/helpers.rs @@ -42,6 +42,9 @@ pub(super) fn truncated_path_variants(path: &str) -> Vec { pub(crate) fn normalize_snapshot_paths(text: impl Into) -> String { let mut text = text.into(); + // Snapshot fixtures must be stable regardless of the compiled crate version. + let version = format!("OpenAI Codex (v{})", env!("CARGO_PKG_VERSION")); + text = text.replace(&version, "OpenAI Codex (v0.0.0)"); for unix_path in ["/tmp/project", "/tmp/hooks.json"] { let platform_path = test_path_display(unix_path); diff --git a/codex-rs/tui/src/chatwidget/tests/popups_and_settings.rs b/codex-rs/tui/src/chatwidget/tests/popups_and_settings.rs index 54e1f1fc67cc..7950af9f8552 100644 --- a/codex-rs/tui/src/chatwidget/tests/popups_and_settings.rs +++ b/codex-rs/tui/src/chatwidget/tests/popups_and_settings.rs @@ -1274,6 +1274,7 @@ async fn plugins_popup_remote_section_fallback_states_when_remote_plugin_disable let (mut remote_chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; remote_chat.set_feature_enabled(Feature::Plugins, /*enabled*/ true); + remote_chat.set_feature_enabled(Feature::RemotePlugin, /*enabled*/ true); remote_chat.add_plugins_output(); let remote_cwd = remote_chat.config.cwd.clone(); remote_chat.on_plugins_loaded( @@ -4386,6 +4387,7 @@ async fn reasoning_popup_escape_returns_to_model_popup() { #[tokio::test] async fn account_change_dismisses_the_previous_app_directory_snapshot() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; + chat.set_feature_enabled(Feature::Apps, /*enabled*/ true); chat.thread_id = Some(ThreadId::new()); set_chatgpt_auth(&mut chat); chat.on_connectors_loaded( diff --git a/codex-rs/tui/src/history_cell/snapshots/codex_tui__history_cell__tests__pnpm_update_available_history_cell_snapshot.snap b/codex-rs/tui/src/history_cell/snapshots/codex_tui__history_cell__tests__pnpm_update_available_history_cell_snapshot.snap index aeb365d3b99e..2647a4e3a9d4 100644 --- a/codex-rs/tui/src/history_cell/snapshots/codex_tui__history_cell__tests__pnpm_update_available_history_cell_snapshot.snap +++ b/codex-rs/tui/src/history_cell/snapshots/codex_tui__history_cell__tests__pnpm_update_available_history_cell_snapshot.snap @@ -1,11 +1,14 @@ --- source: tui/src/history_cell/tests.rs +assertion_line: 1399 expression: rendered --- -╭─────────────────────────────────────────────────╮ -│ ✨ Update available! 0.0.0 -> 9.9.9 │ -│ Run curl -fsSL https://raw.githubusercontent.com/caokai674/codefx/main/scripts/install/install-codefx.sh | CODEFX_REPLACE_OFFICIAL=1 CODEX_NON_INTERACTIVE=1 sh to update. │ -│ │ -│ See full release notes: │ -│ https://github.com/caokai674/codefx/releases/latest │ -╰─────────────────────────────────────────────────╯ +╭────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ +│ ✨ Update available! 0.0.0 -> 9.9.9 │ +│ Run sh -c 'set -eu; installer="$(mktemp)"; trap '"'rm -f \""'$installer"'"' EXIT; curl -fsSL -o │ +│ \""'$installer" https://raw.githubusercontent.com/caokai674/codefx/main/scripts/install/install-codefx.sh; │ +│ test -s "$installer"; CODEFX_REPLACE_OFFICIAL=1 CODEX_NON_INTERACTIVE=1 sh "$installer"' to update. │ +│ │ +│ See full release notes: │ +│ https://github.com/caokai674/codefx/releases/latest │ +╰────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ diff --git a/codex-rs/tui/src/history_cell/snapshots/codex_tui__history_cell__tests__standalone_unix_update_available_history_cell_snapshot.snap b/codex-rs/tui/src/history_cell/snapshots/codex_tui__history_cell__tests__standalone_unix_update_available_history_cell_snapshot.snap index ce58a585493a..98a4b65c71b7 100644 --- a/codex-rs/tui/src/history_cell/snapshots/codex_tui__history_cell__tests__standalone_unix_update_available_history_cell_snapshot.snap +++ b/codex-rs/tui/src/history_cell/snapshots/codex_tui__history_cell__tests__standalone_unix_update_available_history_cell_snapshot.snap @@ -1,11 +1,14 @@ --- source: tui/src/history_cell/tests.rs +assertion_line: 1381 expression: rendered --- -╭─────────────────────────────────────────────────────────────────────────────────────────────────────╮ -│ ✨ Update available! 0.0.0 -> 9.9.9 │ -│ Run sh -c 'curl -fsSL https://raw.githubusercontent.com/caokai674/codefx/main/scripts/install/install-codefx.sh | CODEFX_REPLACE_OFFICIAL=1 CODEX_NON_INTERACTIVE=1 sh' to update. │ -│ │ -│ See full release notes: │ -│ https://github.com/caokai674/codefx/releases/latest │ -╰─────────────────────────────────────────────────────────────────────────────────────────────────────╯ +╭────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ +│ ✨ Update available! 0.0.0 -> 9.9.9 │ +│ Run sh -c 'set -eu; installer="$(mktemp)"; trap '"'rm -f \""'$installer"'"' EXIT; curl -fsSL -o │ +│ \""'$installer" https://raw.githubusercontent.com/caokai674/codefx/main/scripts/install/install-codefx.sh; │ +│ test -s "$installer"; CODEFX_REPLACE_OFFICIAL=1 CODEX_NON_INTERACTIVE=1 sh "$installer"' to update. │ +│ │ +│ See full release notes: │ +│ https://github.com/caokai674/codefx/releases/latest │ +╰────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ diff --git a/codex-rs/tui/src/history_cell/snapshots/codex_tui__history_cell__tests__standalone_windows_update_available_history_cell_snapshot.snap b/codex-rs/tui/src/history_cell/snapshots/codex_tui__history_cell__tests__standalone_windows_update_available_history_cell_snapshot.snap index 0800740bc0a1..c9e2bd85f78c 100644 --- a/codex-rs/tui/src/history_cell/snapshots/codex_tui__history_cell__tests__standalone_windows_update_available_history_cell_snapshot.snap +++ b/codex-rs/tui/src/history_cell/snapshots/codex_tui__history_cell__tests__standalone_windows_update_available_history_cell_snapshot.snap @@ -4,9 +4,11 @@ expression: rendered --- ╭────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ │ ✨ Update available! 0.0.0 -> 9.9.9 │ -│ Run powershell -ExecutionPolicy Bypass -c '$env:CODEX_NON_INTERACTIVE=1; irm │ -│ https://raw.githubusercontent.com/caokai674/codefx/main/scripts/install/install-codefx.ps1 | iex' to update. │ +│ Run powershell -ExecutionPolicy Bypass -c '$env:CODEFX_REPLACE_OFFICIAL='"'1'; │ +│ "'$env:CODEX_NON_INTERACTIVE='"'1'; irm │ +│ https://raw.githubusercontent.com/caokai674/codefx/main/scripts/install/install-codefx.ps1 | iex" to │ +│ update. │ │ │ │ See full release notes: │ -│ https://github.com/caokai674/codefx/releases/latest │ +│ https://github.com/caokai674/codefx/releases/latest │ ╰────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ diff --git a/codex-rs/tui/src/snapshots/codex_tui__update_prompt__tests__update_picker_selected_28x12.snap b/codex-rs/tui/src/snapshots/codex_tui__update_prompt__tests__update_picker_selected_28x12.snap index 53c8053051ed..0b8e03348e31 100644 --- a/codex-rs/tui/src/snapshots/codex_tui__update_prompt__tests__update_picker_selected_28x12.snap +++ b/codex-rs/tui/src/snapshots/codex_tui__update_prompt__tests__update_picker_selected_28x12.snap @@ -6,8 +6,8 @@ expression: rendered Update available · 0.0.0 → 9.9.9 Release notes: - https://github.com/opena - i/codex/releases/latest + https://github.com/caoka + i674/codefx/releases/lat ↑ › 3. Skip until next version diff --git a/codex-rs/tui/src/snapshots/codex_tui__update_prompt__tests__update_prompt_modal.snap b/codex-rs/tui/src/snapshots/codex_tui__update_prompt__tests__update_prompt_modal.snap index add7b572cd30..2c57c4693430 100644 --- a/codex-rs/tui/src/snapshots/codex_tui__update_prompt__tests__update_prompt_modal.snap +++ b/codex-rs/tui/src/snapshots/codex_tui__update_prompt__tests__update_prompt_modal.snap @@ -1,13 +1,16 @@ --- source: tui/src/update_prompt.rs +assertion_line: 301 expression: terminal.backend() --- Update available · 0.0.0 → 9.9.9 Release notes: https://github.com/caokai674/codefx/releases/latest -› 1. Update now (runs `curl -fsSL https://raw.githubusercontent.com/caokai674/codefx/main/scripts/install/install-codefx.sh | CODEFX_REPLACE_OFFICIAL=1 CODEX_NON_INTERACTIVE=1 sh`) - 2. Skip - 3. Skip until next version - +› 1. Update now (runs `sh -c 'set -eu; installer="$(mktemp)"; trap '"'rm -f + \""'$installer"'"' EXIT; curl -fsSL -o \""'$installer" https:// + raw.githubusercontent.com/caokai674/codefx/main/scripts/install/install- + codefx.sh; test -s "$installer"; CODEFX_REPLACE_OFFICIAL=1 + CODEX_NON_INTERACTIVE=1 sh "$installer"'`) +↓ enter continue · esc skip diff --git a/codex-rs/tui/src/status/tests.rs b/codex-rs/tui/src/status/tests.rs index c51f429dfa62..988826169ec2 100644 --- a/codex-rs/tui/src/status/tests.rs +++ b/codex-rs/tui/src/status/tests.rs @@ -186,9 +186,12 @@ fn render_lines(lines: &[Line<'static>]) -> Vec { } fn sanitize_directory(lines: Vec) -> Vec { + // Use a version-independent fixture across Cargo and Bazel builds. + let version = format!("OpenAI Codex (v{})", env!("CARGO_PKG_VERSION")); lines .into_iter() .map(|line| { + let line = line.replace(&version, "OpenAI Codex (v0.0.0)"); if let Some((prefix, value)) = line.split_once("Directory:") { let padding = &value[..value.len() - value.trim_start().len()]; format!("{prefix}Directory:{padding}[[workspace]]") diff --git a/codex-rs/tui/src/update_action.rs b/codex-rs/tui/src/update_action.rs index 9936e0ec4dd5..d88045d2881d 100644 --- a/codex-rs/tui/src/update_action.rs +++ b/codex-rs/tui/src/update_action.rs @@ -56,7 +56,7 @@ impl UpdateAction { "sh", &[ "-c", - "curl -fsSL https://raw.githubusercontent.com/caokai674/codefx/main/scripts/install/install-codefx.sh | CODEFX_REPLACE_OFFICIAL=1 CODEX_NON_INTERACTIVE=1 sh", + "set -eu; installer=\"$(mktemp)\"; trap 'rm -f \"$installer\"' EXIT; curl -fsSL -o \"$installer\" https://raw.githubusercontent.com/caokai674/codefx/main/scripts/install/install-codefx.sh; test -s \"$installer\"; CODEFX_REPLACE_OFFICIAL=1 CODEX_NON_INTERACTIVE=1 sh \"$installer\"", ], ), UpdateAction::StandaloneWindows => ( @@ -163,7 +163,7 @@ mod tests { "sh", &[ "-c", - "curl -fsSL https://raw.githubusercontent.com/caokai674/codefx/main/scripts/install/install-codefx.sh | CODEFX_REPLACE_OFFICIAL=1 CODEX_NON_INTERACTIVE=1 sh" + "set -eu; installer=\"$(mktemp)\"; trap 'rm -f \"$installer\"' EXIT; curl -fsSL -o \"$installer\" https://raw.githubusercontent.com/caokai674/codefx/main/scripts/install/install-codefx.sh; test -s \"$installer\"; CODEFX_REPLACE_OFFICIAL=1 CODEX_NON_INTERACTIVE=1 sh \"$installer\"" ][..], ) ); diff --git a/codex-rs/tui/src/update_prompt.rs b/codex-rs/tui/src/update_prompt.rs index 843e4d34deaa..8506b9d66983 100644 --- a/codex-rs/tui/src/update_prompt.rs +++ b/codex-rs/tui/src/update_prompt.rs @@ -126,7 +126,7 @@ impl UpdatePromptScreen { Self { request_frame, latest_version, - current_version: env!("CARGO_PKG_VERSION").to_string(), + current_version: crate::version::CODEX_CLI_VERSION.to_string(), update_action, highlighted: UpdateSelection::UpdateNow, selection: None, diff --git a/codex-rs/tui/src/version.rs b/codex-rs/tui/src/version.rs index 8c8d108dc613..01440e2a16eb 100644 --- a/codex-rs/tui/src/version.rs +++ b/codex-rs/tui/src/version.rs @@ -1,2 +1,7 @@ /// The current Codex CLI version as embedded at compile time. +/// Snapshot tests use a stable fixture, while published binaries expose the +/// actual package version. +#[cfg(not(test))] pub const CODEX_CLI_VERSION: &str = env!("CARGO_PKG_VERSION"); +#[cfg(test)] +pub const CODEX_CLI_VERSION: &str = "0.0.0"; diff --git a/codex-rs/tui/tests/suite/focus_palette.rs b/codex-rs/tui/tests/suite/focus_palette.rs index 084599ce1c38..e6cb3c6c7a49 100644 --- a/codex-rs/tui/tests/suite/focus_palette.rs +++ b/codex-rs/tui/tests/suite/focus_palette.rs @@ -387,6 +387,8 @@ impl PtyCodex { .env_remove("TERM_PROGRAM_VERSION") .env("OPENAI_API_KEY", "focus-palette-test") .env("CODEX_HOME", codex_home.path()) + // Keep panic diagnostics while making CLI error snapshots deterministic. + .env("RUST_LIB_BACKTRACE", "0") .stdin(stdin) .stdout(stdout) .stderr(slave.try_clone()?) diff --git a/codex-rs/v8-poc/Cargo.toml b/codex-rs/v8-poc/Cargo.toml index 9615ab977f9d..a34a1306f108 100644 --- a/codex-rs/v8-poc/Cargo.toml +++ b/codex-rs/v8-poc/Cargo.toml @@ -10,6 +10,7 @@ path = "src/lib.rs" doctest = false [features] +default = ["sandbox"] sandbox = ["v8/v8_enable_sandbox"] [lints] diff --git a/codex-rs/v8-poc/src/lib.rs b/codex-rs/v8-poc/src/lib.rs index 500bb986e57c..a9f450914205 100644 --- a/codex-rs/v8-poc/src/lib.rs +++ b/codex-rs/v8-poc/src/lib.rs @@ -153,21 +153,27 @@ mod tests { let expression = format!("new Uint8Array({length}).fill(90)"); let value = evaluate_script(scope, &expression); let view = v8::Local::::try_from(value).unwrap(); - let on_heap = - v8::TYPED_ARRAY_MAX_SIZE_IN_HEAP != 0 && length <= v8::TYPED_ARRAY_MAX_SIZE_IN_HEAP; + let on_heap = match v8::TYPED_ARRAY_MAX_SIZE_IN_HEAP { + 0 => false, + max_size => length <= max_size, + }; + let had_buffer = view.has_buffer(); // Check native placement before asking C++ to copy into storage: // stale size-zero bindings must fail here rather than abort in FFI. - assert_eq!(view.has_buffer(), !on_heap, "byte length {length}"); + // Empty arrays may use a native empty representation in either build. + if length > 0 { + assert_eq!(had_buffer, !on_heap, "byte length {length}"); + } let mut storage = vec![0; v8::TYPED_ARRAY_MAX_SIZE_IN_HEAP]; let storage_ptr = storage.as_ptr(); let contents = view.get_contents(&mut storage); assert_eq!(contents, vec![90; length], "byte length {length}"); - if on_heap { + if on_heap && length > 0 { assert_eq!(contents.as_ptr(), storage_ptr); } // Reading inline contents copies bytes without promoting the view. - assert_eq!(view.has_buffer(), !on_heap, "byte length {length}"); + assert_eq!(view.has_buffer(), had_buffer, "byte length {length}"); } } diff --git a/docs/codefx-installer.md b/docs/codefx-installer.md index f0f00ce52622..6a7f303c772e 100644 --- a/docs/codefx-installer.md +++ b/docs/codefx-installer.md @@ -1,6 +1,6 @@ # Codefx 安装与升级 -安装脚本在 Linux、macOS 和 Windows 上提供同一套安全切换流程,支持各系统的 x86_64 和 ARM64 架构。Linux 使用 musl 安装包;macOS 自动识别 Apple Silicon,包括 Rosetta 终端;Windows 使用原生 PowerShell 脚本。 +当前开发、CI 和新版本发布仅支持 Linux amd64(x86_64),使用 musl 安装包。安装脚本保留历史发布的跨平台兼容逻辑,下文中的 macOS、Windows 和 ARM64 说明仅用于维护已有安装。 安装包是否可用,以对应 Release 的附件和本平台 `.sha256` 文件(或旧版 `codex-package_SHA256SUMS`)为准。缺少本机安装包或校验记录时,安装会退出并保留原版本。32 位系统不受支持。 diff --git a/docs/config.md b/docs/config.md index d35b0a87e3c2..ce31f5b5dcc2 100644 --- a/docs/config.md +++ b/docs/config.md @@ -6,6 +6,29 @@ For advanced configuration instructions, see [this documentation](https://develo For a full configuration reference, see [this documentation](https://developers.openai.com/codex/config-reference). +## Codefx account integrations + +Codefx defaults to `apps = false`, `remote_plugin = false`, and +`plugin_sharing = false` under `[features]`. Each integration requires an explicit +setting to enable its interactive operations. + +Signing in to an OpenAI account does not synchronize plugins or skills. Startup, +discovery, plugin listing, and account changes do not install, replace, remove, or +upgrade local plugin bundles or skills. This applies even when all three features +are enabled. The `plugin/reconcile` compatibility endpoint returns an empty result +without fetching account state or changing local files. + +Install, remove, and upgrade plugins through explicit plugin commands or actions. +Configured local plugins and skills remain available without remote account sync. + +## OpenAI retry and timeout settings + +The built-in OpenAI provider honors explicit `request_max_retries`, +`stream_max_retries`, `stream_idle_timeout_ms`, and `websocket_connect_timeout_ms` +under `[model_providers.openai]`, including zero retries. Unspecified values use +Codefx's defaults. OpenAI routing and authentication use the built-in provider +settings. + ## Lifecycle hooks Admins can set top-level `allow_managed_hooks_only = true` in diff --git a/scripts/format.py b/scripts/format.py old mode 100644 new mode 100755 index cc1e96bee8ae..3edcaa9d3ec2 --- a/scripts/format.py +++ b/scripts/format.py @@ -58,9 +58,12 @@ def rust_formatter_group(*, check: bool) -> FormatterGroup: rust_files = sorted( os.path.relpath(REPO_ROOT / os.fsdecode(encoded_path), rust_workspace) for encoded_path in repository_files - if encoded_path and (REPO_ROOT / os.fsdecode(encoded_path)).is_file() + if encoded_path + and not os.fsdecode(encoded_path).startswith("vendor/") + and (REPO_ROOT / os.fsdecode(encoded_path)).is_file() ) # Git supplies every source file, including files Cargo cannot discover. + # Third-party vendor files retain upstream formatting. # Do not recursively format child modules again or include ignored files. args = [ "rustfmt", diff --git a/scripts/install/prepare_sdk_package.py b/scripts/install/prepare_sdk_package.py new file mode 100644 index 000000000000..14694b005100 --- /dev/null +++ b/scripts/install/prepare_sdk_package.py @@ -0,0 +1,67 @@ +"""Verify candidate provenance before using a same-run native package in SDK CI.""" + +import argparse +import hashlib +import json +import os +from pathlib import Path +import subprocess +import tarfile +import tomllib + + +def validate(metadata, source, target, version, digest): + expected = { + "source_commit": source, + "target": target, + "version": version, + "archive_sha256": digest, + } + if metadata != expected: + raise ValueError("SDK package provenance does not match this candidate") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--directory", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + target = "x86_64-unknown-linux-musl" + source = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip() + version = tomllib.loads(Path("codex-rs/Cargo.toml").read_text())["workspace"][ + "package" + ]["version"] + archive = args.directory / f"codex-package-{target}.tar.gz" + with archive.open("rb") as stream: + digest = hashlib.file_digest(stream, "sha256").hexdigest() + metadata = json.loads((args.directory / f"codefx-build-{target}.json").read_text()) + validate(metadata, source, target, version, digest) + args.output.mkdir(parents=True, exist_ok=False) + with tarfile.open(archive) as package: + for member in package: + if not (member.isfile() or member.isdir()): + raise ValueError(f"Unexpected package member: {member.name}") + if ( + member.name.startswith("/") + or ".." in Path(member.name).parts + or "\\" in member.name + ): + raise ValueError(f"Unsafe package member: {member.name}") + package.extractall(args.output, filter="data") + package_metadata = json.loads((args.output / "codex-package.json").read_text()) + if package_metadata["target"] != target or package_metadata["version"] != version: + raise ValueError("SDK package target/version mismatch") + for name in ("codex", "codex-code-mode-host", "codex-exec-server"): + binary = args.output / "bin" / name + with binary.open("rb") as stream: + header = stream.read(20) + if header[:5] != b"\x7fELF\x02" or header[18:20] != b"\x3e\x00": + raise ValueError(f"Expected native x86_64 ELF binary: {name}") + binary.chmod(0o755) + with open(os.environ["GITHUB_ENV"], "a") as environment: + environment.write(f"CODEX_EXEC_PATH={args.output.resolve()}/bin/codex\n") + print(f"SDK uses verified candidate {source}: {digest}") + + +if __name__ == "__main__": + main() diff --git a/scripts/install/smoke_source_package.py b/scripts/install/smoke_source_package.py new file mode 100644 index 000000000000..280014129a76 --- /dev/null +++ b/scripts/install/smoke_source_package.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python3 +"""Install and run a native package built from the current CI revision. + +The installer fixture redirects downloads to the newly built archive. Neither +the archive nor the executables are fixtures; no published release is reused. +""" + +import argparse +import hashlib +import json +import os +from pathlib import Path +import subprocess +import tempfile +import tomllib + +from release_package import verify +from test_install_sh import run_installer_in + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--directory", type=Path, required=True) + parser.add_argument("--target", required=True) + args = parser.parse_args() + version = tomllib.loads(Path("codex-rs/Cargo.toml").read_text())["workspace"][ + "package" + ]["version"] + archive = args.directory / f"codex-package-{args.target}.tar.gz" + verify(archive, args.target, version) + checksum = args.directory / "codex-package_SHA256SUMS" + with archive.open("rb") as archive_file: + archive_digest = hashlib.file_digest(archive_file, "sha256").hexdigest() + checksum.write_text(f"{archive_digest} {archive.name}\n") + metadata = json.dumps( + { + "tag_name": f"rust-v{version}", + "assets": [ + {"name": archive.name, "digest": f"sha256:{archive_digest}"}, + { + "name": checksum.name, + "digest": "sha256:" + + hashlib.sha256(checksum.read_bytes()).hexdigest(), + }, + ], + } + ) + source = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip() + (args.directory / f"codefx-build-{args.target}.json").write_text( + json.dumps( + { + "source_commit": source, + "target": args.target, + "version": version, + "archive_sha256": archive_digest, + }, + indent=2, + ) + + "\n" + ) + with tempfile.TemporaryDirectory(prefix="codefx native install ") as temp: + root = Path(temp) + for replacement in (True, False): + result, requests = run_installer_in( + root, + version, + archive_path=archive.resolve(), + checksum_path=checksum.resolve(), + metadata_json=metadata, + replacement_wrapper=replacement, + ) + if result.returncode: + raise RuntimeError(result.stdout + result.stderr) + if replacement and not any(archive.name in url for url in requests): + raise RuntimeError("Installer did not fetch the current source archive") + binary = root / "install-bin/codex" + output = subprocess.check_output([str(binary), "--version"], text=True) + if output.strip() != f"codefx {version}": + raise RuntimeError(f"Unexpected installed version: {output}") + env = os.environ | {"CODEX_HOME": str(root / "codex-home")} + subprocess.run( + [str(binary), "app-server", "daemon", "update", "--help"], + env=env, + check=True, + timeout=30, + ) + standalone = root / "codex-home/packages/standalone" + if (standalone / ".transaction").exists(): + raise RuntimeError("Installer left an unfinished transaction") + print(f"Current source {source}: {args.target} package and installation verified") + + +if __name__ == "__main__": + main() diff --git a/scripts/install/test_install_sh.py b/scripts/install/test_install_sh.py index 14b8682d5f7d..d8f8d781606d 100644 --- a/scripts/install/test_install_sh.py +++ b/scripts/install/test_install_sh.py @@ -614,7 +614,7 @@ def test_standalone_retains_previous_and_running_releases_across_installs( self.assertEqual(first.returncode, 0, first.stderr) oldest = releases / f"{versions[0]}-{target}" helper = oldest / "bin/codex-code-mode-host" - shutil.copy("/bin/sleep", helper) + shutil.copy("/bin/sh", helper) if system.sysname == "Darwin": # A copied macOS system binary cannot run with its platform signature. subprocess.run( @@ -623,7 +623,12 @@ def test_standalone_retains_previous_and_running_releases_across_installs( capture_output=True, ) # A helper can outlive its parent CLI; retain its whole release. - with subprocess.Popen([str(helper), "300"]) as running: + # Renamed multicall /bin/sleep binaries can reject the helper name. + # A shell blocked in its read builtin keeps the old release's real + # executable mapped without spawning a child or relying on argv[0]. + with subprocess.Popen( + [str(helper), "-c", "read -r _"], stdin=subprocess.PIPE + ) as running: try: second, _ = run_installer_in( root, versions[1], **install_options[versions[1]] @@ -738,11 +743,14 @@ def test_standalone_retains_previous_and_running_releases_across_installs( readable, "installer did not attempt retirement" ) self.assertEqual(os.read(ready_fd, 128), b"ready\n") - with subprocess.Popen([str(helper), "300"]) as late_helper: + with subprocess.Popen( + [str(helper), "-c", "read -r _"], stdin=subprocess.PIPE + ) as late_helper: try: os.write(resume_fd, b"continue\n") raced, _ = installing.result(timeout=30) self.assertEqual(raced.returncode, 0, raced.stderr) + self.assertIsNone(late_helper.poll()) self.assertTrue(oldest.is_dir(), raced.stderr) self.assertEqual(history.read_bytes(), recorded) finally: diff --git a/scripts/install/test_prepare_sdk_package.py b/scripts/install/test_prepare_sdk_package.py new file mode 100644 index 000000000000..9ee1c81947d5 --- /dev/null +++ b/scripts/install/test_prepare_sdk_package.py @@ -0,0 +1,24 @@ +"""Reject stale candidates and changed artifacts before executing SDK binaries.""" + +import unittest + +from prepare_sdk_package import validate + + +class CandidateProvenance(unittest.TestCase): + def test_only_exact_source_target_version_and_digest_are_accepted(self): + metadata = { + "source_commit": "a" * 40, + "target": "x86_64-unknown-linux-musl", + "version": "0.166.0", + "archive_sha256": "b" * 64, + } + args = tuple(metadata.values()) + validate(metadata, *args) + for key in metadata: + with self.subTest(field=key), self.assertRaises(ValueError): + validate(metadata | {key: "different"}, *args) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/list-bazel-release-targets.sh b/scripts/list-bazel-release-targets.sh old mode 100644 new mode 100755 diff --git a/sdk/typescript/src/exec.ts b/sdk/typescript/src/exec.ts index e1735d2c764f..56f6d8ace47f 100644 --- a/sdk/typescript/src/exec.ts +++ b/sdk/typescript/src/exec.ts @@ -255,7 +255,9 @@ export class CodexExec { } } finally { rl.close(); - child.removeAllListeners(); + // Keep the error guard and Node's internal exit listeners until the child + // exits. A caller can abort after consuming turn.failed but before exit; + // removing these listeners makes that late AbortError unhandled. try { if (!child.killed) child.kill(); } catch { diff --git a/sdk/typescript/tests/exec.test.ts b/sdk/typescript/tests/exec.test.ts index 5c3c50bf9926..64ba9e77fd98 100644 --- a/sdk/typescript/tests/exec.test.ts +++ b/sdk/typescript/tests/exec.test.ts @@ -73,6 +73,31 @@ describe("CodexExec", () => { } }); + it("handles a late abort after the consumer stops reading", async () => { + const { CodexExec } = await import("../src/exec"); + const child = new FakeChildProcess(); + spawnMock.mockReturnValue(child as unknown as child_process.ChildProcess); + const controller = new AbortController(); + const exitListener = jest.fn(); + child.once("exit", exitListener); + controller.signal.addEventListener("abort", () => { + child.emit("error", new Error("late abort")); + }); + setImmediate(() => child.stdout.write('{"type":"turn.failed"}\n')); + + const exec = new CodexExec("codex"); + for await (const _ of exec.run({ input: "hi", signal: controller.signal })) { + break; + } + + expect(child.killed).toBe(true); + expect(() => controller.abort()).not.toThrow(); + child.emit("exit", null, "SIGTERM"); + expect(exitListener).toHaveBeenCalledWith(null, "SIGTERM"); + child.stdout.end(); + child.stderr.end(); + }); + it("places resume args before image args", async () => { const { CodexExec } = await import("../src/exec"); spawnMock.mockClear(); diff --git a/sdk/typescript/tests/run.test.ts b/sdk/typescript/tests/run.test.ts index 34a2742d1db7..c8979ae4b873 100644 --- a/sdk/typescript/tests/run.test.ts +++ b/sdk/typescript/tests/run.test.ts @@ -12,7 +12,6 @@ import { sse, responseFailed, startResponsesTestProxy, - SseResponseBody, } from "./responsesProxy"; import { createMockClient, createTestClient } from "./testCodex"; @@ -846,25 +845,32 @@ describe("Codex", () => { } }); it("throws ThreadRunError on turn failures", async () => { - const { url, close } = await startResponsesTestProxy({ + const { url, close, requests } = await startResponsesTestProxy({ statusCode: 200, - responseBodies: (function* (): Generator { - yield sse(responseStarted("response_1")); - while (true) { - yield sse(responseFailed("rate limit exceeded")); - } - })(), + responseBodies: [sse(responseStarted("response_1"), responseFailed("rate limit exceeded"))], }); - const { client, cleanup } = createMockClient(url); + // This checks error propagation. Retry timing is covered by the Rust retry tests. + const { client, cleanup } = createMockClient(url, { + request_max_retries: 0, + stream_max_retries: 0, + }); + const controller = new AbortController(); + const deadline = setTimeout(() => controller.abort("SDK failure test deadline"), 5000); + let run: Promise | undefined; try { const thread = client.startThread(); - await expect(thread.run("fail")).rejects.toThrow("stream disconnected before completion:"); + run = thread.run("fail", { signal: controller.signal }); + await expect(run).rejects.toThrow("rate limit exceeded"); + expect(requests).toHaveLength(1); } finally { + clearTimeout(deadline); + controller.abort(); + await run?.catch(() => {}); cleanup(); await close(); } - }, 10000); // TODO(pakrym): remove timeout + }, 10000); }); /** diff --git a/sdk/typescript/tests/testCodex.ts b/sdk/typescript/tests/testCodex.ts index 5d7b1bc4a436..1f1eb5536088 100644 --- a/sdk/typescript/tests/testCodex.ts +++ b/sdk/typescript/tests/testCodex.ts @@ -21,7 +21,10 @@ export type TestClient = { client: Codex; }; -export function createMockClient(url: string): TestClient { +export function createMockClient( + url: string, + providerOverrides: CodexConfigObject = {}, +): TestClient { return createTestClient({ config: { model_provider: "mock", @@ -31,6 +34,7 @@ export function createMockClient(url: string): TestClient { base_url: url, wire_api: "responses", supports_websockets: false, + ...providerOverrides, }, }, }, diff --git a/third_party/v8/BUILD.bazel b/third_party/v8/BUILD.bazel index 908e9a3edff8..a901f0d9e323 100644 --- a/third_party/v8/BUILD.bazel +++ b/third_party/v8/BUILD.bazel @@ -782,6 +782,25 @@ v8_artifact_files( v8_cpu = "x64", ) +# Cargo can reuse a verified published archive, but its generated binding must +# use the same Unix inline TypedArray policy as the compiled native library. +[ + v8_artifact_files( + name = "rusty_v8_sandbox_binding_%s_unknown_linux_%s" % (arch, libc), + srcs = [":binding_generated_152_2_0"], + profile = "sandbox_release", + v8_cpu = cpu, + ) + for arch, cpu in [ + ("x86_64", "x64"), + ("aarch64", "arm64"), + ] + for libc in [ + "gnu", + "musl", + ] +] + v8_artifact_files( name = "rusty_v8_sandbox_release_pair_aarch64_unknown_linux_gnu", srcs = [ diff --git a/third_party/v8/README.md b/third_party/v8/README.md index 9b74a8d8a06c..0248e570a63f 100644 --- a/third_party/v8/README.md +++ b/third_party/v8/README.md @@ -142,6 +142,12 @@ bindings use that same threshold; never pair a native 64-byte threshold with GN's size-zero binding constant. These are fixed platform choices, not additional developer build switches. +Cargo CI verifies the published archive and its original manifest, then generates +the Linux sandbox binding from these pinned headers through +`rusty_v8_sandbox_binding_`. The generated input replaces the published +Unix size-zero binding for Cargo consumers. The runtime TypedArray regression +checks the threshold against the native archive before calling `get_contents`. + Use a native Visual Studio Developer PowerShell with the C++ tools and Windows SDK available. The SDK supplies headers, libraries, `dumpbin.exe`, and the assembler. From the repo root, build the archive for that host: diff --git a/vendor/sqlx-sqlite/.cargo_vcs_info.json b/vendor/sqlx-sqlite/.cargo_vcs_info.json new file mode 100644 index 000000000000..f133fd70dbc3 --- /dev/null +++ b/vendor/sqlx-sqlite/.cargo_vcs_info.json @@ -0,0 +1,6 @@ +{ + "git": { + "sha1": "003b698e99e024f3621b8043a2426fde5b741171" + }, + "path_in_vcs": "sqlx-sqlite" +} \ No newline at end of file diff --git a/vendor/sqlx-sqlite/Cargo.lock b/vendor/sqlx-sqlite/Cargo.lock new file mode 100644 index 000000000000..ab88efa7fef2 --- /dev/null +++ b/vendor/sqlx-sqlite/Cargo.lock @@ -0,0 +1,1365 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "atoi" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528" +dependencies = [ + "num-traits", +] + +[[package]] +name = "autocfg" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bindgen" +version = "0.72.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895" +dependencies = [ + "bitflags", + "cexpr", + "clang-sys", + "itertools", + "proc-macro2", + "quote", + "regex", + "rustc-hash", + "shlex", + "syn", +] + +[[package]] +name = "bitflags" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" + +[[package]] +name = "bytes" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" + +[[package]] +name = "cc" +version = "1.2.61" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d16d90359e986641506914ba71350897565610e87ce0ad9e6f28569db3dd5c6d" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "chrono" +version = "0.4.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c673075a2e0e5f4a1dde27ce9dee1ea4558c7ffe648f576438a20ca1d2acc4b0" +dependencies = [ + "iana-time-zone", + "num-traits", + "windows-link", +] + +[[package]] +name = "clang-sys" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4" +dependencies = [ + "glob", + "libc", + "libloading", +] + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crc" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d" +dependencies = [ + "crc-catalog", +] + +[[package]] +name = "crc-catalog" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" + +[[package]] +name = "crossbeam-queue" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f58bbc28f91df819d0aa2a2c00cd19754769c2fad90579b3592b1c9ba7a3115" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +dependencies = [ + "powerfmt", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "either" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" +dependencies = [ + "serde", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "event-listener" +version = "5.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab" +dependencies = [ + "concurrent-queue", + "parking", + "pin-project-lite", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + +[[package]] +name = "flume" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e139bc46ca777eb5efaf62df0ab8cc5fd400866427e56c68b22e414e53bd3be" +dependencies = [ + "futures-core", + "futures-sink", + "spin", +] + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" + +[[package]] +name = "futures-executor" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-intrusive" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f" +dependencies = [ + "futures-core", + "lock_api", + "parking_lot", +] + +[[package]] +name = "futures-io" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" + +[[package]] +name = "futures-sink" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" + +[[package]] +name = "futures-task" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" + +[[package]] +name = "futures-util" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +dependencies = [ + "futures-core", + "futures-io", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "glob" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f467dd6dccf739c208452f8014c75c18bb8301b050ad1cfb27153803edb0f51" + +[[package]] +name = "hashlink" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea0b22561a9c04a7cb1a302c013e0259cd3b4bb619f145b32f72b8b4bcbed230" +dependencies = [ + "hashbrown 0.16.1", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" + +[[package]] +name = "icu_properties" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" + +[[package]] +name = "icu_provider" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +dependencies = [ + "equivalent", + "hashbrown 0.17.0", +] + +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.97" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1840c94c045fbcf8ba2812c95db44499f7c64910a912551aaaa541decebcacf" +dependencies = [ + "cfg-if", + "futures-util", + "once_cell", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.186" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "libsqlite3-sys" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f111c8c41e7c61a49cd34e44c7619462967221a6443b0ec299e0ac30cfb9b1" +dependencies = [ + "bindgen", + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "litemap" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" + +[[package]] +name = "memchr" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "num-conv" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6673768db2d862beb9b39a78fdcb1a69439615d5794a1be50caa9bc92c81967" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" + +[[package]] +name = "potential_utf" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex" +version = "1.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" + +[[package]] +name = "rustc-hash" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe" + +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.149" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" + +[[package]] +name = "spin" +version = "0.9.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" +dependencies = [ + "lock_api", +] + +[[package]] +name = "sqlx-core" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05b44e85bf579a8eeb4ceaa77a3a523baf2bf0e9bac7e40f405d537b5d2d5ccb" +dependencies = [ + "base64", + "bytes", + "cfg-if", + "chrono", + "crc", + "crossbeam-queue", + "either", + "event-listener", + "futures-core", + "futures-intrusive", + "futures-io", + "futures-util", + "hashbrown 0.16.1", + "hashlink", + "indexmap", + "log", + "memchr", + "percent-encoding", + "serde", + "serde_json", + "sha2", + "smallvec", + "thiserror", + "time", + "toml", + "tracing", + "url", + "uuid", +] + +[[package]] +name = "sqlx-sqlite" +version = "0.9.0" +dependencies = [ + "atoi", + "chrono", + "flume", + "form_urlencoded", + "futures-channel", + "futures-core", + "futures-executor", + "futures-intrusive", + "futures-util", + "libsqlite3-sys", + "log", + "percent-encoding", + "regex", + "serde", + "sqlx-core", + "thiserror", + "time", + "tracing", + "url", + "uuid", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "syn" +version = "2.0.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "thiserror" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "time" +version = "0.3.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c" +dependencies = [ + "deranged", + "itoa", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca" + +[[package]] +name = "time-macros" +version = "0.2.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime", + "toml_edit", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime", + "toml_write", + "winnow", +] + +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "typenum" +version = "1.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40ce102ab67701b8526c123c1bab5cbe42d7040ccfd0f64af1a385808d2f43de" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "uuid" +version = "1.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd74a9687298c6858e9b88ec8935ec45d22e8fd5e6394fa1bd4e99a87789c76" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasm-bindgen" +version = "0.2.120" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df52b6d9b87e0c74c9edfa1eb2d9bf85e5d63515474513aa50fa181b3c4f5db1" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.120" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78b1041f495fb322e64aca85f5756b2172e35cd459376e67f2a6c9dffcedb103" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.120" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9dcd0ff20416988a18ac686d4d4d0f6aae9ebf08a389ff5d29012b05af2a1b41" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.120" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49757b3c82ebf16c57d69365a142940b384176c24df52a087fb748e2085359ea" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + +[[package]] +name = "writeable" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" + +[[package]] +name = "yoke" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69faa1f2a1ea75661980b013019ed6687ed0e83d069bc1114e2cc74c6c04c4df" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerotrie" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zmij" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" diff --git a/vendor/sqlx-sqlite/Cargo.toml b/vendor/sqlx-sqlite/Cargo.toml new file mode 100644 index 000000000000..0473ba4659ce --- /dev/null +++ b/vendor/sqlx-sqlite/Cargo.toml @@ -0,0 +1,198 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2021" +rust-version = "1.94.0" +name = "sqlx-sqlite" +version = "0.9.0" +authors = [ + "Ryan Leckey ", + "Austin Bonander ", + "Chloe Ross ", + "Daniel Akhterov ", +] +build = false +autolib = false +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "SQLite driver implementation for SQLx. Not for direct use; see the `sqlx` crate for details." +documentation = "https://docs.rs/sqlx" +readme = false +license = "MIT OR Apache-2.0" +repository = "https://github.com/launchbadge/sqlx" + +[package.metadata.docs.rs] +features = ["__unstable_docs"] + +[features] +_unstable-all-sqlite-features = [ + "deserialize", + "load-extension", + "preupdate-hook", + "unlock-notify", +] +_unstable-all-types = [ + "json", + "chrono", + "time", + "uuid", +] +_unstable-docs = [ + "bundled", + "any", + "_unstable-all-types", + "_unstable-all-sqlite-features", +] +any = ["sqlx-core/any"] +bigdecimal = [] +bundled = ["libsqlite3-sys/bundled"] +chrono = [ + "dep:chrono", + "sqlx-core/chrono", +] +deserialize = [] +json = [ + "sqlx-core/json", + "serde", +] +load-extension = [] +migrate = ["sqlx-core/migrate"] +offline = [ + "sqlx-core/offline", + "serde", +] +preupdate-hook = ["libsqlite3-sys/preupdate_hook"] +regexp = ["dep:regex"] +rust_decimal = [] +sqlx-toml = ["sqlx-core/sqlx-toml"] +time = [ + "dep:time", + "sqlx-core/time", +] +unbundled = ["libsqlite3-sys/buildtime_bindgen"] +unlock-notify = ["libsqlite3-sys/unlock_notify"] +uuid = [ + "dep:uuid", + "sqlx-core/uuid", +] + +[lib] +name = "sqlx_sqlite" +path = "src/lib.rs" + +[dependencies.atoi] +version = "2.0" + +[dependencies.chrono] +version = "0.4.34" +features = [ + "std", + "clock", +] +optional = true +default-features = false + +[dependencies.flume] +version = "0.12.0" +features = ["async"] +default-features = false + +[dependencies.form_urlencoded] +version = "1.2.2" + +[dependencies.futures-channel] +version = "0.3.32" +features = [ + "sink", + "alloc", + "std", +] +default-features = false + +[dependencies.futures-core] +version = "0.3.32" +default-features = false + +[dependencies.futures-executor] +version = "0.3.32" + +[dependencies.futures-intrusive] +version = "0.5.0" + +[dependencies.futures-util] +version = "0.3.32" +features = [ + "alloc", + "sink", +] +default-features = false + +[dependencies.libsqlite3-sys] +version = ">=0.30.1, <0.40.0" +features = [ + "pkg-config", + "vcpkg", +] +default-features = false + +[dependencies.log] +version = "0.4.18" + +[dependencies.percent-encoding] +version = "2.3.0" + +[dependencies.regex] +version = "1.6.0" +optional = true + +[dependencies.serde] +version = "1.0.219" +features = ["derive"] +optional = true + +[dependencies.sqlx-core] +version = "=0.9.0" + +[dependencies.thiserror] +version = "2.0.18" +features = ["std"] +default-features = false + +[dependencies.time] +version = "0.3.47" +features = [ + "formatting", + "parsing", + "macros", +] +optional = true + +[dependencies.tracing] +version = "0.1.37" +features = ["log"] + +[dependencies.url] +version = "2.2.2" + +[dependencies.uuid] +version = "1.12.1" +optional = true + +[dev-dependencies] + +[lints.clippy] +cast_possible_truncation = "deny" +cast_possible_wrap = "deny" +cast_sign_loss = "deny" +disallowed_methods = "deny" diff --git a/vendor/sqlx-sqlite/Cargo.toml.orig b/vendor/sqlx-sqlite/Cargo.toml.orig new file mode 100755 index 000000000000..ffac1b9d149a --- /dev/null +++ b/vendor/sqlx-sqlite/Cargo.toml.orig @@ -0,0 +1,108 @@ +[package] +name = "sqlx-sqlite" +documentation = "https://docs.rs/sqlx" +description = "SQLite driver implementation for SQLx. Not for direct use; see the `sqlx` crate for details." +version.workspace = true +license.workspace = true +edition.workspace = true +authors.workspace = true +repository.workspace = true +rust-version.workspace = true + +[features] +any = ["sqlx-core/any"] +json = ["sqlx-core/json", "serde"] +offline = ["sqlx-core/offline", "serde"] +migrate = ["sqlx-core/migrate"] + +# Type integrations +chrono = ["dep:chrono", "sqlx-core/chrono"] +time = ["dep:time", "sqlx-core/time"] +uuid = ["dep:uuid", "sqlx-core/uuid"] + +regexp = ["dep:regex"] + +# Conditionally compiled SQLite features +deserialize = [] +load-extension = [] +preupdate-hook = ["libsqlite3-sys/preupdate_hook"] +unlock-notify = ["libsqlite3-sys/unlock_notify"] + +bundled = ["libsqlite3-sys/bundled"] +unbundled = ["libsqlite3-sys/buildtime_bindgen"] + +sqlx-toml = ["sqlx-core/sqlx-toml"] + +# Note: currently unused, only to satisfy "unexpected `cfg` condition" lint +bigdecimal = [] +rust_decimal = [] + +_unstable-all-types = [ + "json", "chrono", "time", "uuid", +] + +_unstable-all-sqlite-features = [ + "deserialize", + "load-extension", + "preupdate-hook", + "unlock-notify", +] + +_unstable-docs = [ + "bundled", "any", + "_unstable-all-types", + "_unstable-all-sqlite-features" +] + +[dependencies.libsqlite3-sys] +# See `sqlx-sqlite/src/lib.rs` for details. +version = ">=0.30.1, <0.38.0" +default-features = false +features = [ + "pkg-config", + "vcpkg", +] + +[dependencies] +futures-core = { version = "0.3.32", default-features = false } +futures-channel = { version = "0.3.32", default-features = false, features = ["sink", "alloc", "std"] } +# used by the SQLite worker thread to block on the async mutex that locks the database handle +futures-executor = { version = "0.3.32" } +futures-intrusive = "0.5.0" +futures-util = { version = "0.3.32", default-features = false, features = ["alloc", "sink"] } + +chrono = { workspace = true, optional = true } +time = { workspace = true, optional = true } +uuid = { workspace = true, optional = true } + +url = { version = "2.2.2" } +percent-encoding = "2.3.0" +form_urlencoded = "1.2.2" + +flume = { version = "0.12.0", default-features = false, features = ["async"] } + +atoi = "2.0" + +log = "0.4.18" +tracing = { version = "0.1.37", features = ["log"] } + +thiserror.workspace = true + +serde = { version = "1.0.219", features = ["derive"], optional = true } +regex = { version = "1.6.0", optional = true } + +[dependencies.sqlx-core] +workspace = true + +[dev-dependencies.sqlx] +# FIXME: https://github.com/rust-lang/cargo/issues/15622 +# workspace = true +path = ".." +default-features = false +features = ["macros", "runtime-tokio", "tls-none", "sqlite"] + +[lints] +workspace = true + +[package.metadata.docs.rs] +features = ["__unstable_docs"] diff --git a/vendor/sqlx-sqlite/LICENSE-APACHE b/vendor/sqlx-sqlite/LICENSE-APACHE new file mode 100755 index 000000000000..965b606f331b --- /dev/null +++ b/vendor/sqlx-sqlite/LICENSE-APACHE @@ -0,0 +1 @@ +../LICENSE-APACHE \ No newline at end of file diff --git a/vendor/sqlx-sqlite/LICENSE-MIT b/vendor/sqlx-sqlite/LICENSE-MIT new file mode 100755 index 000000000000..76219eb72e85 --- /dev/null +++ b/vendor/sqlx-sqlite/LICENSE-MIT @@ -0,0 +1 @@ +../LICENSE-MIT \ No newline at end of file diff --git a/vendor/sqlx-sqlite/src/any.rs b/vendor/sqlx-sqlite/src/any.rs new file mode 100755 index 000000000000..b3a5af55430a --- /dev/null +++ b/vendor/sqlx-sqlite/src/any.rs @@ -0,0 +1,242 @@ +use crate::{ + Either, Sqlite, SqliteArgumentValue, SqliteArguments, SqliteColumn, SqliteConnectOptions, + SqliteConnection, SqliteQueryResult, SqliteRow, SqliteTransactionManager, SqliteTypeInfo, +}; +use futures_core::future::BoxFuture; +use futures_core::stream::BoxStream; +use futures_util::{FutureExt, StreamExt, TryFutureExt, TryStreamExt}; + +use sqlx_core::any::{ + AnyArguments, AnyColumn, AnyConnectOptions, AnyConnectionBackend, AnyQueryResult, AnyRow, + AnyStatement, AnyTypeInfo, AnyTypeInfoKind, AnyValueKind, +}; +use sqlx_core::sql_str::SqlStr; + +use crate::arguments::SqliteArgumentsBuffer; +use crate::type_info::DataType; +use sqlx_core::connection::{ConnectOptions, Connection}; +use sqlx_core::database::Database; +use sqlx_core::executor::Executor; +use sqlx_core::transaction::TransactionManager; +use std::pin::pin; +use std::sync::Arc; + +sqlx_core::declare_driver_with_optional_migrate!(DRIVER = Sqlite); + +impl AnyConnectionBackend for SqliteConnection { + fn name(&self) -> &str { + ::NAME + } + + fn close(self: Box) -> BoxFuture<'static, sqlx_core::Result<()>> { + Connection::close(*self).boxed() + } + + fn close_hard(self: Box) -> BoxFuture<'static, sqlx_core::Result<()>> { + Connection::close_hard(*self).boxed() + } + + fn ping(&mut self) -> BoxFuture<'_, sqlx_core::Result<()>> { + Connection::ping(self).boxed() + } + + fn begin(&mut self, statement: Option) -> BoxFuture<'_, sqlx_core::Result<()>> { + SqliteTransactionManager::begin(self, statement).boxed() + } + + fn commit(&mut self) -> BoxFuture<'_, sqlx_core::Result<()>> { + SqliteTransactionManager::commit(self).boxed() + } + + fn rollback(&mut self) -> BoxFuture<'_, sqlx_core::Result<()>> { + SqliteTransactionManager::rollback(self).boxed() + } + + fn start_rollback(&mut self) { + SqliteTransactionManager::start_rollback(self) + } + + fn get_transaction_depth(&self) -> usize { + SqliteTransactionManager::get_transaction_depth(self) + } + + fn shrink_buffers(&mut self) { + // NO-OP. + } + + fn flush(&mut self) -> BoxFuture<'_, sqlx_core::Result<()>> { + Connection::flush(self).boxed() + } + + fn should_flush(&self) -> bool { + Connection::should_flush(self) + } + + #[cfg(feature = "migrate")] + fn as_migrate( + &mut self, + ) -> sqlx_core::Result<&mut (dyn sqlx_core::migrate::Migrate + Send + 'static)> { + Ok(self) + } + + fn fetch_many( + &mut self, + query: SqlStr, + persistent: bool, + arguments: Option, + ) -> BoxStream<'_, sqlx_core::Result>> { + let persistent = persistent && arguments.is_some(); + let args = arguments.map(map_arguments); + + Box::pin( + self.worker + .execute(query, args, self.row_channel_size, persistent, None) + .map_ok(flume::Receiver::into_stream) + .try_flatten_stream() + .map( + move |res: sqlx_core::Result>| match res? { + Either::Left(result) => Ok(Either::Left(map_result(result))), + Either::Right(row) => Ok(Either::Right(AnyRow::try_from(&row)?)), + }, + ), + ) + } + + fn fetch_optional( + &mut self, + query: SqlStr, + persistent: bool, + arguments: Option, + ) -> BoxFuture<'_, sqlx_core::Result>> { + let persistent = persistent && arguments.is_some(); + let args = arguments.map(map_arguments); + + Box::pin(async move { + let mut stream = pin!( + self.worker + .execute(query, args, self.row_channel_size, persistent, Some(1)) + .map_ok(flume::Receiver::into_stream) + .await? + ); + + if let Some(Either::Right(row)) = stream.try_next().await? { + return Ok(Some(AnyRow::try_from(&row)?)); + } + + Ok(None) + }) + } + + fn prepare_with<'c, 'q: 'c>( + &'c mut self, + sql: SqlStr, + _parameters: &[AnyTypeInfo], + ) -> BoxFuture<'c, sqlx_core::Result> { + Box::pin(async move { + let statement = Executor::prepare_with(self, sql, &[]).await?; + let column_names = statement.column_names.clone(); + AnyStatement::try_from_statement(statement, column_names) + }) + } + + #[cfg(feature = "offline")] + fn describe( + &mut self, + sql: SqlStr, + ) -> BoxFuture<'_, sqlx_core::Result>> { + Box::pin(async move { Executor::describe(self, sql).await?.try_into_any() }) + } +} + +impl<'a> TryFrom<&'a SqliteTypeInfo> for AnyTypeInfo { + type Error = sqlx_core::Error; + + fn try_from(sqlite_type: &'a SqliteTypeInfo) -> Result { + Ok(AnyTypeInfo { + kind: match &sqlite_type.0 { + DataType::Null => AnyTypeInfoKind::Null, + DataType::Int4 => AnyTypeInfoKind::Integer, + DataType::Integer => AnyTypeInfoKind::BigInt, + DataType::Float => AnyTypeInfoKind::Double, + DataType::Blob => AnyTypeInfoKind::Blob, + DataType::Text => AnyTypeInfoKind::Text, + _ => { + return Err(sqlx_core::Error::AnyDriverError( + format!("Any driver does not support the SQLite type {sqlite_type:?}") + .into(), + )) + } + }, + }) + } +} + +impl<'a> TryFrom<&'a SqliteColumn> for AnyColumn { + type Error = sqlx_core::Error; + + fn try_from(col: &'a SqliteColumn) -> Result { + let type_info = + AnyTypeInfo::try_from(&col.type_info).map_err(|e| sqlx_core::Error::ColumnDecode { + index: col.name.to_string(), + source: e.into(), + })?; + + Ok(AnyColumn { + ordinal: col.ordinal, + name: col.name.clone(), + type_info, + }) + } +} + +impl<'a> TryFrom<&'a SqliteRow> for AnyRow { + type Error = sqlx_core::Error; + + fn try_from(row: &'a SqliteRow) -> Result { + AnyRow::map_from(row, row.column_names.clone()) + } +} + +impl<'a> TryFrom<&'a AnyConnectOptions> for SqliteConnectOptions { + type Error = sqlx_core::Error; + + fn try_from(opts: &'a AnyConnectOptions) -> Result { + let mut opts_out = SqliteConnectOptions::from_url(&opts.database_url)?; + opts_out.log_settings = opts.log_settings.clone(); + + Ok(opts_out) + } +} + +// Infallible alternative to AnyArguments::convert_into() +fn map_arguments(args: AnyArguments) -> SqliteArguments { + let values = args + .values + .0 + .into_iter() + .map(|val| match val { + AnyValueKind::Null(_) => SqliteArgumentValue::Null, + AnyValueKind::Bool(b) => SqliteArgumentValue::Int(b as i32), + AnyValueKind::SmallInt(i) => SqliteArgumentValue::Int(i as i32), + AnyValueKind::Integer(i) => SqliteArgumentValue::Int(i), + AnyValueKind::BigInt(i) => SqliteArgumentValue::Int64(i), + AnyValueKind::Real(r) => SqliteArgumentValue::Double(r as f64), + AnyValueKind::Double(d) => SqliteArgumentValue::Double(d), + AnyValueKind::Text(t) => SqliteArgumentValue::Text(Arc::new(t.to_string())), + AnyValueKind::Blob(b) => SqliteArgumentValue::Blob(Arc::new(b.to_vec())), + // AnyValueKind is `#[non_exhaustive]` but we should have covered everything + _ => unreachable!("BUG: missing mapping for {val:?}"), + }) + .collect(); + + SqliteArguments { + values: SqliteArgumentsBuffer::new(values), + } +} + +fn map_result(res: SqliteQueryResult) -> AnyQueryResult { + AnyQueryResult { + rows_affected: res.rows_affected(), + last_insert_id: None, + } +} diff --git a/vendor/sqlx-sqlite/src/arguments.rs b/vendor/sqlx-sqlite/src/arguments.rs new file mode 100755 index 000000000000..4fd7da506749 --- /dev/null +++ b/vendor/sqlx-sqlite/src/arguments.rs @@ -0,0 +1,148 @@ +use crate::encode::{Encode, IsNull}; +use crate::error::Error; +use crate::statement::StatementHandle; +use crate::Sqlite; +use atoi::atoi; +use libsqlite3_sys::SQLITE_OK; +use std::sync::Arc; + +pub(crate) use sqlx_core::arguments::*; +use sqlx_core::error::BoxDynError; + +#[derive(Debug, Clone)] +pub enum SqliteArgumentValue { + Null, + Text(Arc), + TextSlice(Arc), + Blob(Arc>), + Double(f64), + Int(i32), + Int64(i64), +} + +#[derive(Default, Debug, Clone)] +pub struct SqliteArguments { + pub(crate) values: SqliteArgumentsBuffer, +} + +#[derive(Default, Debug, Clone)] +pub struct SqliteArgumentsBuffer(Vec); + +impl SqliteArguments { + pub(crate) fn add<'t, T>(&mut self, value: T) -> Result<(), BoxDynError> + where + T: Encode<'t, Sqlite>, + { + let value_length_before_encoding = self.values.0.len(); + + match value.encode(&mut self.values) { + Ok(IsNull::Yes) => self.values.0.push(SqliteArgumentValue::Null), + Ok(IsNull::No) => {} + Err(error) => { + // reset the value buffer to its previous value if encoding failed so we don't leave a half-encoded value behind + self.values.0.truncate(value_length_before_encoding); + return Err(error); + } + }; + + Ok(()) + } +} + +impl Arguments for SqliteArguments { + type Database = Sqlite; + + fn reserve(&mut self, len: usize, _size_hint: usize) { + self.values.0.reserve(len); + } + + fn add<'t, T>(&mut self, value: T) -> Result<(), BoxDynError> + where + T: Encode<'t, Self::Database>, + { + self.add(value) + } + + fn len(&self) -> usize { + self.values.0.len() + } +} + +impl SqliteArguments { + pub(super) fn bind(&self, handle: &mut StatementHandle, offset: usize) -> Result { + let mut arg_i = offset; + // for handle in &statement.handles { + + let cnt = handle.bind_parameter_count(); + + for param_i in 1..=cnt { + // figure out the index of this bind parameter into our argument tuple + let n: usize = if let Some(name) = handle.bind_parameter_name(param_i) { + if let Some(name) = name.strip_prefix('?') { + // parameter should have the form ?NNN + atoi(name.as_bytes()).expect("parameter of the form ?NNN") + } else if let Some(name) = name.strip_prefix('$') { + // parameter should have the form $NNN + atoi(name.as_bytes()).ok_or_else(|| { + err_protocol!( + "parameters with non-integer names are not currently supported: {}", + name + ) + })? + } else { + return Err(err_protocol!("unsupported SQL parameter format: {}", name)); + } + } else { + arg_i += 1; + arg_i + }; + + if n > self.values.0.len() { + // SQLite treats unbound variables as NULL + // we reproduce this here + // If you are reading this and think this should be an error, open an issue and we can + // discuss configuring this somehow + // Note that the query macros have a different way of enforcing + // argument arity + break; + } + + self.values.0[n - 1].bind(handle, param_i)?; + } + + Ok(arg_i - offset) + } +} + +impl SqliteArgumentsBuffer { + #[allow(dead_code)] // clippy incorrectly reports this as unused + pub(crate) fn new(values: Vec) -> SqliteArgumentsBuffer { + Self(values) + } + + pub(crate) fn push(&mut self, value: SqliteArgumentValue) { + self.0.push(value); + } +} + +impl SqliteArgumentValue { + fn bind(&self, handle: &mut StatementHandle, i: usize) -> Result<(), Error> { + use SqliteArgumentValue::*; + + let status = match self { + Text(v) => handle.bind_text(i, v), + TextSlice(v) => handle.bind_text(i, v), + Blob(v) => handle.bind_blob(i, v), + Int(v) => handle.bind_int(i, *v), + Int64(v) => handle.bind_int64(i, *v), + Double(v) => handle.bind_double(i, *v), + Null => handle.bind_null(i), + }; + + if status != SQLITE_OK { + return Err(handle.last_error().into()); + } + + Ok(()) + } +} diff --git a/vendor/sqlx-sqlite/src/column.rs b/vendor/sqlx-sqlite/src/column.rs new file mode 100755 index 000000000000..d319bd46a890 --- /dev/null +++ b/vendor/sqlx-sqlite/src/column.rs @@ -0,0 +1,35 @@ +use crate::ext::ustr::UStr; +use crate::{Sqlite, SqliteTypeInfo}; + +pub(crate) use sqlx_core::column::*; + +#[derive(Debug, Clone)] +#[cfg_attr(feature = "offline", derive(serde::Serialize, serde::Deserialize))] +pub struct SqliteColumn { + pub(crate) name: UStr, + pub(crate) ordinal: usize, + pub(crate) type_info: SqliteTypeInfo, + + #[cfg_attr(feature = "offline", serde(default))] + pub(crate) origin: ColumnOrigin, +} + +impl Column for SqliteColumn { + type Database = Sqlite; + + fn ordinal(&self) -> usize { + self.ordinal + } + + fn name(&self) -> &str { + &self.name + } + + fn type_info(&self) -> &SqliteTypeInfo { + &self.type_info + } + + fn origin(&self) -> ColumnOrigin { + self.origin.clone() + } +} diff --git a/vendor/sqlx-sqlite/src/connection/collation.rs b/vendor/sqlx-sqlite/src/connection/collation.rs new file mode 100755 index 000000000000..229e780adfbd --- /dev/null +++ b/vendor/sqlx-sqlite/src/connection/collation.rs @@ -0,0 +1,158 @@ +use std::cmp::Ordering; +use std::ffi::CString; +use std::fmt::{self, Debug, Formatter}; +use std::os::raw::{c_int, c_void}; +use std::slice; +use std::sync::Arc; + +use libsqlite3_sys::{sqlite3_create_collation_v2, SQLITE_OK, SQLITE_UTF8}; + +use crate::connection::handle::ConnectionHandle; +use crate::error::Error; + +#[derive(Clone)] +pub struct Collation { + name: Arc, + #[allow(clippy::type_complexity)] + collate: Arc Ordering + Send + Sync + 'static>, + // SAFETY: these must match the concrete type of `collate` + call: unsafe extern "C" fn( + arg1: *mut c_void, + arg2: c_int, + arg3: *const c_void, + arg4: c_int, + arg5: *const c_void, + ) -> c_int, + free: unsafe extern "C" fn(*mut c_void), +} + +impl Collation { + pub fn new(name: N, collate: F) -> Self + where + N: Into>, + F: Fn(&str, &str) -> Ordering + Send + Sync + 'static, + { + unsafe extern "C" fn drop_arc_value(p: *mut c_void) { + drop(Arc::from_raw(p as *mut T)); + } + + Collation { + name: name.into(), + collate: Arc::new(collate), + call: call_boxed_closure::, + free: drop_arc_value::, + } + } + + pub(crate) fn create(&self, handle: &mut ConnectionHandle) -> Result<(), Error> { + let raw_f = Arc::into_raw(Arc::clone(&self.collate)); + let c_name = CString::new(&*self.name) + .map_err(|_| err_protocol!("invalid collation name: {:?}", self.name))?; + let flags = SQLITE_UTF8; + let r = unsafe { + sqlite3_create_collation_v2( + handle.as_ptr(), + c_name.as_ptr(), + flags, + raw_f as *mut c_void, + Some(self.call), + Some(self.free), + ) + }; + + if r == SQLITE_OK { + Ok(()) + } else { + // The xDestroy callback is not called if the sqlite3_create_collation_v2() function fails. + drop(unsafe { Arc::from_raw(raw_f) }); + Err(handle.expect_error().into()) + } + } +} + +impl Debug for Collation { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.debug_struct("Collation") + .field("name", &self.name) + .finish_non_exhaustive() + } +} + +pub(crate) fn create_collation( + handle: &mut ConnectionHandle, + name: &str, + compare: F, +) -> Result<(), Error> +where + F: Fn(&str, &str) -> Ordering + Send + Sync + 'static, +{ + unsafe extern "C" fn free_boxed_value(p: *mut c_void) { + drop(Box::from_raw(p as *mut T)); + } + + let boxed_f: *mut F = Box::into_raw(Box::new(compare)); + let c_name = + CString::new(name).map_err(|_| err_protocol!("invalid collation name: {}", name))?; + let flags = SQLITE_UTF8; + let r = unsafe { + sqlite3_create_collation_v2( + handle.as_ptr(), + c_name.as_ptr(), + flags, + boxed_f as *mut c_void, + Some(call_boxed_closure::), + Some(free_boxed_value::), + ) + }; + + if r == SQLITE_OK { + Ok(()) + } else { + // The xDestroy callback is not called if the sqlite3_create_collation_v2() function fails. + drop(unsafe { Box::from_raw(boxed_f) }); + Err(handle.expect_error().into()) + } +} + +unsafe extern "C" fn call_boxed_closure( + data: *mut c_void, + left_len: c_int, + left_ptr: *const c_void, + right_len: c_int, + right_ptr: *const c_void, +) -> c_int +where + C: Fn(&str, &str) -> Ordering, +{ + let boxed_f: *mut C = data as *mut C; + + // Note: unwinding is now caught at the FFI boundary: + // https://doc.rust-lang.org/nomicon/ffi.html#ffi-and-unwinding + assert!(!boxed_f.is_null()); + + let left_len = + usize::try_from(left_len).unwrap_or_else(|_| panic!("left_len out of range: {left_len}")); + + let right_len = usize::try_from(right_len) + .unwrap_or_else(|_| panic!("right_len out of range: {right_len}")); + + // SQLite explicitly documents that invalid UTF-8 may be passed into + // application-defined collating sequences. The safe `Fn(&str, &str)` + // signature exposed to users must never observe invalid UTF-8, so + // lossily coerce the raw bytes here. + let s1 = { + let c_slice = slice::from_raw_parts(left_ptr as *const u8, left_len); + String::from_utf8_lossy(c_slice) + }; + let s2 = { + let c_slice = slice::from_raw_parts(right_ptr as *const u8, right_len); + String::from_utf8_lossy(c_slice) + }; + let t = (*boxed_f)(&s1, &s2); + + match t { + Ordering::Less => -1, + Ordering::Equal => 0, + Ordering::Greater => 1, + } +} diff --git a/vendor/sqlx-sqlite/src/connection/describe.rs b/vendor/sqlx-sqlite/src/connection/describe.rs new file mode 100755 index 000000000000..400c671d9698 --- /dev/null +++ b/vendor/sqlx-sqlite/src/connection/describe.rs @@ -0,0 +1,101 @@ +use crate::connection::explain::explain; +use crate::connection::ConnectionState; +use crate::describe::Describe; +use crate::error::Error; +use crate::statement::VirtualStatement; +use crate::type_info::DataType; +use crate::{Sqlite, SqliteColumn}; +use sqlx_core::sql_str::SqlStr; +use sqlx_core::Either; +use std::convert::identity; + +pub(crate) fn describe( + conn: &mut ConnectionState, + query: SqlStr, +) -> Result, Error> { + // describing a statement from SQLite can be involved + // each SQLx statement is comprised of multiple SQL statements + + let mut statement = VirtualStatement::new(query.as_str(), false)?; + + let mut columns = Vec::new(); + let mut nullable = Vec::new(); + let mut num_params = 0; + + // we start by finding the first statement that *can* return results + while let Some(stmt) = statement.prepare_next(&mut conn.handle)? { + num_params += stmt.handle.bind_parameter_count(); + + let mut stepped = false; + + let num = stmt.handle.column_count(); + if num == 0 { + // no columns in this statement; skip + continue; + } + + // next we try to use [column_decltype] to inspect the type of each column + columns.reserve(num); + + // as a last resort, we explain the original query and attempt to + // infer what would the expression types be as a fallback + // to [column_decltype] + + // if explain.. fails, ignore the failure and we'll have no fallback + let (fallback, fallback_nullable) = match explain(conn, stmt.handle.sql()) { + Ok(v) => v, + Err(error) => { + tracing::debug!(%error, "describe: explain introspection failed"); + + (vec![], vec![]) + } + }; + + for col in 0..num { + let name = stmt.handle.column_name(col).to_owned(); + + let origin = stmt.handle.column_origin(col); + + let type_info = if let Some(ty) = stmt.handle.column_decltype(col) { + ty + } else { + // if that fails, we back up and attempt to step the statement + // once *if* its read-only and then use [column_type] as a + // fallback to [column_decltype] + if !stepped && stmt.handle.read_only() { + stepped = true; + let _ = stmt.handle.step(); + } + + let mut ty = stmt.handle.column_type_info(col); + + if ty.0 == DataType::Null { + if let Some(fallback) = fallback.get(col).cloned() { + ty = fallback; + } + } + + ty + }; + + // check explain + let col_nullable = stmt.handle.column_nullable(col)?; + let exp_nullable = fallback_nullable.get(col).copied().and_then(identity); + + nullable.push(exp_nullable.or(col_nullable)); + + columns.push(SqliteColumn { + name: name.into(), + type_info, + ordinal: col, + origin, + }); + } + } + + Ok(Describe { + columns, + parameters: Some(Either::Right(num_params)), + nullable, + }) +} diff --git a/vendor/sqlx-sqlite/src/connection/deserialize.rs b/vendor/sqlx-sqlite/src/connection/deserialize.rs new file mode 100755 index 000000000000..5056eb6784a1 --- /dev/null +++ b/vendor/sqlx-sqlite/src/connection/deserialize.rs @@ -0,0 +1,299 @@ +use super::ConnectionState; +use crate::{error::Error, SqliteConnection, SqliteError}; +use libsqlite3_sys::{ + sqlite3_deserialize, sqlite3_free, sqlite3_malloc64, sqlite3_serialize, + SQLITE_DESERIALIZE_FREEONCLOSE, SQLITE_DESERIALIZE_READONLY, SQLITE_DESERIALIZE_RESIZEABLE, + SQLITE_NOMEM, SQLITE_OK, +}; +use std::ffi::c_char; +use std::fmt::Debug; +use std::{ + ops::{Deref, DerefMut}, + ptr, + ptr::NonNull, +}; + +impl SqliteConnection { + /// Serialize the given SQLite database schema using [`sqlite3_serialize()`]. + /// + /// The returned buffer is a SQLite managed allocation containing the equivalent data + /// as writing the database to disk. It is freed on-drop. + /// + /// To serialize the primary, unqualified schema (`main`), pass `None` for the schema name. + /// + /// # Errors + /// * [`Error::InvalidArgument`] if the schema name contains a zero/NUL byte (`\0`). + /// * [`Error::Database`] if the schema does not exist or another error occurs. + /// + /// [`sqlite3_serialize()`]: https://sqlite.org/c3ref/serialize.html + #[cfg_attr(docsrs, doc(cfg(feature = "sqlite-deserialize")))] + pub async fn serialize(&mut self, schema: Option<&str>) -> Result { + let schema = schema.map(SchemaName::try_from).transpose()?; + + self.worker.serialize(schema).await + } + + /// Deserialize a SQLite database from a buffer into the specified schema using [`sqlite3_deserialize()`]. + /// + /// The given schema will be disconnected and re-connected as an in-memory database + /// backed by `data`, which should be the serialized form of a database previously returned + /// by a call to [`Self::serialize()`], documented as being equivalent to + /// the contents of the database file on disk. + /// + /// An error will be returned if a schema with the given name is not already attached. + /// You can use `ATTACH ':memory' as ""` to create an empty schema first. + /// + /// Pass `None` to deserialize to the primary, unqualified schema (`main`). + /// + /// The SQLite connection will take ownership of `data` and will free it when the connection + /// is closed or the schema is detached ([`SQLITE_DESERIALIZE_FREEONCLOSE`][deserialize-flags]). + /// + /// If `read_only` is `true`, the schema is opened as read-only ([`SQLITE_DESERIALIZE_READONLY`][deserialize-flags]). + /// If `false`, the schema is marked as resizable ([`SQLITE_DESERIALIZE_RESIZABLE`][deserialize-flags]). + /// + /// If the database is in WAL mode, an error is returned. + /// See [`sqlite3_deserialize()`] for details. + /// + /// # Errors + /// * [`Error::InvalidArgument`] if the schema name contains a zero/NUL byte (`\0`). + /// * [`Error::Database`] if an error occurs during deserialization. + /// + /// [`sqlite3_deserialize()`]: https://sqlite.org/c3ref/deserialize.html + /// [deserialize-flags]: https://sqlite.org/c3ref/c_deserialize_freeonclose.html + #[cfg_attr(docsrs, doc(cfg(feature = "sqlite-deserialize")))] + pub async fn deserialize( + &mut self, + schema: Option<&str>, + data: SqliteOwnedBuf, + read_only: bool, + ) -> Result<(), Error> { + let schema = schema.map(SchemaName::try_from).transpose()?; + + self.worker.deserialize(schema, data, read_only).await + } +} + +pub(crate) fn serialize( + conn: &mut ConnectionState, + schema: Option, +) -> Result { + let mut size = 0; + + let buf = unsafe { + let ptr = sqlite3_serialize( + conn.handle.as_ptr(), + schema.as_ref().map_or(ptr::null(), SchemaName::as_ptr), + &mut size, + 0, + ); + + // looking at the source, `sqlite3_serialize` actually sets `size = -1` on error: + // https://github.com/sqlite/sqlite/blob/da5f81387843f92652128087a8f8ecef0b79461d/src/memdb.c#L776 + usize::try_from(size) + .ok() + .and_then(|size| SqliteOwnedBuf::from_raw(ptr, size)) + }; + + if let Some(buf) = buf { + return Ok(buf); + } + + if let Some(error) = conn.handle.last_error() { + return Err(error.into()); + } + + if size > 0 { + // If `size` is positive but `sqlite3_serialize` still returned NULL, + // the most likely culprit is an out-of-memory condition. + return Err(SqliteError::from_code(SQLITE_NOMEM).into()); + } + + // Otherwise, the schema was probably not found. + // We return the equivalent error as when you try to execute `PRAGMA .page_count` + // against a non-existent schema. + Err(SqliteError::generic(format!( + "database {} does not exist", + schema.as_ref().map_or("main", SchemaName::as_str) + )) + .into()) +} + +pub(crate) fn deserialize( + conn: &mut ConnectionState, + schema: Option, + data: SqliteOwnedBuf, + read_only: bool, +) -> Result<(), Error> { + // SQLITE_DESERIALIZE_FREEONCLOSE causes SQLite to take ownership of the buffer + let mut flags = SQLITE_DESERIALIZE_FREEONCLOSE; + if read_only { + flags |= SQLITE_DESERIALIZE_READONLY; + } else { + flags |= SQLITE_DESERIALIZE_RESIZEABLE; + } + + let (buf, size) = data.into_raw(); + + let rc = unsafe { + sqlite3_deserialize( + conn.handle.as_ptr(), + schema.as_ref().map_or(ptr::null(), SchemaName::as_ptr), + buf, + i64::try_from(size).unwrap(), + i64::try_from(size).unwrap(), + flags, + ) + }; + + match rc { + SQLITE_OK => Ok(()), + SQLITE_NOMEM => Err(SqliteError::from_code(SQLITE_NOMEM).into()), + // SQLite unfortunately doesn't set any specific message for deserialization errors. + _ => Err(SqliteError::generic("an error occurred during deserialization").into()), + } +} + +/// Memory buffer owned and allocated by SQLite. Freed on drop. +/// +/// Intended primarily for use with [`SqliteConnection::serialize()`] and [`SqliteConnection::deserialize()`]. +/// +/// Can be created from `&[u8]` using the `TryFrom` impl. The slice must not be empty. +#[derive(Debug)] +pub struct SqliteOwnedBuf { + ptr: NonNull, + size: usize, +} + +unsafe impl Send for SqliteOwnedBuf {} +unsafe impl Sync for SqliteOwnedBuf {} + +impl Drop for SqliteOwnedBuf { + fn drop(&mut self) { + unsafe { + sqlite3_free(self.ptr.as_ptr().cast()); + } + } +} + +impl SqliteOwnedBuf { + /// Uses `sqlite3_malloc` to allocate a buffer and returns a pointer to it. + /// + /// # Safety + /// The allocated buffer is uninitialized. + unsafe fn with_capacity(size: usize) -> Option { + let ptr = sqlite3_malloc64(u64::try_from(size).unwrap()).cast::(); + Self::from_raw(ptr, size) + } + + /// Creates a new mem buffer from a pointer that has been created with sqlite_malloc + /// + /// # Safety: + /// * The pointer must point to a valid allocation created by `sqlite3_malloc()`, or `NULL`. + unsafe fn from_raw(ptr: *mut u8, size: usize) -> Option { + Some(Self { + ptr: NonNull::new(ptr)?, + size, + }) + } + + fn into_raw(self) -> (*mut u8, usize) { + let raw = (self.ptr.as_ptr(), self.size); + // this is used in sqlite_deserialize and + // underlying buffer must not be freed + std::mem::forget(self); + raw + } +} + +/// # Errors +/// Returns [`Error::InvalidArgument`] if the slice is empty. +impl TryFrom<&[u8]> for SqliteOwnedBuf { + type Error = Error; + + fn try_from(bytes: &[u8]) -> Result { + unsafe { + // SAFETY: `buf` is not initialized until `ptr::copy_nonoverlapping` completes. + let mut buf = Self::with_capacity(bytes.len()).ok_or_else(|| { + Error::InvalidArgument("SQLite owned buffer cannot be empty".to_string()) + })?; + ptr::copy_nonoverlapping(bytes.as_ptr(), buf.ptr.as_mut(), buf.size); + Ok(buf) + } + } +} + +impl Deref for SqliteOwnedBuf { + type Target = [u8]; + + fn deref(&self) -> &Self::Target { + unsafe { std::slice::from_raw_parts(self.ptr.as_ptr(), self.size) } + } +} + +impl DerefMut for SqliteOwnedBuf { + fn deref_mut(&mut self) -> &mut Self::Target { + unsafe { std::slice::from_raw_parts_mut(self.ptr.as_mut(), self.size) } + } +} + +impl AsRef<[u8]> for SqliteOwnedBuf { + fn as_ref(&self) -> &[u8] { + self.deref() + } +} + +impl AsMut<[u8]> for SqliteOwnedBuf { + fn as_mut(&mut self) -> &mut [u8] { + self.deref_mut() + } +} + +/// Checked schema name to pass to SQLite. +/// +/// # Safety: +/// * Valid UTF-8 (not guaranteed by `CString`) +/// * No internal zero bytes (`\0`) (not guaranteed by `String`) +/// * Terminated with a zero byte (`\0`) (not guaranteed by `String`) +#[derive(Debug)] +pub(crate) struct SchemaName(Box); + +impl SchemaName { + /// Get the schema name as a string without the zero byte terminator. + pub fn as_str(&self) -> &str { + &self.0[..self.0.len() - 1] + } + + /// Get a pointer to the string data, suitable for passing as C's `*const char`. + /// + /// # Safety + /// The string data is guaranteed to be terminated with a zero byte. + pub fn as_ptr(&self) -> *const c_char { + self.0.as_ptr() as *const c_char + } +} + +impl<'a> TryFrom<&'a str> for SchemaName { + type Error = Error; + + fn try_from(name: &'a str) -> Result { + // SAFETY: we must ensure that the string does not contain an internal NULL byte + if let Some(pos) = name.as_bytes().iter().position(|&b| b == 0) { + return Err(Error::InvalidArgument(format!( + "schema name {name:?} contains a zero byte at index {pos}" + ))); + } + + let capacity = name.len().checked_add(1).unwrap(); + + let mut s = String::new(); + // `String::with_capacity()` does not guarantee that it will not overallocate, + // which might mean an unnecessary reallocation to make `capacity == len` + // in the conversion to `Box`. + s.reserve_exact(capacity); + + s.push_str(name); + s.push('\0'); + + Ok(SchemaName(s.into())) + } +} diff --git a/vendor/sqlx-sqlite/src/connection/establish.rs b/vendor/sqlx-sqlite/src/connection/establish.rs new file mode 100755 index 000000000000..cedf752e6ade --- /dev/null +++ b/vendor/sqlx-sqlite/src/connection/establish.rs @@ -0,0 +1,271 @@ +use crate::connection::handle::ConnectionHandle; +use crate::connection::LogSettings; +use crate::connection::{ConnectionState, Statements}; +use crate::error::Error; +use crate::SqliteConnectOptions; +use libsqlite3_sys::{ + sqlite3_busy_timeout, SQLITE_OPEN_CREATE, SQLITE_OPEN_FULLMUTEX, SQLITE_OPEN_MEMORY, + SQLITE_OPEN_NOMUTEX, SQLITE_OPEN_PRIVATECACHE, SQLITE_OPEN_READONLY, SQLITE_OPEN_READWRITE, + SQLITE_OPEN_SHAREDCACHE, SQLITE_OPEN_URI, +}; +use percent_encoding::NON_ALPHANUMERIC; +use std::collections::BTreeMap; +use std::ffi::CString; +use std::io; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Duration; + +#[cfg(feature = "load-extension")] +use sqlx_core::IndexMap; + +// This was originally `AtomicU64` but that's not supported on MIPS (or PowerPC): +// https://github.com/launchbadge/sqlx/issues/2859 +// https://doc.rust-lang.org/stable/std/sync/atomic/index.html#portability +static THREAD_ID: AtomicUsize = AtomicUsize::new(0); + +pub struct EstablishParams { + filename: CString, + open_flags: i32, + busy_timeout: Duration, + statement_cache_capacity: usize, + log_settings: LogSettings, + #[cfg(feature = "load-extension")] + extensions: IndexMap>, + pub(crate) thread_name: String, + pub(crate) command_channel_size: usize, + #[cfg(feature = "regexp")] + register_regexp_function: bool, +} + +impl EstablishParams { + pub fn from_options(options: &SqliteConnectOptions) -> Result { + let mut filename = options + .filename + .to_str() + .ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "filename passed to SQLite must be valid UTF-8", + ) + })? + .to_owned(); + + // Set common flags we expect to have in sqlite + let mut flags = SQLITE_OPEN_URI; + + // By default, we connect to an in-memory database. + // [SQLITE_OPEN_NOMUTEX] will instruct [sqlite3_open_v2] to return an error if it + // cannot satisfy our wish for a thread-safe, lock-free connection object + + flags |= if options.serialized { + SQLITE_OPEN_FULLMUTEX + } else { + SQLITE_OPEN_NOMUTEX + }; + + flags |= if options.read_only { + SQLITE_OPEN_READONLY + } else if options.create_if_missing { + SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE + } else { + SQLITE_OPEN_READWRITE + }; + + if options.in_memory { + flags |= SQLITE_OPEN_MEMORY; + } + + flags |= if options.shared_cache { + SQLITE_OPEN_SHAREDCACHE + } else { + SQLITE_OPEN_PRIVATECACHE + }; + + let mut query_params = BTreeMap::new(); + + if options.immutable { + query_params.insert("immutable", "true"); + } + + if let Some(vfs) = options.vfs.as_deref() { + query_params.insert("vfs", vfs); + } + + if !query_params.is_empty() { + filename = format!( + "file:{}?", + percent_encoding::percent_encode(filename.as_bytes(), NON_ALPHANUMERIC), + ); + + // Suffix serializer automatically handles `&` separators for us. + let filename_len = filename.len(); + filename = form_urlencoded::Serializer::for_suffix(filename, filename_len) + .extend_pairs(query_params) + .finish(); + } + + let filename = CString::new(filename).map_err(|_| { + io::Error::new( + io::ErrorKind::InvalidData, + "filename passed to SQLite must not contain nul bytes", + ) + })?; + + #[cfg(feature = "load-extension")] + let extensions = options + .extensions + .iter() + .map(|(name, entry)| { + let entry = entry + .as_ref() + .map(|e| { + CString::new(e.as_bytes()).map_err(|_| { + io::Error::new( + io::ErrorKind::InvalidData, + "extension entrypoint names passed to SQLite must not contain nul bytes" + ) + }) + }) + .transpose()?; + Ok(( + CString::new(name.as_bytes()).map_err(|_| { + io::Error::new( + io::ErrorKind::InvalidData, + "extension names passed to SQLite must not contain nul bytes", + ) + })?, + entry, + )) + }) + .collect::>, io::Error>>()?; + + let thread_id = THREAD_ID.fetch_add(1, Ordering::AcqRel); + + Ok(Self { + filename, + open_flags: flags, + busy_timeout: options.busy_timeout, + statement_cache_capacity: options.statement_cache_capacity, + log_settings: options.log_settings.clone(), + #[cfg(feature = "load-extension")] + extensions, + thread_name: (options.thread_name)(thread_id as u64), + command_channel_size: options.command_channel_size, + #[cfg(feature = "regexp")] + register_regexp_function: options.register_regexp_function, + }) + } + + pub(crate) fn establish(&self) -> Result { + let mut handle = ConnectionHandle::open(&self.filename, self.open_flags)?; + + #[cfg(feature = "load-extension")] + unsafe { + self.apply_extensions(&mut handle)?; + } + + #[cfg(feature = "regexp")] + if self.register_regexp_function { + // configure a `regexp` function for sqlite, it does not come with one by default + let status = crate::regexp::register(handle.as_ptr()); + if status != libsqlite3_sys::SQLITE_OK { + return Err(Error::Database(Box::new(handle.expect_error()))); + } + } + + // Configure a busy timeout + // This causes SQLite to automatically sleep in increasing intervals until the time + // when there is something locked during [sqlite3_step]. + // + // We also need to convert the u128 value to i32, checking we're not overflowing. + let ms = i32::try_from(self.busy_timeout.as_millis()) + .expect("Given busy timeout value is too big."); + + handle.call_with_result(|db| unsafe { sqlite3_busy_timeout(db, ms) })?; + + Ok(ConnectionState { + handle, + statements: Statements::new(self.statement_cache_capacity), + log_settings: self.log_settings.clone(), + progress_handler_callback: None, + update_hook_callback: None, + #[cfg(feature = "preupdate-hook")] + preupdate_hook_callback: None, + commit_hook_callback: None, + rollback_hook_callback: None, + }) + } + + #[cfg(feature = "load-extension")] + unsafe fn apply_extensions(&self, handle: &mut ConnectionHandle) -> Result<(), Error> { + use libsqlite3_sys::{sqlite3_free, sqlite3_load_extension}; + use std::ffi::{c_int, CStr}; + use std::ptr; + + /// `true` enables *just* `sqlite3_load_extension`, false disables *all* extension loading. + fn enable_load_extension( + handle: &mut ConnectionHandle, + enabled: bool, + ) -> Result<(), Error> { + use libsqlite3_sys::{sqlite3_db_config, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION}; + + // SAFETY: we have exclusive access and this matches the expected signature + // + handle.call_with_result(|db| unsafe { + // https://doc.rust-lang.org/reference/expressions/operator-expr.html#r-expr.as.bool-char-as-int + sqlite3_db_config( + db, + SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, + enabled as c_int, + ptr::null_mut::(), + ) + })?; + + Ok(()) + } + + if self.extensions.is_empty() { + return Ok(()); + } + + // We enable extension loading only so long as *we're* doing it. + enable_load_extension(handle, true)?; + + for (name, entrypoint) in &self.extensions { + let name_ptr = name.as_ptr(); + let entrypoint_ptr = entrypoint.as_ref().map_or_else(ptr::null, |s| s.as_ptr()); + let mut err_msg_ptr = ptr::null_mut(); + + // SAFETY: + // * we have exclusive access + // * all pointers are initialized + // * we warn the user about loading extensions in documentation + handle + .call_with_result(|db| unsafe { + sqlite3_load_extension(db, name_ptr, entrypoint_ptr, &mut err_msg_ptr) + }) + .map_err(|e| { + if !err_msg_ptr.is_null() { + // SAFETY: pointer is not-null, + // and we copy the error message to an allocation we own. + let err_msg = unsafe { CStr::from_ptr(err_msg_ptr) } + // In practice, the string *should* be UTF-8. + .to_string_lossy() + .into_owned(); + + // SAFETY: we're expected to free the error message afterward. + unsafe { + sqlite3_free(err_msg_ptr.cast()); + } + + e.with_message(err_msg) + } else { + e + } + })?; + } + + // We then disable extension loading immediately afterward. + enable_load_extension(handle, false) + } +} diff --git a/vendor/sqlx-sqlite/src/connection/execute.rs b/vendor/sqlx-sqlite/src/connection/execute.rs new file mode 100755 index 000000000000..733a1abbe66b --- /dev/null +++ b/vendor/sqlx-sqlite/src/connection/execute.rs @@ -0,0 +1,132 @@ +use crate::connection::{ConnectionHandle, ConnectionState}; +use crate::error::Error; +use crate::logger::QueryLogger; +use crate::statement::{StatementHandle, VirtualStatement}; +use crate::{SqliteArguments, SqliteQueryResult, SqliteRow}; +use sqlx_core::sql_str::SqlSafeStr; +use sqlx_core::Either; + +pub struct ExecuteIter<'a> { + handle: &'a mut ConnectionHandle, + statement: &'a mut VirtualStatement, + logger: QueryLogger, + args: Option, + + /// since a `VirtualStatement` can encompass multiple actual statements, + /// this keeps track of the number of arguments so far + args_used: usize, + + goto_next: bool, +} + +pub(crate) fn iter( + conn: &mut ConnectionState, + query: impl SqlSafeStr, + args: Option, + persistent: bool, +) -> Result, Error> { + let query = query.into_sql_str(); + // fetch the cached statement or allocate a new one + let statement = conn.statements.get(query.as_str(), persistent)?; + + let logger = QueryLogger::new(query, conn.log_settings.clone()); + + Ok(ExecuteIter { + handle: &mut conn.handle, + statement, + logger, + args, + args_used: 0, + goto_next: true, + }) +} + +fn bind( + statement: &mut StatementHandle, + arguments: &Option, + offset: usize, +) -> Result { + let mut n = 0; + + if let Some(arguments) = arguments { + n = arguments.bind(statement, offset)?; + } + + Ok(n) +} + +impl ExecuteIter<'_> { + pub fn finish(self) -> Result<(), Error> { + for res in self { + let _ = res?; + } + + Ok(()) + } +} + +impl Iterator for ExecuteIter<'_> { + type Item = Result, Error>; + + fn next(&mut self) -> Option { + let statement = if self.goto_next { + let statement = match self.statement.prepare_next(self.handle) { + Ok(Some(statement)) => statement, + Ok(None) => return None, + Err(e) => return Some(Err(e)), + }; + + self.goto_next = false; + + // sanity check: ensure the VM is reset and the bindings are cleared + if let Err(e) = statement.handle.reset() { + return Some(Err(e.into())); + } + + statement.handle.clear_bindings(); + + match bind(statement.handle, &self.args, self.args_used) { + Ok(args_used) => self.args_used += args_used, + Err(e) => return Some(Err(e)), + } + + statement + } else { + self.statement.current()? + }; + + match statement.handle.step() { + Ok(true) => { + self.logger.increment_rows_returned(); + + Some(Ok(Either::Right(SqliteRow::current( + statement.handle, + statement.columns, + statement.column_names, + )))) + } + Ok(false) => { + let last_insert_rowid = self.handle.last_insert_rowid(); + + let changes = statement.handle.changes(); + self.logger.increase_rows_affected(changes); + + let done = SqliteQueryResult { + changes, + last_insert_rowid, + }; + + self.goto_next = true; + + Some(Ok(Either::Left(done))) + } + Err(e) => Some(Err(e.into())), + } + } +} + +impl Drop for ExecuteIter<'_> { + fn drop(&mut self) { + self.statement.reset().ok(); + } +} diff --git a/vendor/sqlx-sqlite/src/connection/executor.rs b/vendor/sqlx-sqlite/src/connection/executor.rs new file mode 100755 index 000000000000..a62d3349a559 --- /dev/null +++ b/vendor/sqlx-sqlite/src/connection/executor.rs @@ -0,0 +1,101 @@ +use crate::{ + Sqlite, SqliteConnection, SqliteQueryResult, SqliteRow, SqliteStatement, SqliteTypeInfo, +}; +use futures_core::future::BoxFuture; +use futures_core::stream::BoxStream; +use futures_util::{stream, FutureExt, StreamExt, TryFutureExt, TryStreamExt}; +use sqlx_core::error::Error; +use sqlx_core::executor::{Execute, Executor}; +use sqlx_core::sql_str::SqlStr; +use sqlx_core::Either; +use std::{future, pin::pin}; + +impl<'c> Executor<'c> for &'c mut SqliteConnection { + type Database = Sqlite; + + fn fetch_many<'e, 'q, E>( + self, + mut query: E, + ) -> BoxStream<'e, Result, Error>> + where + 'c: 'e, + E: Execute<'q, Self::Database>, + 'q: 'e, + E: 'q, + { + let arguments = match query.take_arguments().map_err(Error::Encode) { + Ok(arguments) => arguments, + Err(error) => return stream::once(future::ready(Err(error))).boxed(), + }; + let persistent = query.persistent() && arguments.is_some(); + let sql = query.sql(); + + Box::pin( + self.worker + .execute(sql, arguments, self.row_channel_size, persistent, None) + .map_ok(flume::Receiver::into_stream) + .try_flatten_stream(), + ) + } + + fn fetch_optional<'e, 'q, E>( + self, + mut query: E, + ) -> BoxFuture<'e, Result, Error>> + where + 'c: 'e, + E: Execute<'q, Self::Database>, + 'q: 'e, + E: 'q, + { + let arguments = match query.take_arguments().map_err(Error::Encode) { + Ok(arguments) => arguments, + Err(error) => return future::ready(Err(error)).boxed(), + }; + let persistent = query.persistent() && arguments.is_some(); + + Box::pin(async move { + let sql = query.sql(); + let mut stream = pin!(self + .worker + .execute(sql, arguments, self.row_channel_size, persistent, Some(1)) + .map_ok(flume::Receiver::into_stream) + .try_flatten_stream()); + + while let Some(res) = stream.try_next().await? { + if let Either::Right(row) = res { + return Ok(Some(row)); + } + } + + Ok(None) + }) + } + + fn prepare_with<'e>( + self, + sql: SqlStr, + _parameters: &[SqliteTypeInfo], + ) -> BoxFuture<'e, Result> + where + 'c: 'e, + { + Box::pin(async move { + let statement = self.worker.prepare(sql).await?; + + Ok(statement) + }) + } + + #[doc(hidden)] + #[cfg(feature = "offline")] + fn describe<'e>( + self, + sql: SqlStr, + ) -> BoxFuture<'e, Result, Error>> + where + 'c: 'e, + { + Box::pin(async move { self.worker.describe(sql).await }) + } +} diff --git a/vendor/sqlx-sqlite/src/connection/explain.rs b/vendor/sqlx-sqlite/src/connection/explain.rs new file mode 100755 index 000000000000..550f21557e3c --- /dev/null +++ b/vendor/sqlx-sqlite/src/connection/explain.rs @@ -0,0 +1,1844 @@ +// Bad casts in this module SHOULD NOT result in a SQL injection +// https://github.com/launchbadge/sqlx/issues/3440 +#![allow( + clippy::cast_possible_truncation, + clippy::cast_possible_wrap, + clippy::cast_sign_loss +)] +use crate::connection::intmap::IntMap; +use crate::connection::{execute, ConnectionState}; +use crate::error::Error; +use crate::from_row::FromRow; +use crate::logger::{BranchParent, BranchResult, DebugDiff}; +use crate::type_info::DataType; +use crate::SqliteTypeInfo; +use sqlx_core::sql_str::AssertSqlSafe; +use sqlx_core::{hash_map, HashMap}; +use std::fmt::Debug; +use std::str::from_utf8; + +// affinity +const SQLITE_AFF_NONE: u8 = 0x40; /* '@' */ +const SQLITE_AFF_BLOB: u8 = 0x41; /* 'A' */ +const SQLITE_AFF_TEXT: u8 = 0x42; /* 'B' */ +const SQLITE_AFF_NUMERIC: u8 = 0x43; /* 'C' */ +const SQLITE_AFF_INTEGER: u8 = 0x44; /* 'D' */ +const SQLITE_AFF_REAL: u8 = 0x45; /* 'E' */ + +// opcodes +const OP_INIT: &str = "Init"; +const OP_GOTO: &str = "Goto"; +const OP_DECR_JUMP_ZERO: &str = "DecrJumpZero"; +const OP_DELETE: &str = "Delete"; +const OP_ELSE_EQ: &str = "ElseEq"; +const OP_EQ: &str = "Eq"; +const OP_END_COROUTINE: &str = "EndCoroutine"; +const OP_FILTER: &str = "Filter"; +const OP_FK_IF_ZERO: &str = "FkIfZero"; +const OP_FOUND: &str = "Found"; +const OP_GE: &str = "Ge"; +const OP_GO_SUB: &str = "Gosub"; +const OP_GT: &str = "Gt"; +const OP_IDX_GE: &str = "IdxGE"; +const OP_IDX_GT: &str = "IdxGT"; +const OP_IDX_LE: &str = "IdxLE"; +const OP_IDX_LT: &str = "IdxLT"; +const OP_IDX_ROWID: &str = "IdxRowid"; +const OP_IF: &str = "If"; +const OP_IF_NO_HOPE: &str = "IfNoHope"; +const OP_IF_NOT: &str = "IfNot"; +const OP_IF_NOT_OPEN: &str = "IfNotOpen"; +const OP_IF_NOT_ZERO: &str = "IfNotZero"; +const OP_IF_NULL_ROW: &str = "IfNullRow"; +const OP_IF_POS: &str = "IfPos"; +const OP_IF_SMALLER: &str = "IfSmaller"; +const OP_INCR_VACUUM: &str = "IncrVacuum"; +const OP_INIT_COROUTINE: &str = "InitCoroutine"; +const OP_IS_NULL: &str = "IsNull"; +const OP_IS_NULL_OR_TYPE: &str = "IsNullOrType"; +const OP_LAST: &str = "Last"; +const OP_LE: &str = "Le"; +const OP_LT: &str = "Lt"; +const OP_MUST_BE_INT: &str = "MustBeInt"; +const OP_NE: &str = "Ne"; +const OP_NEXT: &str = "Next"; +const OP_NO_CONFLICT: &str = "NoConflict"; +const OP_NOT_EXISTS: &str = "NotExists"; +const OP_NOT_NULL: &str = "NotNull"; +const OP_ONCE: &str = "Once"; +const OP_PREV: &str = "Prev"; +const OP_PROGRAM: &str = "Program"; +const OP_RETURN: &str = "Return"; +const OP_REWIND: &str = "Rewind"; +const OP_ROW_DATA: &str = "RowData"; +const OP_ROW_SET_READ: &str = "RowSetRead"; +const OP_ROW_SET_TEST: &str = "RowSetTest"; +const OP_SEEK_GE: &str = "SeekGE"; +const OP_SEEK_GT: &str = "SeekGT"; +const OP_SEEK_LE: &str = "SeekLE"; +const OP_SEEK_LT: &str = "SeekLT"; +const OP_SEEK_ROW_ID: &str = "SeekRowid"; +const OP_SEEK_SCAN: &str = "SeekScan"; +const OP_SEQUENCE: &str = "Sequence"; +const OP_SEQUENCE_TEST: &str = "SequenceTest"; +const OP_SORT: &str = "Sort"; +const OP_SORTER_DATA: &str = "SorterData"; +const OP_SORTER_INSERT: &str = "SorterInsert"; +const OP_SORTER_NEXT: &str = "SorterNext"; +const OP_SORTER_OPEN: &str = "SorterOpen"; +const OP_SORTER_SORT: &str = "SorterSort"; +const OP_V_FILTER: &str = "VFilter"; +const OP_V_NEXT: &str = "VNext"; +const OP_YIELD: &str = "Yield"; +const OP_JUMP: &str = "Jump"; +const OP_COLUMN: &str = "Column"; +const OP_MAKE_RECORD: &str = "MakeRecord"; +const OP_INSERT: &str = "Insert"; +const OP_IDX_INSERT: &str = "IdxInsert"; +const OP_OPEN_DUP: &str = "OpenDup"; +const OP_OPEN_PSEUDO: &str = "OpenPseudo"; +const OP_OPEN_READ: &str = "OpenRead"; +const OP_OPEN_WRITE: &str = "OpenWrite"; +const OP_OPEN_EPHEMERAL: &str = "OpenEphemeral"; +const OP_OPEN_AUTOINDEX: &str = "OpenAutoindex"; +const OP_AGG_FINAL: &str = "AggFinal"; +const OP_AGG_VALUE: &str = "AggValue"; +const OP_AGG_STEP: &str = "AggStep"; +const OP_FUNCTION: &str = "Function"; +const OP_MOVE: &str = "Move"; +const OP_COPY: &str = "Copy"; +const OP_SCOPY: &str = "SCopy"; +const OP_NULL: &str = "Null"; +const OP_NULL_ROW: &str = "NullRow"; +const OP_INT_COPY: &str = "IntCopy"; +const OP_CAST: &str = "Cast"; +const OP_STRING8: &str = "String8"; +const OP_INT64: &str = "Int64"; +const OP_INTEGER: &str = "Integer"; +const OP_REAL: &str = "Real"; +const OP_NOT: &str = "Not"; +const OP_BLOB: &str = "Blob"; +const OP_VARIABLE: &str = "Variable"; +const OP_COUNT: &str = "Count"; +const OP_ROWID: &str = "Rowid"; +const OP_NEWROWID: &str = "NewRowid"; +const OP_OR: &str = "Or"; +const OP_AND: &str = "And"; +const OP_BIT_AND: &str = "BitAnd"; +const OP_BIT_OR: &str = "BitOr"; +const OP_SHIFT_LEFT: &str = "ShiftLeft"; +const OP_SHIFT_RIGHT: &str = "ShiftRight"; +const OP_ADD: &str = "Add"; +const OP_SUBTRACT: &str = "Subtract"; +const OP_MULTIPLY: &str = "Multiply"; +const OP_DIVIDE: &str = "Divide"; +const OP_REMAINDER: &str = "Remainder"; +const OP_CONCAT: &str = "Concat"; +const OP_OFFSET_LIMIT: &str = "OffsetLimit"; +const OP_RESULT_ROW: &str = "ResultRow"; +const OP_HALT: &str = "Halt"; +const OP_HALT_IF_NULL: &str = "HaltIfNull"; + +const MAX_LOOP_COUNT: u8 = 2; +const MAX_TOTAL_INSTRUCTION_COUNT: u32 = 100_000; + +#[derive(Clone, Eq, PartialEq, Hash)] +enum ColumnType { + Single { + datatype: DataType, + nullable: Option, + }, + Record(IntMap), +} + +impl Default for ColumnType { + fn default() -> Self { + Self::Single { + datatype: DataType::Null, + nullable: None, + } + } +} + +impl ColumnType { + fn null() -> Self { + Self::Single { + datatype: DataType::Null, + nullable: Some(true), + } + } + fn map_to_datatype(&self) -> DataType { + match self { + Self::Single { datatype, .. } => *datatype, + Self::Record(_) => DataType::Null, //If we're trying to coerce to a regular Datatype, we can assume a Record is invalid for the context + } + } + fn map_to_nullable(&self) -> Option { + match self { + Self::Single { nullable, .. } => *nullable, + Self::Record(_) => None, //If we're trying to coerce to a regular Datatype, we can assume a Record is invalid for the context + } + } +} + +impl core::fmt::Debug for ColumnType { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::Single { datatype, nullable } => { + let nullable_str = match nullable { + Some(true) => "NULL", + Some(false) => "NOT NULL", + None => "NULL?", + }; + write!(f, "{:?} {}", datatype, nullable_str) + } + Self::Record(columns) => { + f.write_str("Record(")?; + let mut column_iter = columns.iter(); + if let Some(item) = column_iter.next() { + write!(f, "{:?}", item)?; + for item in column_iter { + write!(f, ", {:?}", item)?; + } + } + f.write_str(")") + } + } + } +} + +#[derive(Debug, Clone, Eq, PartialEq, Hash)] +enum RegDataType { + Single(ColumnType), + Int(i64), +} + +impl RegDataType { + fn map_to_datatype(&self) -> DataType { + match self { + RegDataType::Single(d) => d.map_to_datatype(), + RegDataType::Int(_) => DataType::Integer, + } + } + fn map_to_nullable(&self) -> Option { + match self { + RegDataType::Single(d) => d.map_to_nullable(), + RegDataType::Int(_) => Some(false), + } + } + fn map_to_columntype(&self) -> ColumnType { + match self { + RegDataType::Single(d) => d.clone(), + RegDataType::Int(_) => ColumnType::Single { + datatype: DataType::Integer, + nullable: Some(false), + }, + } + } +} + +impl Default for RegDataType { + fn default() -> Self { + Self::Single(ColumnType::default()) + } +} + +#[derive(Debug, Clone, Eq, PartialEq, Hash)] +struct TableDataType { + cols: IntMap, + is_empty: Option, +} + +#[derive(Debug, Clone, Eq, PartialEq, Hash)] +enum CursorDataType { + Normal(i64), + Pseudo(i64), +} + +impl CursorDataType { + fn columns( + &self, + tables: &IntMap, + registers: &IntMap, + ) -> IntMap { + match self { + Self::Normal(i) => match tables.get(i) { + Some(tab) => tab.cols.clone(), + None => IntMap::new(), + }, + Self::Pseudo(i) => match registers.get(i) { + Some(RegDataType::Single(ColumnType::Record(r))) => r.clone(), + _ => IntMap::new(), + }, + } + } + + fn columns_ref<'s, 'r, 'o>( + &'s self, + tables: &'r IntMap, + registers: &'r IntMap, + ) -> Option<&'o IntMap> + where + 's: 'o, + 'r: 'o, + { + match self { + Self::Normal(i) => match tables.get(i) { + Some(tab) => Some(&tab.cols), + None => None, + }, + Self::Pseudo(i) => match registers.get(i) { + Some(RegDataType::Single(ColumnType::Record(r))) => Some(r), + _ => None, + }, + } + } + + fn columns_mut<'s, 'r, 'o>( + &'s self, + tables: &'r mut IntMap, + registers: &'r mut IntMap, + ) -> Option<&'o mut IntMap> + where + 's: 'o, + 'r: 'o, + { + match self { + Self::Normal(i) => match tables.get_mut(i) { + Some(tab) => Some(&mut tab.cols), + None => None, + }, + Self::Pseudo(i) => match registers.get_mut(i) { + Some(RegDataType::Single(ColumnType::Record(r))) => Some(r), + _ => None, + }, + } + } + + fn table_mut<'s, 'r, 'o>( + &'s self, + tables: &'r mut IntMap, + ) -> Option<&'o mut TableDataType> + where + 's: 'o, + 'r: 'o, + { + match self { + Self::Normal(i) => match tables.get_mut(i) { + Some(tab) => Some(tab), + None => None, + }, + _ => None, + } + } + + fn is_empty(&self, tables: &IntMap) -> Option { + match self { + Self::Normal(i) => match tables.get(i) { + Some(tab) => tab.is_empty, + None => Some(true), + }, + Self::Pseudo(_) => Some(false), //pseudo cursors have exactly one row + } + } +} + +#[allow(clippy::wildcard_in_or_patterns)] +fn affinity_to_type(affinity: u8) -> DataType { + match affinity { + SQLITE_AFF_BLOB => DataType::Blob, + SQLITE_AFF_INTEGER => DataType::Integer, + SQLITE_AFF_NUMERIC => DataType::Numeric, + SQLITE_AFF_REAL => DataType::Float, + SQLITE_AFF_TEXT => DataType::Text, + + SQLITE_AFF_NONE | _ => DataType::Null, + } +} + +#[allow(clippy::wildcard_in_or_patterns)] +fn opcode_to_type(op: &str) -> DataType { + match op { + OP_REAL => DataType::Float, + OP_BLOB => DataType::Blob, + OP_AND | OP_OR => DataType::Bool, + OP_NEWROWID | OP_IDX_ROWID | OP_ROWID | OP_COUNT | OP_INT64 | OP_INTEGER => { + DataType::Integer + } + OP_STRING8 => DataType::Text, + OP_COLUMN | _ => DataType::Null, + } +} + +fn root_block_columns( + conn: &mut ConnectionState, +) -> Result>, Error> { + let table_block_columns: Vec<(i64, i64, i64, String, bool)> = execute::iter( + conn, + "SELECT s.dbnum, s.rootpage, col.cid as colnum, col.type, col.\"notnull\" + FROM ( + select 1 dbnum, tss.* from temp.sqlite_schema tss + UNION ALL select 0 dbnum, mss.* from main.sqlite_schema mss + ) s + JOIN pragma_table_info(s.name) AS col + WHERE s.type = 'table' + UNION ALL + SELECT s.dbnum, s.rootpage, idx.seqno as colnum, col.type, col.\"notnull\" + FROM ( + select 1 dbnum, tss.* from temp.sqlite_schema tss + UNION ALL select 0 dbnum, mss.* from main.sqlite_schema mss + ) s + JOIN pragma_index_info(s.name) AS idx + LEFT JOIN pragma_table_info(s.tbl_name) as col + ON col.cid = idx.cid + WHERE s.type = 'index'", + None, + false, + )? + .filter_map(|res| res.map(|either| either.right()).transpose()) + .map(|row| FromRow::from_row(&row?)) + .collect::, Error>>()?; + + let mut row_info: HashMap<(i64, i64), IntMap> = HashMap::new(); + for (dbnum, block, colnum, datatype, notnull) in table_block_columns { + let row_info = row_info.entry((dbnum, block)).or_default(); + row_info.insert( + colnum, + ColumnType::Single { + datatype: datatype.parse().unwrap_or(DataType::Null), + nullable: Some(!notnull), + }, + ); + } + + Ok(row_info) +} + +struct Sequence(i64); + +impl Sequence { + pub fn new() -> Self { + Self(0) + } + pub fn next(&mut self) -> i64 { + let curr = self.0; + self.0 += 1; + curr + } +} + +#[derive(Debug)] +struct QueryState { + // The number of times each instruction has been visited + pub visited: Vec, + // A unique identifier of the query branch + pub branch_id: i64, + // How many instructions have been executed on this branch (NOT the same as program_i, which is the currently executing instruction of the program) + pub instruction_counter: i64, + // Parent branch this branch was forked from (if any) + pub branch_parent: Option, + // State of the virtual machine + pub mem: MemoryState, + // Results published by the execution + pub result: Option, Option)>>, +} + +impl From<&QueryState> for MemoryState { + fn from(val: &QueryState) -> Self { + val.mem.clone() + } +} + +impl From for MemoryState { + fn from(val: QueryState) -> Self { + val.mem + } +} + +impl From<&QueryState> for BranchParent { + fn from(val: &QueryState) -> Self { + Self { + id: val.branch_id, + idx: val.instruction_counter, + } + } +} + +impl QueryState { + fn get_reference(&self) -> BranchParent { + BranchParent { + id: self.branch_id, + idx: self.instruction_counter, + } + } + fn new_branch(&self, branch_seq: &mut Sequence) -> Self { + Self { + visited: self.visited.clone(), + branch_id: branch_seq.next(), + instruction_counter: 0, + branch_parent: Some(BranchParent { + id: self.branch_id, + idx: self.instruction_counter - 1, //instruction counter is incremented at the start of processing an instruction, so need to subtract 1 to get the 'current' instruction + }), + mem: self.mem.clone(), + result: self.result.clone(), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +struct MemoryState { + // Next instruction to execute + pub program_i: usize, + // Registers + pub r: IntMap, + // Rows that pointers point to + pub p: IntMap, + // Table definitions pointed to by pointers + pub t: IntMap, +} + +impl DebugDiff for MemoryState { + fn diff(&self, prev: &Self) -> String { + let r_diff = self.r.diff(&prev.r); + let p_diff = self.p.diff(&prev.p); + let t_diff = self.t.diff(&prev.t); + + let mut differences = String::new(); + for (i, v) in r_diff { + if !differences.is_empty() { + differences.push('\n'); + } + differences.push_str(&format!("r[{}]={:?}", i, v)) + } + for (i, v) in p_diff { + if !differences.is_empty() { + differences.push('\n'); + } + differences.push_str(&format!("p[{}]={:?}", i, v)) + } + for (i, v) in t_diff { + if !differences.is_empty() { + differences.push('\n'); + } + differences.push_str(&format!("t[{}]={:?}", i, v)) + } + differences + } +} + +struct BranchList { + states: Vec, + visited_branch_state: HashMap, +} + +impl BranchList { + pub fn new(state: QueryState) -> Self { + Self { + states: vec![state], + visited_branch_state: HashMap::new(), + } + } + pub fn push( + &mut self, + mut state: QueryState, + logger: &mut crate::logger::QueryPlanLogger<'_, R, MemoryState, P>, + ) { + logger.add_branch(&state, &state.branch_parent.unwrap()); + match self.visited_branch_state.entry(state.mem) { + hash_map::Entry::Vacant(entry) => { + //this state is not identical to another state, so it will need to be processed + state.mem = entry.key().clone(); //replace state.mem since .entry() moved it + entry.insert(state.get_reference()); + self.states.push(state); + } + hash_map::Entry::Occupied(entry) => { + //already saw a state identical to this one, so no point in processing it + state.mem = entry.key().clone(); //replace state.mem since .entry() moved it + logger.add_result(state, BranchResult::Dedup(*entry.get())); + } + } + } + pub fn pop(&mut self) -> Option { + self.states.pop() + } +} + +// Opcode Reference: https://sqlite.org/opcode.html +pub(super) fn explain( + conn: &mut ConnectionState, + query: &str, +) -> Result<(Vec, Vec>), Error> { + let root_block_cols = root_block_columns(conn)?; + let program: Vec<(i64, String, i64, i64, i64, Vec)> = + execute::iter(conn, AssertSqlSafe(format!("EXPLAIN {query}")), None, false)? + .filter_map(|res| res.map(|either| either.right()).transpose()) + .map(|row| FromRow::from_row(&row?)) + .collect::, Error>>()?; + let program_size = program.len(); + + let mut logger = crate::logger::QueryPlanLogger::new(query, &program); + let mut branch_seq = Sequence::new(); + let mut states = BranchList::new(QueryState { + visited: vec![0; program_size], + branch_id: branch_seq.next(), + branch_parent: None, + instruction_counter: 0, + result: None, + mem: MemoryState { + program_i: 0, + r: IntMap::new(), + t: IntMap::new(), + p: IntMap::new(), + }, + }); + + let mut gas = MAX_TOTAL_INSTRUCTION_COUNT; + let mut result_states = Vec::new(); + + while let Some(mut state) = states.pop() { + while state.mem.program_i < program_size { + let (_, ref opcode, p1, p2, p3, ref p4) = program[state.mem.program_i]; + + logger.add_operation(state.mem.program_i, &state); + state.instruction_counter += 1; + + //limit the number of 'instructions' that can be evaluated + if gas > 0 { + gas -= 1; + } else { + logger.add_result(state, BranchResult::GasLimit); + break; + } + + if state.visited[state.mem.program_i] > MAX_LOOP_COUNT { + logger.add_result(state, BranchResult::LoopLimit); + //avoid (infinite) loops by breaking if we ever hit the same instruction twice + break; + } + + state.visited[state.mem.program_i] += 1; + + match &**opcode { + OP_INIT => { + // start at + state.mem.program_i = p2 as usize; + continue; + } + + OP_GOTO => { + // goto + + state.mem.program_i = p2 as usize; + continue; + } + + OP_GO_SUB => { + // store current instruction in r[p1], goto + state + .mem + .r + .insert(p1, RegDataType::Int(state.mem.program_i as i64)); + state.mem.program_i = p2 as usize; + continue; + } + + OP_FK_IF_ZERO => { + // goto if no constraints are unsatisfied (assumed to be true) + + state.mem.program_i = p2 as usize; + continue; + } + + OP_DECR_JUMP_ZERO | OP_ELSE_EQ | OP_EQ | OP_FILTER | OP_FOUND | OP_GE | OP_GT + | OP_IDX_GE | OP_IDX_GT | OP_IDX_LE | OP_IDX_LT | OP_IF_NO_HOPE | OP_IF_NOT + | OP_IF_NOT_OPEN | OP_IF_NOT_ZERO | OP_IF_NULL_ROW | OP_IF_SMALLER + | OP_INCR_VACUUM | OP_IS_NULL_OR_TYPE | OP_LE | OP_LT | OP_NE | OP_NEXT + | OP_NO_CONFLICT | OP_NOT_EXISTS | OP_ONCE | OP_PREV | OP_PROGRAM + | OP_ROW_SET_READ | OP_ROW_SET_TEST | OP_SEEK_GE | OP_SEEK_GT | OP_SEEK_LE + | OP_SEEK_LT | OP_SEEK_ROW_ID | OP_SEEK_SCAN | OP_SEQUENCE_TEST + | OP_SORTER_NEXT | OP_V_FILTER | OP_V_NEXT => { + // goto or next instruction (depending on actual values) + + let mut branch_state = state.new_branch(&mut branch_seq); + branch_state.mem.program_i = p2 as usize; + states.push(branch_state, &mut logger); + + state.mem.program_i += 1; + continue; + } + + OP_IS_NULL => { + // goto if p1 is null + + //branch if maybe null + let might_branch = match state.mem.r.get(&p1) { + Some(r_p1) => !matches!(r_p1.map_to_nullable(), Some(false)), + _ => false, + }; + + //nobranch if maybe not null + let might_not_branch = match state.mem.r.get(&p1) { + Some(r_p1) => r_p1.map_to_nullable() != Some(false), + _ => false, + }; + + if might_branch { + let mut branch_state = state.new_branch(&mut branch_seq); + branch_state.mem.program_i = p2 as usize; + branch_state + .mem + .r + .insert(p1, RegDataType::Single(ColumnType::default())); + + states.push(branch_state, &mut logger); + } + + if might_not_branch { + state.mem.program_i += 1; + if let Some(RegDataType::Single(ColumnType::Single { nullable, .. })) = + state.mem.r.get_mut(&p1) + { + *nullable = Some(false); + } + continue; + } else { + logger.add_result(state, BranchResult::Branched); + break; + } + } + + OP_NOT_NULL => { + // goto if p1 is not null + + let might_branch = match state.mem.r.get(&p1) { + Some(r_p1) => !matches!(r_p1.map_to_datatype(), DataType::Null), + _ => false, + }; + + let might_not_branch = match state.mem.r.get(&p1) { + Some(r_p1) => !matches!(r_p1.map_to_nullable(), Some(false)), + _ => false, + }; + + if might_branch { + let mut branch_state = state.new_branch(&mut branch_seq); + branch_state.mem.program_i = p2 as usize; + if let Some(RegDataType::Single(ColumnType::Single { nullable, .. })) = + branch_state.mem.r.get_mut(&p1) + { + *nullable = Some(false); + } + + states.push(branch_state, &mut logger); + } + + if might_not_branch { + state.mem.program_i += 1; + state + .mem + .r + .insert(p1, RegDataType::Single(ColumnType::default())); + continue; + } else { + logger.add_result(state, BranchResult::Branched); + break; + } + } + + OP_MUST_BE_INT => { + // if p1 can be coerced to int, continue + // if p1 cannot be coerced to int, error if p2 == 0, else jump to p2 + + //don't bother checking actual types, just don't branch to instruction 0 + if p2 != 0 { + let mut branch_state = state.new_branch(&mut branch_seq); + branch_state.mem.program_i = p2 as usize; + states.push(branch_state, &mut logger); + } + + state.mem.program_i += 1; + continue; + } + + OP_IF => { + // goto if r[p1] is true (1) or r[p1] is null and p3 is nonzero + + let might_branch = match state.mem.r.get(&p1) { + Some(RegDataType::Int(r_p1)) => *r_p1 != 0, + _ => true, + }; + + let might_not_branch = match state.mem.r.get(&p1) { + Some(RegDataType::Int(r_p1)) => *r_p1 == 0, + _ => true, + }; + + if might_branch { + let mut branch_state = state.new_branch(&mut branch_seq); + branch_state.mem.program_i = p2 as usize; + if p3 == 0 { + branch_state.mem.r.insert(p1, RegDataType::Int(1)); + } + + states.push(branch_state, &mut logger); + } + + if might_not_branch { + state.mem.program_i += 1; + if p3 == 0 { + state.mem.r.insert(p1, RegDataType::Int(0)); + } + continue; + } else { + logger.add_result(state, BranchResult::Branched); + break; + } + } + + OP_IF_POS => { + // goto if r[p1] is true (1) or r[p1] is null and p3 is nonzero + + // as a workaround for large offset clauses, both branches will be attempted after 1 loop + + let might_branch = match state.mem.r.get(&p1) { + Some(RegDataType::Int(r_p1)) => *r_p1 >= 1, + _ => true, + }; + + let might_not_branch = match state.mem.r.get(&p1) { + Some(RegDataType::Int(r_p1)) => *r_p1 < 1, + _ => true, + }; + + let loop_detected = state.visited[state.mem.program_i] > 1; + if might_branch || loop_detected { + let mut branch_state = state.new_branch(&mut branch_seq); + branch_state.mem.program_i = p2 as usize; + if let Some(RegDataType::Int(r_p1)) = branch_state.mem.r.get_mut(&p1) { + *r_p1 -= 1; + } + states.push(branch_state, &mut logger); + } + + if might_not_branch { + state.mem.program_i += 1; + continue; + } else if loop_detected { + state.mem.program_i += 1; + if matches!(state.mem.r.get_mut(&p1), Some(RegDataType::Int(..))) { + //forget the exact value, in case some later cares + state.mem.r.insert( + p1, + RegDataType::Single(ColumnType::Single { + datatype: DataType::Integer, + nullable: Some(false), + }), + ); + } + continue; + } else { + logger.add_result(state, BranchResult::Branched); + break; + } + } + + OP_REWIND | OP_LAST | OP_SORT | OP_SORTER_SORT => { + // goto if cursor p1 is empty and p2 != 0, else next instruction + + if p2 == 0 { + state.mem.program_i += 1; + continue; + } + + if let Some(cursor) = state.mem.p.get(&p1) { + if matches!(cursor.is_empty(&state.mem.t), None | Some(true)) { + //only take this branch if the cursor is empty + + let mut branch_state = state.new_branch(&mut branch_seq); + branch_state.mem.program_i = p2 as usize; + + if let Some(cur) = branch_state.mem.p.get(&p1) { + if let Some(tab) = cur.table_mut(&mut branch_state.mem.t) { + tab.is_empty = Some(true); + } + } + states.push(branch_state, &mut logger); + } + + if matches!(cursor.is_empty(&state.mem.t), None | Some(false)) { + //only take this branch if the cursor is non-empty + state.mem.program_i += 1; + continue; + } else { + logger.add_result(state, BranchResult::Branched); + break; + } + } + + logger.add_result(state, BranchResult::Branched); + break; + } + + OP_INIT_COROUTINE => { + // goto or next instruction (depending on actual values) + + state.mem.r.insert(p1, RegDataType::Int(p3)); + + if p2 != 0 { + state.mem.program_i = p2 as usize; + } else { + state.mem.program_i += 1; + } + continue; + } + + OP_END_COROUTINE => { + // jump to p2 of the yield instruction pointed at by register p1 + + if let Some(RegDataType::Int(yield_i)) = state.mem.r.get(&p1) { + if let Some((_, yield_op, _, yield_p2, _, _)) = + program.get(*yield_i as usize) + { + if OP_YIELD == yield_op.as_str() { + state.mem.program_i = (*yield_p2) as usize; + state.mem.r.remove(&p1); + continue; + } else { + logger.add_result(state, BranchResult::Error); + break; + } + } else { + logger.add_result(state, BranchResult::Error); + break; + } + } else { + logger.add_result(state, BranchResult::Error); + break; + } + } + + OP_RETURN => { + // jump to the instruction after the instruction pointed at by register p1 + + if let Some(RegDataType::Int(return_i)) = state.mem.r.get(&p1) { + state.mem.program_i = (*return_i + 1) as usize; + state.mem.r.remove(&p1); + continue; + } else if p3 == 1 { + state.mem.program_i += 1; + continue; + } else { + logger.add_result(state, BranchResult::Error); + break; + } + } + + OP_YIELD => { + // jump to p2 of the yield instruction pointed at by register p1, store prior instruction in p1 + + if let Some(RegDataType::Int(yield_i)) = state.mem.r.get_mut(&p1) { + let program_i: usize = state.mem.program_i; + + //if yielding to a yield operation, go to the NEXT instruction after that instruction + if program + .get(*yield_i as usize) + .map(|(_, yield_op, _, _, _, _)| yield_op.as_str()) + == Some(OP_YIELD) + { + state.mem.program_i = (*yield_i + 1) as usize; + *yield_i = program_i as i64; + continue; + } else { + state.mem.program_i = *yield_i as usize; + *yield_i = program_i as i64; + continue; + } + } else { + logger.add_result(state, BranchResult::Error); + break; + } + } + + OP_JUMP => { + // goto one of , , or based on the result of a prior compare + + let mut branch_state = state.new_branch(&mut branch_seq); + branch_state.mem.program_i = p1 as usize; + states.push(branch_state, &mut logger); + + let mut branch_state = state.new_branch(&mut branch_seq); + branch_state.mem.program_i = p2 as usize; + states.push(branch_state, &mut logger); + + let mut branch_state = state.new_branch(&mut branch_seq); + branch_state.mem.program_i = p3 as usize; + states.push(branch_state, &mut logger); + } + + OP_COLUMN => { + //Get the row stored at p1, or NULL; get the column stored at p2, or NULL + let value: ColumnType = state + .mem + .p + .get(&p1) + .and_then(|c| c.columns_ref(&state.mem.t, &state.mem.r)) + .and_then(|cc| cc.get(&p2)) + .cloned() + .unwrap_or_default(); + + // insert into p3 the datatype of the col + state.mem.r.insert(p3, RegDataType::Single(value)); + } + + OP_SEQUENCE => { + //Copy sequence number from cursor p1 to register p2, increment cursor p1 sequence number + + //Cursor emulation doesn't sequence value, but it is an int + state.mem.r.insert( + p2, + RegDataType::Single(ColumnType::Single { + datatype: DataType::Integer, + nullable: Some(false), + }), + ); + } + + OP_ROW_DATA | OP_SORTER_DATA => { + //Get entire row from cursor p1, store it into register p2 + if let Some(record) = state + .mem + .p + .get(&p1) + .map(|c| c.columns(&state.mem.t, &state.mem.r)) + { + state + .mem + .r + .insert(p2, RegDataType::Single(ColumnType::Record(record))); + } else { + state + .mem + .r + .insert(p2, RegDataType::Single(ColumnType::Record(IntMap::new()))); + } + } + + OP_MAKE_RECORD => { + // p3 = Record([p1 .. p1 + p2]) + let mut record = Vec::with_capacity(p2 as usize); + for reg in p1..p1 + p2 { + record.push( + state + .mem + .r + .get(®) + .map(|d| d.map_to_columntype()) + .unwrap_or(ColumnType::default()), + ); + } + state.mem.r.insert( + p3, + RegDataType::Single(ColumnType::Record(IntMap::from_dense_record(&record))), + ); + } + + OP_INSERT | OP_IDX_INSERT | OP_SORTER_INSERT => { + if let Some(RegDataType::Single(columntype)) = state.mem.r.get(&p2) { + match columntype { + ColumnType::Record(record) => { + if let Some(TableDataType { cols, is_empty }) = state + .mem + .p + .get(&p1) + .and_then(|cur| cur.table_mut(&mut state.mem.t)) + { + // Insert the record into wherever pointer p1 is + *cols = record.clone(); + *is_empty = Some(false); + } + } + ColumnType::Single { + datatype: DataType::Null, + nullable: _, + } => { + if let Some(TableDataType { is_empty, .. }) = state + .mem + .p + .get(&p1) + .and_then(|cur| cur.table_mut(&mut state.mem.t)) + { + // Insert a null record into wherever pointer p1 is + *is_empty = Some(false); + } + } + _ => {} + } + } + //Noop if the register p2 isn't a record, or if pointer p1 does not exist + } + + OP_DELETE => { + // delete a record from cursor p1 + if let Some(TableDataType { is_empty, .. }) = state + .mem + .p + .get(&p1) + .and_then(|cur| cur.table_mut(&mut state.mem.t)) + { + if *is_empty == Some(false) { + *is_empty = None; //the cursor might be empty now + } + } + } + + OP_OPEN_PSEUDO => { + // Create a cursor p1 aliasing the record from register p2 + state.mem.p.insert(p1, CursorDataType::Pseudo(p2)); + } + + OP_OPEN_DUP => { + if let Some(cur) = state.mem.p.get(&p2) { + state.mem.p.insert(p1, cur.clone()); + } + } + + OP_OPEN_READ | OP_OPEN_WRITE => { + //Create a new pointer which is referenced by p1, take column metadata from db schema if found + let table_info = if p3 == 0 || p3 == 1 { + if let Some(columns) = root_block_cols.get(&(p3, p2)) { + TableDataType { + cols: columns.clone(), + is_empty: None, + } + } else { + TableDataType { + cols: IntMap::new(), + is_empty: None, + } + } + } else { + TableDataType { + cols: IntMap::new(), + is_empty: None, + } + }; + + state.mem.t.insert(state.mem.program_i as i64, table_info); + state + .mem + .p + .insert(p1, CursorDataType::Normal(state.mem.program_i as i64)); + } + + OP_OPEN_EPHEMERAL | OP_OPEN_AUTOINDEX | OP_SORTER_OPEN => { + //Create a new pointer which is referenced by p1 + let table_info = TableDataType { + cols: IntMap::from_elem(ColumnType::null(), p2 as usize), + is_empty: Some(true), + }; + + state.mem.t.insert(state.mem.program_i as i64, table_info); + state + .mem + .p + .insert(p1, CursorDataType::Normal(state.mem.program_i as i64)); + } + + OP_VARIABLE => { + // r[p2] = + state + .mem + .r + .insert(p2, RegDataType::Single(ColumnType::null())); + } + + // if there is a value in p3, and the query passes, then + // we know that it is not nullable + OP_HALT_IF_NULL => { + if let Some(RegDataType::Single(ColumnType::Single { nullable, .. })) = + state.mem.r.get_mut(&p3) + { + *nullable = Some(false); + } + } + + OP_FUNCTION => { + // r[p3] = func( _ ), registered function name is in p4 + match from_utf8(p4).map_err(Error::protocol)? { + "last_insert_rowid(0)" => { + // last_insert_rowid() -> INTEGER + state.mem.r.insert( + p3, + RegDataType::Single(ColumnType::Single { + datatype: DataType::Integer, + nullable: Some(false), + }), + ); + } + "date(-1)" | "time(-1)" | "datetime(-1)" | "strftime(-1)" => { + // date|time|datetime|strftime(...) -> TEXT + state.mem.r.insert( + p3, + RegDataType::Single(ColumnType::Single { + datatype: DataType::Text, + nullable: Some(p2 != 0), //never a null result if no argument provided + }), + ); + } + "julianday(-1)" => { + // julianday(...) -> REAL + state.mem.r.insert( + p3, + RegDataType::Single(ColumnType::Single { + datatype: DataType::Float, + nullable: Some(p2 != 0), //never a null result if no argument provided + }), + ); + } + "unixepoch(-1)" => { + // unixepoch(p2...) -> INTEGER + state.mem.r.insert( + p3, + RegDataType::Single(ColumnType::Single { + datatype: DataType::Integer, + nullable: Some(p2 != 0), //never a null result if no argument provided + }), + ); + } + + _ => logger.add_unknown_operation(state.mem.program_i), + } + } + + OP_NULL_ROW => { + // all columns in cursor X are potentially nullable + if let Some(cols) = state + .mem + .p + .get_mut(&p1) + .and_then(|c| c.columns_mut(&mut state.mem.t, &mut state.mem.r)) + { + for col in cols.values_mut() { + if let ColumnType::Single { + ref mut nullable, .. + } = col + { + *nullable = Some(true); + } + } + } + //else we don't know about the cursor + } + + OP_AGG_STEP | OP_AGG_VALUE => { + //assume that AGG_FINAL will be called + let p4 = from_utf8(p4).map_err(Error::protocol)?; + + if p4.starts_with("count(") + || p4.starts_with("row_number(") + || p4.starts_with("rank(") + || p4.starts_with("dense_rank(") + || p4.starts_with("ntile(") + { + // count(_) -> INTEGER + state.mem.r.insert( + p3, + RegDataType::Single(ColumnType::Single { + datatype: DataType::Integer, + nullable: Some(false), + }), + ); + } else if p4.starts_with("percent_rank(") || p4.starts_with("cume_dist") { + // percent_rank(_) -> REAL + state.mem.r.insert( + p3, + RegDataType::Single(ColumnType::Single { + datatype: DataType::Float, + nullable: Some(false), + }), + ); + } else if p4.starts_with("sum(") { + if let Some(r_p2) = state.mem.r.get(&p2) { + let datatype = match r_p2.map_to_datatype() { + // The result of a `SUM()` can be arbitrarily large + DataType::Integer | DataType::Int4 | DataType::Bool => { + DataType::Integer + } + _ => DataType::Float, + }; + let nullable = r_p2.map_to_nullable(); + state.mem.r.insert( + p3, + RegDataType::Single(ColumnType::Single { datatype, nullable }), + ); + } + } else if p4.starts_with("lead(") || p4.starts_with("lag(") { + if let Some(r_p2) = state.mem.r.get(&p2) { + let datatype = r_p2.map_to_datatype(); + state.mem.r.insert( + p3, + RegDataType::Single(ColumnType::Single { + datatype, + nullable: Some(true), + }), + ); + } + } else if let Some(v) = state.mem.r.get(&p2).cloned() { + // r[p3] = AGG ( r[p2] ) + state.mem.r.insert(p3, v); + } + } + + OP_AGG_FINAL => { + let p4 = from_utf8(p4).map_err(Error::protocol)?; + + if p4.starts_with("count(") + || p4.starts_with("row_number(") + || p4.starts_with("rank(") + || p4.starts_with("dense_rank(") + || p4.starts_with("ntile(") + { + // count(_) -> INTEGER + state.mem.r.insert( + p1, + RegDataType::Single(ColumnType::Single { + datatype: DataType::Integer, + nullable: Some(false), + }), + ); + } else if p4.starts_with("percent_rank(") || p4.starts_with("cume_dist") { + // percent_rank(_) -> REAL + state.mem.r.insert( + p3, + RegDataType::Single(ColumnType::Single { + datatype: DataType::Float, + nullable: Some(false), + }), + ); + } else if p4.starts_with("lead(") || p4.starts_with("lag(") { + if let Some(r_p2) = state.mem.r.get(&p2) { + let datatype = r_p2.map_to_datatype(); + state.mem.r.insert( + p3, + RegDataType::Single(ColumnType::Single { + datatype, + nullable: Some(true), + }), + ); + } + } + } + + OP_CAST => { + // affinity(r[p1]) + if let Some(v) = state.mem.r.get_mut(&p1) { + *v = RegDataType::Single(ColumnType::Single { + datatype: affinity_to_type(p2 as u8), + nullable: v.map_to_nullable(), + }); + } + } + + OP_SCOPY | OP_INT_COPY => { + // r[p2] = r[p1] + if let Some(v) = state.mem.r.get(&p1).cloned() { + state.mem.r.insert(p2, v); + } + } + + OP_COPY => { + // r[p2..=p2+p3] = r[p1..=p1+p3] + if p3 >= 0 { + for i in 0..=p3 { + let src = p1 + i; + let dst = p2 + i; + if let Some(v) = state.mem.r.get(&src).cloned() { + state.mem.r.insert(dst, v); + } + } + } + } + + OP_MOVE => { + // r[p2..p2+p3] = r[p1..p1+p3]; r[p1..p1+p3] = null + if p3 >= 1 { + for i in 0..p3 { + let src = p1 + i; + let dst = p2 + i; + if let Some(v) = state.mem.r.get(&src).cloned() { + state.mem.r.insert(dst, v); + state + .mem + .r + .insert(src, RegDataType::Single(ColumnType::null())); + } + } + } + } + + OP_INTEGER => { + // r[p2] = p1 + state.mem.r.insert(p2, RegDataType::Int(p1)); + } + + OP_BLOB | OP_COUNT | OP_REAL | OP_STRING8 | OP_ROWID | OP_IDX_ROWID + | OP_NEWROWID => { + // r[p2] = + state.mem.r.insert( + p2, + RegDataType::Single(ColumnType::Single { + datatype: opcode_to_type(opcode), + nullable: Some(false), + }), + ); + } + + OP_NOT => { + // r[p2] = NOT r[p1] + if let Some(a) = state.mem.r.get(&p1).cloned() { + state.mem.r.insert(p2, a); + } + } + + OP_NULL => { + // r[p2..p3] = null + let idx_range = if p2 < p3 { p2..=p3 } else { p2..=p2 }; + + for idx in idx_range { + state + .mem + .r + .insert(idx, RegDataType::Single(ColumnType::null())); + } + } + + OP_OR | OP_AND | OP_BIT_AND | OP_BIT_OR | OP_SHIFT_LEFT | OP_SHIFT_RIGHT + | OP_ADD | OP_SUBTRACT | OP_MULTIPLY | OP_DIVIDE | OP_REMAINDER | OP_CONCAT => { + // r[p3] = r[p1] + r[p2] + let value = match (state.mem.r.get(&p1), state.mem.r.get(&p2)) { + (Some(a), Some(b)) => RegDataType::Single(ColumnType::Single { + datatype: if matches!(a.map_to_datatype(), DataType::Null) { + b.map_to_datatype() + } else { + a.map_to_datatype() + }, + nullable: match (a.map_to_nullable(), b.map_to_nullable()) { + (Some(a_n), Some(b_n)) => Some(a_n | b_n), + (Some(a_n), None) => Some(a_n), + (None, Some(b_n)) => Some(b_n), + (None, None) => None, + }, + }), + (Some(v), None) => RegDataType::Single(ColumnType::Single { + datatype: v.map_to_datatype(), + nullable: None, + }), + (None, Some(v)) => RegDataType::Single(ColumnType::Single { + datatype: v.map_to_datatype(), + nullable: None, + }), + _ => RegDataType::default(), + }; + + state.mem.r.insert(p3, value); + } + + OP_OFFSET_LIMIT => { + // r[p2] = if r[p2] < 0 { r[p1] } else if r[p1]<0 { -1 } else { r[p1] + r[p3] } + state.mem.r.insert( + p2, + RegDataType::Single(ColumnType::Single { + datatype: DataType::Integer, + nullable: Some(false), + }), + ); + } + + OP_RESULT_ROW => { + // output = r[p1 .. p1 + p2] + let result: Vec<_> = (p1..p1 + p2) + .map(|i| { + state + .mem + .r + .get(&i) + .map(RegDataType::map_to_columntype) + .unwrap_or_default() + }) + .collect(); + + let mut branch_state = state.new_branch(&mut branch_seq); + branch_state.mem.program_i += 1; + states.push(branch_state, &mut logger); + + logger.add_result( + state, + BranchResult::Result(IntMap::from_dense_record(&result)), + ); + + result_states.push(result); + break; + } + + OP_HALT => { + logger.add_result(state, BranchResult::Halt); + break; + } + + _ => { + // ignore unsupported operations + // if we fail to find an r later, we just give up + logger.add_unknown_operation(state.mem.program_i); + } + } + + state.mem.program_i += 1; + } + } + + let mut output: Vec> = Vec::new(); + let mut nullable: Vec> = Vec::new(); + + while let Some(result) = result_states.pop() { + // find the datatype info from each ResultRow execution + for (idx, this_col) in result.into_iter().enumerate() { + let this_type = this_col.map_to_datatype(); + let this_nullable = this_col.map_to_nullable(); + if output.len() == idx { + output.push(Some(SqliteTypeInfo(this_type))); + } else if output[idx].is_none() + || matches!(output[idx], Some(SqliteTypeInfo(DataType::Null))) + && !matches!(this_type, DataType::Null) + { + output[idx] = Some(SqliteTypeInfo(this_type)); + } + + if nullable.len() == idx { + nullable.push(this_nullable); + } else if let Some(ref mut null) = nullable[idx] { + //if any ResultRow's column is nullable, the final result is nullable + if let Some(this_null) = this_nullable { + *null |= this_null; + } + } else { + nullable[idx] = this_nullable; + } + } + } + + let output = output + .into_iter() + .map(|o| o.unwrap_or(SqliteTypeInfo(DataType::Null))) + .collect(); + + Ok((output, nullable)) +} + +#[test] +fn test_root_block_columns_has_types() { + use crate::SqliteConnectOptions; + use std::str::FromStr; + let conn_options = SqliteConnectOptions::from_str("sqlite::memory:").unwrap(); + let mut conn = super::EstablishParams::from_options(&conn_options) + .unwrap() + .establish() + .unwrap(); + + assert!(execute::iter( + &mut conn, + r"CREATE TABLE t(a INTEGER PRIMARY KEY, b_null TEXT NULL, b TEXT NOT NULL);", + None, + false + ) + .unwrap() + .next() + .is_some()); + assert!( + execute::iter(&mut conn, r"CREATE INDEX i1 on t (a,b_null);", None, false) + .unwrap() + .next() + .is_some() + ); + assert!(execute::iter( + &mut conn, + r"CREATE UNIQUE INDEX i2 on t (a,b_null);", + None, + false + ) + .unwrap() + .next() + .is_some()); + assert!(execute::iter( + &mut conn, + r"CREATE TABLE t2(a INTEGER NOT NULL, b_null NUMERIC NULL, b NUMERIC NOT NULL);", + None, + false + ) + .unwrap() + .next() + .is_some()); + assert!(execute::iter( + &mut conn, + r"CREATE INDEX t2i1 on t2 (a,b_null);", + None, + false + ) + .unwrap() + .next() + .is_some()); + assert!(execute::iter( + &mut conn, + r"CREATE UNIQUE INDEX t2i2 on t2 (a,b);", + None, + false + ) + .unwrap() + .next() + .is_some()); + + assert!(execute::iter( + &mut conn, + r"CREATE TEMPORARY TABLE t3(a TEXT PRIMARY KEY, b REAL NOT NULL, b_null REAL NULL);", + None, + false + ) + .unwrap() + .next() + .is_some()); + + let table_block_nums: HashMap = execute::iter( + &mut conn, + r"select name, 0 db_seq, rootpage from main.sqlite_schema UNION ALL select name, 1 db_seq, rootpage from temp.sqlite_schema", + None, + false, + ) + .unwrap() + .filter_map(|res| res.map(|either| either.right()).transpose()) + .map(|row| FromRow::from_row(row.as_ref().unwrap())) + .map(|row| row.map(|(name,seq,block)|(name,(seq,block)))) + .collect::, Error>>() + .unwrap(); + + let root_block_cols = root_block_columns(&mut conn).unwrap(); + + // there should be 7 tables/indexes created explicitly, plus 1 autoindex for t3 + assert_eq!(8, root_block_cols.len()); + + //prove that we have some information for each table & index + for (name, db_seq_block) in dbg!(&table_block_nums) { + assert!( + root_block_cols.contains_key(db_seq_block), + "{:?}", + (name, db_seq_block) + ); + } + + //prove that each block has the correct information + { + let table_db_block = table_block_nums["t"]; + assert_eq!( + Some(&ColumnType::Single { + datatype: DataType::Integer, + nullable: Some(true) //sqlite primary key columns are nullable unless declared not null + }), + root_block_cols[&table_db_block].get(&0) + ); + assert_eq!( + Some(&ColumnType::Single { + datatype: DataType::Text, + nullable: Some(true) + }), + root_block_cols[&table_db_block].get(&1) + ); + assert_eq!( + Some(&ColumnType::Single { + datatype: DataType::Text, + nullable: Some(false) + }), + root_block_cols[&table_db_block].get(&2) + ); + } + + { + let table_db_block = table_block_nums["i1"]; + assert_eq!( + Some(&ColumnType::Single { + datatype: DataType::Integer, + nullable: Some(true) //sqlite primary key columns are nullable unless declared not null + }), + root_block_cols[&table_db_block].get(&0) + ); + assert_eq!( + Some(&ColumnType::Single { + datatype: DataType::Text, + nullable: Some(true) + }), + root_block_cols[&table_db_block].get(&1) + ); + } + + { + let table_db_block = table_block_nums["i2"]; + assert_eq!( + Some(&ColumnType::Single { + datatype: DataType::Integer, + nullable: Some(true) //sqlite primary key columns are nullable unless declared not null + }), + root_block_cols[&table_db_block].get(&0) + ); + assert_eq!( + Some(&ColumnType::Single { + datatype: DataType::Text, + nullable: Some(true) + }), + root_block_cols[&table_db_block].get(&1) + ); + } + + { + let table_db_block = table_block_nums["t2"]; + assert_eq!( + Some(&ColumnType::Single { + datatype: DataType::Integer, + nullable: Some(false) + }), + root_block_cols[&table_db_block].get(&0) + ); + assert_eq!( + Some(&ColumnType::Single { + datatype: DataType::Null, + nullable: Some(true) + }), + root_block_cols[&table_db_block].get(&1) + ); + assert_eq!( + Some(&ColumnType::Single { + datatype: DataType::Null, + nullable: Some(false) + }), + root_block_cols[&table_db_block].get(&2) + ); + } + + { + let table_db_block = table_block_nums["t2i1"]; + assert_eq!( + Some(&ColumnType::Single { + datatype: DataType::Integer, + nullable: Some(false) + }), + root_block_cols[&table_db_block].get(&0) + ); + assert_eq!( + Some(&ColumnType::Single { + datatype: DataType::Null, + nullable: Some(true) + }), + root_block_cols[&table_db_block].get(&1) + ); + } + + { + let table_db_block = table_block_nums["t2i2"]; + assert_eq!( + Some(&ColumnType::Single { + datatype: DataType::Integer, + nullable: Some(false) + }), + root_block_cols[&table_db_block].get(&0) + ); + assert_eq!( + Some(&ColumnType::Single { + datatype: DataType::Null, + nullable: Some(false) + }), + root_block_cols[&table_db_block].get(&1) + ); + } + + { + let table_db_block = table_block_nums["t3"]; + assert_eq!( + Some(&ColumnType::Single { + datatype: DataType::Text, + nullable: Some(true) + }), + root_block_cols[&table_db_block].get(&0) + ); + assert_eq!( + Some(&ColumnType::Single { + datatype: DataType::Float, + nullable: Some(false) + }), + root_block_cols[&table_db_block].get(&1) + ); + assert_eq!( + Some(&ColumnType::Single { + datatype: DataType::Float, + nullable: Some(true) + }), + root_block_cols[&table_db_block].get(&2) + ); + } +} + +#[test] +fn test_explain() { + use crate::SqliteConnectOptions; + use std::str::FromStr; + let conn_options = SqliteConnectOptions::from_str("sqlite::memory:").unwrap(); + let mut conn = super::EstablishParams::from_options(&conn_options) + .unwrap() + .establish() + .unwrap(); + + assert!(execute::iter( + &mut conn, + r"CREATE TABLE an_alias(a INTEGER PRIMARY KEY);", + None, + false + ) + .unwrap() + .next() + .is_some()); + + assert!(execute::iter( + &mut conn, + r"CREATE TABLE not_an_alias(a INT PRIMARY KEY);", + None, + false + ) + .unwrap() + .next() + .is_some()); + + assert!( + if let Ok((ty, nullable)) = explain(&mut conn, "SELECT * FROM an_alias") { + ty == [SqliteTypeInfo(DataType::Integer)] && nullable == [Some(false)] + } else { + false + } + ); + assert!( + if let Ok((ty, nullable)) = explain(&mut conn, "SELECT * FROM not_an_alias") { + ty == [SqliteTypeInfo(DataType::Integer)] && nullable == [Some(true)] + } else { + false + } + ); + assert!( + if let Ok((ty, nullable)) = explain(&mut conn, "SELECT rowid FROM an_alias") { + ty == [SqliteTypeInfo(DataType::Integer)] && nullable == [Some(false)] + } else { + false + } + ); + assert!( + if let Ok((ty, nullable)) = explain(&mut conn, "SELECT rowid FROM not_an_alias") { + ty == [SqliteTypeInfo(DataType::Integer)] && nullable == [Some(false)] + } else { + false + } + ); +} diff --git a/vendor/sqlx-sqlite/src/connection/handle.rs b/vendor/sqlx-sqlite/src/connection/handle.rs new file mode 100755 index 000000000000..e89179b30ed4 --- /dev/null +++ b/vendor/sqlx-sqlite/src/connection/handle.rs @@ -0,0 +1,151 @@ +use std::ffi::{c_int, CStr, CString}; +use std::ptr::NonNull; +use std::{io, ptr}; + +use crate::error::Error; +use libsqlite3_sys::{ + sqlite3, sqlite3_close, sqlite3_exec, sqlite3_extended_result_codes, sqlite3_get_autocommit, + sqlite3_last_insert_rowid, sqlite3_open_v2, SQLITE_OK, +}; + +use crate::SqliteError; + +/// Managed SQLite3 database handle. +/// The database handle will be closed when this is dropped. +#[derive(Debug)] +pub(crate) struct ConnectionHandle(NonNull); + +// A SQLite3 handle is safe to send between threads, provided not more than +// one is accessing it at the same time. This is upheld as long as [SQLITE_CONFIG_MULTITHREAD] is +// enabled and [SQLITE_THREADSAFE] was enabled when sqlite was compiled. We refuse to work +// if these conditions are not upheld. +// +// +// + +unsafe impl Send for ConnectionHandle {} + +impl ConnectionHandle { + pub(crate) fn open(filename: &CStr, flags: c_int) -> Result { + let mut handle = ptr::null_mut(); + + // + let status = unsafe { sqlite3_open_v2(filename.as_ptr(), &mut handle, flags, ptr::null()) }; + + // SAFETY: the database is still initialized as long as the pointer is not `NULL`. + // We need to close it even if there's an error. + let mut handle = Self(NonNull::new(handle).ok_or_else(|| { + Error::Io(io::Error::new( + io::ErrorKind::OutOfMemory, + "SQLite is unable to allocate memory to hold the sqlite3 object", + )) + })?); + + if status != SQLITE_OK { + return Err(Error::Database(Box::new(handle.expect_error()))); + } + + // Enable extended result codes + // https://www.sqlite.org/c3ref/extended_result_codes.html + unsafe { + // This only returns a non-OK code if SQLite is built with `SQLITE_ENABLE_API_ARMOR` + // and the database pointer is `NULL` or already closed. + // + // The invariants of this type guarantee that neither is true. + sqlite3_extended_result_codes(handle.as_ptr(), 1); + } + + Ok(handle) + } + + #[inline] + pub(crate) fn as_ptr(&self) -> *mut sqlite3 { + self.0.as_ptr() + } + + pub(crate) fn as_non_null_ptr(&self) -> NonNull { + self.0 + } + + pub(crate) fn call_with_result( + &mut self, + call: impl FnOnce(*mut sqlite3) -> c_int, + ) -> Result<(), SqliteError> { + let res = call(self.as_ptr()); + + if res == SQLITE_OK { + Ok(()) + } else { + Err(self + .last_error() + .unwrap_or_else(|| SqliteError::from_code(res))) + } + } + + pub(crate) fn in_transaction(&mut self) -> bool { + // SAFETY: we have exclusive access to the database handle + let ret = unsafe { sqlite3_get_autocommit(self.as_ptr()) }; + ret == 0 + } + + pub(crate) fn last_insert_rowid(&mut self) -> i64 { + // SAFETY: we have exclusive access to the database handle + unsafe { sqlite3_last_insert_rowid(self.as_ptr()) } + } + + pub(crate) fn last_error(&mut self) -> Option { + // SAFETY: we have exclusive access to the database handle + unsafe { SqliteError::try_new(self.as_ptr()) } + } + + #[track_caller] + pub(crate) fn expect_error(&mut self) -> SqliteError { + self.last_error() + .expect("expected error code to be set in current context") + } + + pub(crate) fn exec(&mut self, query: impl Into) -> Result<(), Error> { + let query = query.into(); + let query = CString::new(query).map_err(|_| err_protocol!("query contains nul bytes"))?; + + // SAFETY: we have exclusive access to the database handle + unsafe { + #[cfg_attr(not(feature = "unlock-notify"), expect(clippy::never_loop))] + loop { + let status = sqlite3_exec( + self.as_ptr(), + query.as_ptr(), + // callback if we wanted result rows + None, + // callback data + ptr::null_mut(), + // out-pointer for the error message, we just use `SqliteError::new()` + ptr::null_mut(), + ); + + match status { + SQLITE_OK => return Ok(()), + #[cfg(feature = "unlock-notify")] + libsqlite3_sys::SQLITE_LOCKED_SHAREDCACHE => { + crate::statement::unlock_notify::wait(self.as_ptr())? + } + _ => return Err(SqliteError::new(self.as_ptr()).into()), + } + } + } + } +} + +impl Drop for ConnectionHandle { + fn drop(&mut self) { + unsafe { + // https://sqlite.org/c3ref/close.html + let status = sqlite3_close(self.0.as_ptr()); + if status != SQLITE_OK { + // this should *only* happen due to an internal bug in SQLite where we left + // SQLite handles open + panic!("{}", SqliteError::new(self.0.as_ptr())); + } + } + } +} diff --git a/vendor/sqlx-sqlite/src/connection/intmap.rs b/vendor/sqlx-sqlite/src/connection/intmap.rs new file mode 100755 index 000000000000..f8308067ccf8 --- /dev/null +++ b/vendor/sqlx-sqlite/src/connection/intmap.rs @@ -0,0 +1,175 @@ +// Bad casts in this module SHOULD NOT result in a SQL injection +// https://github.com/launchbadge/sqlx/issues/3440 +#![allow( + clippy::cast_possible_truncation, + clippy::cast_possible_wrap, + clippy::cast_sign_loss +)] +use std::cmp::Ordering; +use std::{fmt::Debug, hash::Hash}; + +/// Simplistic map implementation built on a Vec of Options (index = key) +#[derive(Debug, Clone, Eq)] +pub(crate) struct IntMap(Vec>); + +impl Default for IntMap { + fn default() -> Self { + IntMap(Vec::new()) + } +} + +impl IntMap { + pub(crate) fn new() -> Self { + Self(Vec::new()) + } + + pub(crate) fn expand(&mut self, size: i64) -> usize { + let idx = usize::try_from(size).expect("negative column index unsupported"); + if idx >= self.0.len() { + let new_len = idx.checked_add(1).expect("idx + 1 overflowed"); + + self.0.resize_with(new_len, || None); + } + idx + } + + pub(crate) fn values_mut(&mut self) -> impl Iterator { + self.0.iter_mut().filter_map(Option::as_mut) + } + + pub(crate) fn values(&self) -> impl Iterator { + self.0.iter().filter_map(Option::as_ref) + } + + pub(crate) fn get(&self, idx: &i64) -> Option<&V> { + let idx: usize = (*idx) + .try_into() + .expect("negative column index unsupported"); + + match self.0.get(idx) { + Some(Some(v)) => Some(v), + _ => None, + } + } + + pub(crate) fn get_mut(&mut self, idx: &i64) -> Option<&mut V> { + let idx: usize = (*idx) + .try_into() + .expect("negative column index unsupported"); + match self.0.get_mut(idx) { + Some(Some(v)) => Some(v), + _ => None, + } + } + + pub(crate) fn insert(&mut self, idx: i64, value: V) -> Option { + let idx: usize = self.expand(idx); + + self.0[idx].replace(value) + } + + pub(crate) fn remove(&mut self, idx: &i64) -> Option { + let idx: usize = (*idx) + .try_into() + .expect("negative column index unsupported"); + + let item = self.0.get_mut(idx); + match item { + Some(content) => content.take(), + None => None, + } + } + + pub(crate) fn iter(&self) -> impl Iterator> { + self.0.iter().map(Option::as_ref) + } + + pub(crate) fn iter_entries(&self) -> impl Iterator { + self.0 + .iter() + .enumerate() + .filter_map(|(i, v)| v.as_ref().map(|v: &V| (i as i64, v))) + } + + pub(crate) fn last_index(&self) -> Option { + self.0.iter().rposition(|v| v.is_some()).map(|i| i as i64) + } +} + +impl IntMap { + pub(crate) fn get_mut_or_default(&mut self, idx: &i64) -> &mut V { + let idx: usize = self.expand(*idx); + self.0[idx].get_or_insert_default() + } +} + +impl IntMap { + pub(crate) fn from_elem(elem: V, len: usize) -> Self { + Self(vec![Some(elem); len]) + } + pub(crate) fn from_dense_record(record: &[V]) -> Self { + Self(record.iter().cloned().map(Some).collect()) + } +} + +impl IntMap { + /// get the additions to this intmap compared to the prev intmap + pub(crate) fn diff<'a, 'b, 'c>( + &'a self, + prev: &'b Self, + ) -> impl Iterator)> + where + 'a: 'c, + 'b: 'c, + { + let self_pad = if prev.0.len() > self.0.len() { + prev.0.len() - self.0.len() + } else { + 0 + }; + self.iter() + .chain(std::iter::repeat_n(None, self_pad)) + .zip(prev.iter().chain(std::iter::repeat(None))) + .enumerate() + .filter(|(_i, (n, p))| n != p) + .map(|(i, (n, _p))| (i, n)) + } +} + +impl Hash for IntMap { + fn hash(&self, state: &mut H) { + for value in self.values() { + value.hash(state); + } + } +} + +impl PartialEq for IntMap { + fn eq(&self, other: &Self) -> bool { + match self.0.len().cmp(&other.0.len()) { + Ordering::Greater => { + self.0[..other.0.len()] == other.0 + && self.0[other.0.len()..].iter().all(Option::is_none) + } + Ordering::Less => { + other.0[..self.0.len()] == self.0 + && other.0[self.0.len()..].iter().all(Option::is_none) + } + Ordering::Equal => self.0 == other.0, + } + } +} + +impl FromIterator<(i64, V)> for IntMap { + fn from_iter(iter: I) -> Self + where + I: IntoIterator, + { + let mut result = Self(Vec::new()); + for (idx, val) in iter { + let idx = result.expand(idx); + result.0[idx] = Some(val); + } + result + } +} diff --git a/vendor/sqlx-sqlite/src/connection/mod.rs b/vendor/sqlx-sqlite/src/connection/mod.rs new file mode 100755 index 000000000000..218c747143fe --- /dev/null +++ b/vendor/sqlx-sqlite/src/connection/mod.rs @@ -0,0 +1,599 @@ +use std::cmp::Ordering; +use std::ffi::CStr; +use std::fmt::Write; +use std::fmt::{self, Debug, Formatter}; +use std::future::Future; +use std::os::raw::{c_char, c_int, c_void}; +use std::panic::catch_unwind; +use std::ptr; +use std::ptr::NonNull; + +use futures_intrusive::sync::MutexGuard; +use libsqlite3_sys::{ + sqlite3, sqlite3_commit_hook, sqlite3_progress_handler, sqlite3_rollback_hook, + sqlite3_update_hook, SQLITE_DELETE, SQLITE_INSERT, SQLITE_UPDATE, +}; +#[cfg(feature = "preupdate-hook")] +pub use preupdate_hook::*; + +pub(crate) use handle::ConnectionHandle; +use sqlx_core::common::StatementCache; +pub(crate) use sqlx_core::connection::*; +use sqlx_core::error::Error; +use sqlx_core::executor::Executor; +use sqlx_core::sql_str::{AssertSqlSafe, SqlSafeStr}; +use sqlx_core::transaction::Transaction; + +use crate::connection::establish::EstablishParams; +use crate::connection::worker::ConnectionWorker; +use crate::options::OptimizeOnClose; +use crate::statement::VirtualStatement; +use crate::{Sqlite, SqliteConnectOptions, SqliteError}; + +pub(crate) mod collation; +pub(crate) mod describe; +pub(crate) mod establish; +pub(crate) mod execute; +mod executor; +mod explain; +mod handle; +pub(crate) mod intmap; +#[cfg(feature = "preupdate-hook")] +mod preupdate_hook; + +#[cfg(feature = "deserialize")] +pub(crate) mod deserialize; + +mod worker; + +/// A connection to an open [Sqlite] database. +/// +/// Because SQLite is an in-process database accessed by blocking API calls, SQLx uses a background +/// thread and communicates with it via channels to allow non-blocking access to the database. +/// +/// Dropping this struct will signal the worker thread to quit and close the database, though +/// if an error occurs there is no way to pass it back to the user this way. +/// +/// You can explicitly call [`.close()`][Self::close] to ensure the database is closed successfully +/// or get an error otherwise. +pub struct SqliteConnection { + optimize_on_close: OptimizeOnClose, + pub(crate) worker: ConnectionWorker, + pub(crate) row_channel_size: usize, +} + +pub struct LockedSqliteHandle<'a> { + pub(crate) guard: MutexGuard<'a, ConnectionState>, +} + +/// Represents a callback handler that will be shared with the underlying sqlite3 connection. +pub(crate) struct Handler(NonNull bool + Send + 'static>); +unsafe impl Send for Handler {} + +#[derive(Debug, PartialEq, Eq, Clone)] +pub enum SqliteOperation { + Insert, + Update, + Delete, + Unknown(i32), +} + +impl From for SqliteOperation { + fn from(value: i32) -> Self { + match value { + SQLITE_INSERT => SqliteOperation::Insert, + SQLITE_UPDATE => SqliteOperation::Update, + SQLITE_DELETE => SqliteOperation::Delete, + code => SqliteOperation::Unknown(code), + } + } +} + +pub struct UpdateHookResult<'a> { + pub operation: SqliteOperation, + pub database: &'a str, + pub table: &'a str, + pub rowid: i64, +} + +pub(crate) struct UpdateHookHandler(NonNull); +unsafe impl Send for UpdateHookHandler {} + +pub(crate) struct CommitHookHandler(NonNull bool + Send + 'static>); +unsafe impl Send for CommitHookHandler {} + +pub(crate) struct RollbackHookHandler(NonNull); +unsafe impl Send for RollbackHookHandler {} + +pub(crate) struct ConnectionState { + pub(crate) handle: ConnectionHandle, + + pub(crate) statements: Statements, + + log_settings: LogSettings, + + /// Stores the progress handler set on the current connection. If the handler returns `false`, + /// the query is interrupted. + progress_handler_callback: Option, + + update_hook_callback: Option, + #[cfg(feature = "preupdate-hook")] + preupdate_hook_callback: Option, + + commit_hook_callback: Option, + + rollback_hook_callback: Option, +} + +impl ConnectionState { + /// Drops the `progress_handler_callback` if it exists. + pub(crate) fn remove_progress_handler(&mut self) { + if let Some(mut handler) = self.progress_handler_callback.take() { + unsafe { + sqlite3_progress_handler(self.handle.as_ptr(), 0, None, ptr::null_mut()); + let _ = { Box::from_raw(handler.0.as_mut()) }; + } + } + } + + pub(crate) fn remove_update_hook(&mut self) { + if let Some(mut handler) = self.update_hook_callback.take() { + unsafe { + sqlite3_update_hook(self.handle.as_ptr(), None, ptr::null_mut()); + let _ = { Box::from_raw(handler.0.as_mut()) }; + } + } + } + + #[cfg(feature = "preupdate-hook")] + pub(crate) fn remove_preupdate_hook(&mut self) { + if let Some(mut handler) = self.preupdate_hook_callback.take() { + unsafe { + libsqlite3_sys::sqlite3_preupdate_hook(self.handle.as_ptr(), None, ptr::null_mut()); + let _ = { Box::from_raw(handler.0.as_mut()) }; + } + } + } + + pub(crate) fn remove_commit_hook(&mut self) { + if let Some(mut handler) = self.commit_hook_callback.take() { + unsafe { + sqlite3_commit_hook(self.handle.as_ptr(), None, ptr::null_mut()); + let _ = { Box::from_raw(handler.0.as_mut()) }; + } + } + } + + pub(crate) fn remove_rollback_hook(&mut self) { + if let Some(mut handler) = self.rollback_hook_callback.take() { + unsafe { + sqlite3_rollback_hook(self.handle.as_ptr(), None, ptr::null_mut()); + let _ = { Box::from_raw(handler.0.as_mut()) }; + } + } + } +} + +pub(crate) struct Statements { + // cache of semi-persistent statements + cached: StatementCache, + // most recent non-persistent statement + temp: Option, +} + +impl SqliteConnection { + pub(crate) async fn establish(options: &SqliteConnectOptions) -> Result { + let params = EstablishParams::from_options(options)?; + let worker = ConnectionWorker::establish(params).await?; + Ok(Self { + optimize_on_close: options.optimize_on_close.clone(), + worker, + row_channel_size: options.row_channel_size, + }) + } + + /// Lock the SQLite database handle out from the worker thread so direct SQLite API calls can + /// be made safely. + /// + /// Returns an error if the worker thread crashed. + pub async fn lock_handle(&mut self) -> Result, Error> { + let guard = self.worker.unlock_db().await?; + + Ok(LockedSqliteHandle { guard }) + } +} + +impl Debug for SqliteConnection { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.debug_struct("SqliteConnection") + .field("row_channel_size", &self.row_channel_size) + .field("cached_statements_size", &self.cached_statements_size()) + .finish() + } +} + +impl Connection for SqliteConnection { + type Database = Sqlite; + + type Options = SqliteConnectOptions; + + async fn close(mut self) -> Result<(), Error> { + if let OptimizeOnClose::Enabled { analysis_limit } = self.optimize_on_close { + let mut pragma_string = String::new(); + if let Some(limit) = analysis_limit { + write!(pragma_string, "PRAGMA analysis_limit = {limit}; ").ok(); + } + pragma_string.push_str("PRAGMA optimize;"); + self.execute(AssertSqlSafe(pragma_string)).await?; + } + let shutdown = self.worker.shutdown(); + // Drop the statement worker, which should + // cover all references to the connection handle outside of the worker thread + drop(self); + // Ensure the worker thread has terminated + shutdown.await + } + + async fn close_hard(self) -> Result<(), Error> { + drop(self); + Ok(()) + } + + /// Ensure the background worker thread is alive and accepting commands. + fn ping(&mut self) -> impl Future> + Send + '_ { + self.worker.ping() + } + + fn begin( + &mut self, + ) -> impl Future, Error>> + Send + '_ { + Transaction::begin(self, None) + } + + fn begin_with( + &mut self, + statement: impl SqlSafeStr, + ) -> impl Future, Error>> + Send + '_ + where + Self: Sized, + { + Transaction::begin(self, Some(statement.into_sql_str())) + } + + fn cached_statements_size(&self) -> usize { + self.worker.shared.get_cached_statements_size() + } + + fn clear_cached_statements(&mut self) -> impl Future> + Send + '_ { + self.worker.clear_cache() + } + + #[inline] + fn shrink_buffers(&mut self) { + // No-op. + } + + #[doc(hidden)] + async fn flush(&mut self) -> Result<(), Error> { + // For SQLite, FLUSH does effectively nothing... + // Well, we could use this to ensure that the command channel has been cleared, + // but it would only develop a backlog if a lot of queries are executed and then cancelled + // partway through, and then this would only make that situation worse. + Ok(()) + } + + #[doc(hidden)] + fn should_flush(&self) -> bool { + false + } +} + +/// Implements a C binding to a progress callback. The function returns `0` if the +/// user-provided callback returns `true`, and `1` otherwise to signal an interrupt. +extern "C" fn progress_callback(callback: *mut c_void) -> c_int +where + F: FnMut() -> bool, +{ + unsafe { + let r = catch_unwind(|| { + let callback: *mut F = callback.cast::(); + (*callback)() + }); + c_int::from(!r.unwrap_or_default()) + } +} + +extern "C" fn update_hook( + callback: *mut c_void, + op_code: c_int, + database: *const c_char, + table: *const c_char, + rowid: i64, +) where + F: FnMut(UpdateHookResult), +{ + unsafe { + let _ = catch_unwind(|| { + let callback: *mut F = callback.cast::(); + let operation: SqliteOperation = op_code.into(); + let database = CStr::from_ptr(database).to_str().unwrap_or_default(); + let table = CStr::from_ptr(table).to_str().unwrap_or_default(); + (*callback)(UpdateHookResult { + operation, + database, + table, + rowid, + }) + }); + } +} + +extern "C" fn commit_hook(callback: *mut c_void) -> c_int +where + F: FnMut() -> bool, +{ + unsafe { + let r = catch_unwind(|| { + let callback: *mut F = callback.cast::(); + (*callback)() + }); + c_int::from(!r.unwrap_or_default()) + } +} + +extern "C" fn rollback_hook(callback: *mut c_void) +where + F: FnMut(), +{ + unsafe { + let _ = catch_unwind(|| { + let callback: *mut F = callback.cast::(); + (*callback)() + }); + } +} + +impl LockedSqliteHandle<'_> { + /// Returns the underlying sqlite3* connection handle. + /// + /// As long as this `LockedSqliteHandle` exists, it is guaranteed that the background thread + /// is not making FFI calls on this database handle or any of its statements. + /// + /// ### Note: The `sqlite3` type is semver-exempt. + /// This API exposes the `sqlite3` type from `libsqlite3-sys` crate for type safety. + /// However, we reserve the right to upgrade `libsqlite3-sys` as necessary. + /// + /// Thus, if you are making direct calls via `libsqlite3-sys` you should pin the version + /// of SQLx that you're using, and upgrade it and `libsqlite3-sys` manually as new + /// versions are released. + /// + /// See [the driver root docs][crate] for details. + pub fn as_raw_handle(&mut self) -> NonNull { + self.guard.handle.as_non_null_ptr() + } + + /// Apply a collation to the open database. + /// + /// See [`SqliteConnectOptions::collation()`] for details. + pub fn create_collation( + &mut self, + name: &str, + compare: impl Fn(&str, &str) -> Ordering + Send + Sync + 'static, + ) -> Result<(), Error> { + collation::create_collation(&mut self.guard.handle, name, compare) + } + + /// Sets a progress handler that is invoked periodically during long running calls. If the progress callback + /// returns `false`, then the operation is interrupted. + /// + /// `num_ops` is the approximate number of [virtual machine instructions](https://www.sqlite.org/opcode.html) + /// that are evaluated between successive invocations of the callback. If `num_ops` is less than one then the + /// progress handler is disabled. + /// + /// Only a single progress handler may be defined at one time per database connection; setting a new progress + /// handler cancels the old one. + /// + /// The progress handler callback must not do anything that will modify the database connection that invoked + /// the progress handler. Note that sqlite3_prepare_v2() and sqlite3_step() both modify their database connections + /// in this context. + pub fn set_progress_handler(&mut self, num_ops: i32, callback: F) + where + F: FnMut() -> bool + Send + 'static, + { + unsafe { + let callback_boxed = Box::new(callback); + // SAFETY: `Box::into_raw()` always returns a non-null pointer. + let callback = NonNull::new_unchecked(Box::into_raw(callback_boxed)); + let handler = callback.as_ptr() as *mut _; + self.guard.remove_progress_handler(); + self.guard.progress_handler_callback = Some(Handler(callback)); + + sqlite3_progress_handler( + self.as_raw_handle().as_mut(), + num_ops, + Some(progress_callback::), + handler, + ); + } + } + + pub fn set_update_hook(&mut self, callback: F) + where + F: FnMut(UpdateHookResult) + Send + 'static, + { + unsafe { + let callback_boxed = Box::new(callback); + // SAFETY: `Box::into_raw()` always returns a non-null pointer. + let callback = NonNull::new_unchecked(Box::into_raw(callback_boxed)); + let handler = callback.as_ptr() as *mut _; + self.guard.remove_update_hook(); + self.guard.update_hook_callback = Some(UpdateHookHandler(callback)); + + sqlite3_update_hook( + self.as_raw_handle().as_mut(), + Some(update_hook::), + handler, + ); + } + } + + /// Registers a hook that is invoked prior to each `INSERT`, `UPDATE`, and `DELETE` operation on a database table. + /// At most one preupdate hook may be registered at a time on a single database connection. + /// + /// The preupdate hook only fires for changes to real database tables; + /// it is not invoked for changes to virtual tables or to system tables like sqlite_sequence or sqlite_stat1. + /// + /// See https://sqlite.org/c3ref/preupdate_count.html + #[cfg(feature = "preupdate-hook")] + pub fn set_preupdate_hook(&mut self, callback: F) + where + F: FnMut(PreupdateHookResult) + Send + 'static, + { + unsafe { + let callback_boxed = Box::new(callback); + // SAFETY: `Box::into_raw()` always returns a non-null pointer. + let callback = NonNull::new_unchecked(Box::into_raw(callback_boxed)); + let handler = callback.as_ptr() as *mut _; + self.guard.remove_preupdate_hook(); + self.guard.preupdate_hook_callback = Some(PreupdateHookHandler(callback)); + + libsqlite3_sys::sqlite3_preupdate_hook( + self.as_raw_handle().as_mut(), + Some(preupdate_hook::), + handler, + ); + } + } + + /// Sets a commit hook that is invoked whenever a transaction is committed. If the commit hook callback + /// returns `false`, then the operation is turned into a ROLLBACK. + /// + /// Only a single commit hook may be defined at one time per database connection; setting a new commit hook + /// overrides the old one. + /// + /// The commit hook callback must not do anything that will modify the database connection that invoked + /// the commit hook. Note that sqlite3_prepare_v2() and sqlite3_step() both modify their database connections + /// in this context. + /// + /// See https://www.sqlite.org/c3ref/commit_hook.html + pub fn set_commit_hook(&mut self, callback: F) + where + F: FnMut() -> bool + Send + 'static, + { + unsafe { + let callback_boxed = Box::new(callback); + // SAFETY: `Box::into_raw()` always returns a non-null pointer. + let callback = NonNull::new_unchecked(Box::into_raw(callback_boxed)); + let handler = callback.as_ptr() as *mut _; + self.guard.remove_commit_hook(); + self.guard.commit_hook_callback = Some(CommitHookHandler(callback)); + + sqlite3_commit_hook( + self.as_raw_handle().as_mut(), + Some(commit_hook::), + handler, + ); + } + } + + /// Sets a rollback hook that is invoked whenever a transaction rollback occurs. The rollback callback is not + /// invoked if a transaction is automatically rolled back because the database connection is closed. + /// + /// See https://www.sqlite.org/c3ref/commit_hook.html + pub fn set_rollback_hook(&mut self, callback: F) + where + F: FnMut() + Send + 'static, + { + unsafe { + let callback_boxed = Box::new(callback); + // SAFETY: `Box::into_raw()` always returns a non-null pointer. + let callback = NonNull::new_unchecked(Box::into_raw(callback_boxed)); + let handler = callback.as_ptr() as *mut _; + self.guard.remove_rollback_hook(); + self.guard.rollback_hook_callback = Some(RollbackHookHandler(callback)); + + sqlite3_rollback_hook( + self.as_raw_handle().as_mut(), + Some(rollback_hook::), + handler, + ); + } + } + + /// Removes the progress handler on a database connection. The method does nothing if no handler was set. + pub fn remove_progress_handler(&mut self) { + self.guard.remove_progress_handler(); + } + + pub fn remove_update_hook(&mut self) { + self.guard.remove_update_hook(); + } + + #[cfg(feature = "preupdate-hook")] + pub fn remove_preupdate_hook(&mut self) { + self.guard.remove_preupdate_hook(); + } + + pub fn remove_commit_hook(&mut self) { + self.guard.remove_commit_hook(); + } + + pub fn remove_rollback_hook(&mut self) { + self.guard.remove_rollback_hook(); + } + + pub fn last_error(&mut self) -> Option { + self.guard.handle.last_error() + } +} + +impl Drop for ConnectionState { + fn drop(&mut self) { + // explicitly drop statements before the connection handle is dropped + self.statements.clear(); + self.remove_progress_handler(); + self.remove_update_hook(); + self.remove_commit_hook(); + self.remove_rollback_hook(); + } +} + +impl Statements { + fn new(capacity: usize) -> Self { + Statements { + cached: StatementCache::new(capacity), + temp: None, + } + } + + fn get(&mut self, query: &str, persistent: bool) -> Result<&mut VirtualStatement, Error> { + if !persistent || !self.cached.is_enabled() { + return Ok(self.temp.insert(VirtualStatement::new(query, false)?)); + } + + let exists = self.cached.contains_key(query); + + if !exists { + let statement = VirtualStatement::new(query, true)?; + self.cached.insert(query, statement); + } + + let statement = self.cached.get_mut(query).unwrap(); + + if exists { + // as this statement has been executed before, we reset before continuing + statement.reset()?; + } + + Ok(statement) + } + + fn len(&self) -> usize { + self.cached.len() + } + + fn clear(&mut self) { + self.cached.clear(); + self.temp = None; + } +} diff --git a/vendor/sqlx-sqlite/src/connection/preupdate_hook.rs b/vendor/sqlx-sqlite/src/connection/preupdate_hook.rs new file mode 100755 index 000000000000..275958887309 --- /dev/null +++ b/vendor/sqlx-sqlite/src/connection/preupdate_hook.rs @@ -0,0 +1,157 @@ +use super::SqliteOperation; +use crate::{SqliteError, SqliteValueRef}; + +use libsqlite3_sys::{ + sqlite3, sqlite3_preupdate_count, sqlite3_preupdate_depth, sqlite3_preupdate_new, + sqlite3_preupdate_old, sqlite3_value, SQLITE_OK, +}; +use std::ffi::CStr; +use std::marker::PhantomData; +use std::os::raw::{c_char, c_int, c_void}; +use std::panic::catch_unwind; +use std::ptr; +use std::ptr::NonNull; + +#[derive(Debug, thiserror::Error)] +pub enum PreupdateError { + /// Error returned from the database. + #[error("error returned from database: {0}")] + Database(#[source] SqliteError), + /// Index is not within the valid column range + #[error("{0} is not within the valid column range")] + ColumnIndexOutOfBounds(i32), + /// Column value accessor was invoked from an invalid operation + #[error("column value accessor was invoked from an invalid operation")] + InvalidOperation, +} + +pub(crate) struct PreupdateHookHandler( + pub(super) NonNull, +); +unsafe impl Send for PreupdateHookHandler {} + +#[derive(Debug)] +pub struct PreupdateHookResult<'a> { + pub operation: SqliteOperation, + pub database: &'a str, + pub table: &'a str, + db: *mut sqlite3, + // The database pointer should not be usable after the preupdate hook. + // The lifetime on this struct needs to ensure it cannot outlive the callback. + _db_lifetime: PhantomData<&'a ()>, + old_row_id: i64, + new_row_id: i64, +} + +impl<'a> PreupdateHookResult<'a> { + /// Gets the amount of columns in the row being inserted, deleted, or updated. + pub fn get_column_count(&self) -> i32 { + unsafe { sqlite3_preupdate_count(self.db) } + } + + /// Gets the depth of the query that triggered the preupdate hook. + /// Returns 0 if the preupdate callback was invoked as a result of + /// a direct insert, update, or delete operation; + /// 1 for inserts, updates, or deletes invoked by top-level triggers; + /// 2 for changes resulting from triggers called by top-level triggers; and so forth. + pub fn get_query_depth(&self) -> i32 { + unsafe { sqlite3_preupdate_depth(self.db) } + } + + /// Gets the row id of the row being updated/deleted. + /// Returns an error if called from an insert operation. + pub fn get_old_row_id(&self) -> Result { + if self.operation == SqliteOperation::Insert { + return Err(PreupdateError::InvalidOperation); + } + Ok(self.old_row_id) + } + + /// Gets the row id of the row being inserted/updated. + /// Returns an error if called from a delete operation. + pub fn get_new_row_id(&self) -> Result { + if self.operation == SqliteOperation::Delete { + return Err(PreupdateError::InvalidOperation); + } + Ok(self.new_row_id) + } + + /// Gets the value of the row being updated/deleted at the specified index. + /// Returns an error if called from an insert operation or the index is out of bounds. + pub fn get_old_column_value(&self, i: i32) -> Result, PreupdateError> { + if self.operation == SqliteOperation::Insert { + return Err(PreupdateError::InvalidOperation); + } + self.validate_column_index(i)?; + + let mut p_value: *mut sqlite3_value = ptr::null_mut(); + unsafe { + let ret = sqlite3_preupdate_old(self.db, i, &mut p_value); + self.get_value(ret, p_value) + } + } + + /// Gets the value of the row being inserted/updated at the specified index. + /// Returns an error if called from a delete operation or the index is out of bounds. + pub fn get_new_column_value(&self, i: i32) -> Result, PreupdateError> { + if self.operation == SqliteOperation::Delete { + return Err(PreupdateError::InvalidOperation); + } + self.validate_column_index(i)?; + + let mut p_value: *mut sqlite3_value = ptr::null_mut(); + unsafe { + let ret = sqlite3_preupdate_new(self.db, i, &mut p_value); + self.get_value(ret, p_value) + } + } + + fn validate_column_index(&self, i: i32) -> Result<(), PreupdateError> { + if i < 0 || i >= self.get_column_count() { + return Err(PreupdateError::ColumnIndexOutOfBounds(i)); + } + Ok(()) + } + + unsafe fn get_value( + &self, + ret: i32, + p_value: *mut sqlite3_value, + ) -> Result, PreupdateError> { + if ret != SQLITE_OK { + return Err(PreupdateError::Database(SqliteError::new(self.db))); + } + Ok(SqliteValueRef::borrowed(p_value)) + } +} + +pub(super) extern "C" fn preupdate_hook( + callback: *mut c_void, + db: *mut sqlite3, + op_code: c_int, + database: *const c_char, + table: *const c_char, + old_row_id: i64, + new_row_id: i64, +) where + F: FnMut(PreupdateHookResult) + Send + 'static, +{ + unsafe { + let _ = catch_unwind(|| { + let callback: *mut F = callback.cast::(); + let operation: SqliteOperation = op_code.into(); + let database = CStr::from_ptr(database).to_str().unwrap_or_default(); + let table = CStr::from_ptr(table).to_str().unwrap_or_default(); + + (*callback)(PreupdateHookResult { + operation, + database, + table, + old_row_id, + new_row_id, + db, + _db_lifetime: PhantomData, + }) + }); + } +} diff --git a/vendor/sqlx-sqlite/src/connection/worker.rs b/vendor/sqlx-sqlite/src/connection/worker.rs new file mode 100755 index 000000000000..2585dc131221 --- /dev/null +++ b/vendor/sqlx-sqlite/src/connection/worker.rs @@ -0,0 +1,573 @@ +use std::future::Future; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; +use std::thread; + +use futures_channel::oneshot; +use futures_intrusive::sync::{Mutex, MutexGuard}; +use sqlx_core::sql_str::SqlStr; +use tracing::span::Span; + +use sqlx_core::error::Error; +use sqlx_core::transaction::{ + begin_ansi_transaction_sql, commit_ansi_transaction_sql, rollback_ansi_transaction_sql, +}; +use sqlx_core::Either; + +use crate::connection::establish::EstablishParams; +use crate::connection::execute; +use crate::connection::ConnectionState; +use crate::{SqliteArguments, SqliteQueryResult, SqliteRow, SqliteStatement}; + +#[cfg(feature = "deserialize")] +use crate::connection::deserialize::{deserialize, serialize, SchemaName, SqliteOwnedBuf}; + +// Each SQLite connection has a dedicated thread. + +// TODO: Tweak this so that we can use a thread pool per pool of SQLite3 connections to reduce +// OS resource usage. Low priority because a high concurrent load for SQLite3 is very +// unlikely. + +pub(crate) struct ConnectionWorker { + command_tx: flume::Sender<(Command, tracing::Span)>, + /// Mutex for locking access to the database. + pub(crate) shared: Arc, +} + +pub(crate) struct WorkerSharedState { + transaction_depth: AtomicUsize, + cached_statements_size: AtomicUsize, + pub(crate) conn: Mutex, +} + +impl WorkerSharedState { + pub(crate) fn get_transaction_depth(&self) -> usize { + self.transaction_depth.load(Ordering::Acquire) + } + + pub(crate) fn get_cached_statements_size(&self) -> usize { + self.cached_statements_size.load(Ordering::Acquire) + } +} + +enum Command { + Prepare { + query: SqlStr, + tx: oneshot::Sender>, + }, + #[cfg(feature = "offline")] + Describe { + query: SqlStr, + tx: oneshot::Sender, Error>>, + }, + Execute { + query: SqlStr, + arguments: Option, + persistent: bool, + tx: flume::Sender, Error>>, + limit: Option, + }, + #[cfg(feature = "deserialize")] + Serialize { + schema: Option, + tx: oneshot::Sender>, + }, + #[cfg(feature = "deserialize")] + Deserialize { + schema: Option, + data: SqliteOwnedBuf, + read_only: bool, + tx: oneshot::Sender>, + }, + Begin { + tx: rendezvous_oneshot::Sender>, + statement: Option, + }, + Commit { + tx: rendezvous_oneshot::Sender>, + }, + Rollback { + tx: Option>>, + }, + UnlockDb, + ClearCache { + tx: oneshot::Sender<()>, + }, + Ping { + tx: oneshot::Sender<()>, + }, + Shutdown { + tx: oneshot::Sender<()>, + }, +} + +impl ConnectionWorker { + pub(crate) async fn establish(params: EstablishParams) -> Result { + let (establish_tx, establish_rx) = oneshot::channel(); + + thread::Builder::new() + .name(params.thread_name.clone()) + .spawn(move || { + let (command_tx, command_rx) = flume::bounded(params.command_channel_size); + + let conn = match params.establish() { + Ok(conn) => conn, + Err(e) => { + establish_tx.send(Err(e)).ok(); + return; + } + }; + + let shared = Arc::new(WorkerSharedState { + transaction_depth: AtomicUsize::new(0), + cached_statements_size: AtomicUsize::new(0), + // note: must be fair because in `Command::UnlockDb` we unlock the mutex + // and then immediately try to relock it; an unfair mutex would immediately + // grant us the lock even if another task is waiting. + conn: Mutex::new(conn, true), + }); + let mut conn = shared.conn.try_lock().unwrap(); + + if establish_tx + .send(Ok(Self { + command_tx, + shared: Arc::clone(&shared), + })) + .is_err() + { + return; + } + + // If COMMIT or ROLLBACK is processed but not acknowledged, there would be another + // ROLLBACK sent when the `Transaction` drops. We need to ignore it otherwise we + // would rollback an already completed transaction. + let mut ignore_next_start_rollback = false; + + for (cmd, span) in command_rx { + let _guard = span.enter(); + match cmd { + Command::Prepare { query, tx } => { + tx.send(prepare(&mut conn, query)).ok(); + + // This may issue an unnecessary write on failure, + // but it doesn't matter in the grand scheme of things. + update_cached_statements_size( + &conn, + &shared.cached_statements_size, + ); + } + #[cfg(feature = "offline")] + Command::Describe { query, tx } => { + tx.send(crate::connection::describe::describe(&mut conn, query)).ok(); + } + Command::Execute { + query, + arguments, + persistent, + tx, + limit + } => { + let iter = match execute::iter(&mut conn, query, arguments, persistent) + { + Ok(iter) => iter, + Err(e) => { + tx.send(Err(e)).ok(); + continue; + } + }; + + match limit { + None => { + for res in iter { + let has_error = res.is_err(); + if tx.send(res).is_err() || has_error { + break; + } + } + }, + Some(limit) => { + let mut iter = iter; + let mut rows_returned = 0; + + while let Some(res) = iter.next() { + if let Ok(ok) = &res { + if ok.is_right() { + rows_returned += 1; + if rows_returned >= limit { + drop(iter); + let _ = tx.send(res); + break; + } + } + } + let has_error = res.is_err(); + if tx.send(res).is_err() || has_error { + break; + } + } + }, + } + + update_cached_statements_size(&conn, &shared.cached_statements_size); + } + Command::Begin { tx, statement } => { + let depth = shared.transaction_depth.load(Ordering::Acquire); + + let is_custom_statement = statement.is_some(); + let statement = match statement { + // custom `BEGIN` statements are not allowed if + // we're already in a transaction (we need to + // issue a `SAVEPOINT` instead) + Some(_) if depth > 0 => { + if tx.blocking_send(Err(Error::InvalidSavePointStatement)).is_err() { + break; + } + continue; + }, + Some(statement) => statement, + None => begin_ansi_transaction_sql(depth), + }; + let res = + conn.handle + .exec(statement.as_str()) + .and_then(|res| { + if is_custom_statement && !conn.handle.in_transaction() { + return Err(Error::BeginFailed) + } + + shared.transaction_depth.fetch_add(1, Ordering::Release); + + Ok(res) + }); + let res_ok = res.is_ok(); + + if tx.blocking_send(res).is_err() && res_ok { + // The BEGIN was processed but not acknowledged. This means no + // `Transaction` was created and so there is no way to commit / + // rollback this transaction. We need to roll it back + // immediately otherwise it would remain started forever. + if let Err(error) = conn + .handle + .exec(rollback_ansi_transaction_sql(depth + 1).as_str()) + .map(|_| { + shared.transaction_depth.fetch_sub(1, Ordering::Release); + }) + { + // The rollback failed. To prevent leaving the connection + // in an inconsistent state we shutdown this worker which + // causes any subsequent operation on the connection to fail. + tracing::error!(%error, "failed to rollback cancelled transaction"); + break; + } + } + } + Command::Commit { tx } => { + let depth = shared.transaction_depth.load(Ordering::Acquire); + + let res = if depth > 0 { + conn.handle + .exec(commit_ansi_transaction_sql(depth).as_str()) + .map(|_| { + shared.transaction_depth.fetch_sub(1, Ordering::Release); + }) + } else { + Ok(()) + }; + let res_ok = res.is_ok(); + + if tx.blocking_send(res).is_err() && res_ok { + // The COMMIT was processed but not acknowledged. This means that + // the `Transaction` doesn't know it was committed and will try to + // rollback on drop. We need to ignore that rollback. + ignore_next_start_rollback = true; + } + } + Command::Rollback { tx } => { + if ignore_next_start_rollback && tx.is_none() { + ignore_next_start_rollback = false; + continue; + } + + let depth = shared.transaction_depth.load(Ordering::Acquire); + + let res = if depth > 0 { + conn.handle + .exec(rollback_ansi_transaction_sql(depth).as_str()) + .map(|_| { + shared.transaction_depth.fetch_sub(1, Ordering::Release); + }) + } else { + Ok(()) + }; + + let res_ok = res.is_ok(); + + if let Some(tx) = tx { + if tx.blocking_send(res).is_err() && res_ok { + // The ROLLBACK was processed but not acknowledged. This means + // that the `Transaction` doesn't know it was rolled back and + // will try to rollback again on drop. We need to ignore that + // rollback. + ignore_next_start_rollback = true; + } + } + } + #[cfg(feature = "deserialize")] + Command::Serialize { schema, tx } => { + tx.send(serialize(&mut conn, schema)).ok(); + } + #[cfg(feature = "deserialize")] + Command::Deserialize { schema, data, read_only, tx } => { + tx.send(deserialize(&mut conn, schema, data, read_only)).ok(); + } + Command::ClearCache { tx } => { + conn.statements.clear(); + update_cached_statements_size(&conn, &shared.cached_statements_size); + tx.send(()).ok(); + } + Command::UnlockDb => { + drop(conn); + conn = futures_executor::block_on(shared.conn.lock()); + } + Command::Ping { tx } => { + tx.send(()).ok(); + } + Command::Shutdown { tx } => { + // drop the connection references before sending confirmation + // and ending the command loop + drop(conn); + drop(shared); + let _ = tx.send(()); + return; + } + } + } + })?; + + establish_rx.await.map_err(|_| Error::WorkerCrashed)? + } + + pub(crate) async fn prepare(&mut self, query: SqlStr) -> Result { + self.oneshot_cmd(|tx| Command::Prepare { query, tx }) + .await? + } + + #[cfg(feature = "offline")] + pub(crate) async fn describe( + &mut self, + query: SqlStr, + ) -> Result, Error> { + self.oneshot_cmd(|tx| Command::Describe { query, tx }) + .await? + } + + pub(crate) async fn execute( + &mut self, + query: SqlStr, + args: Option, + chan_size: usize, + persistent: bool, + limit: Option, + ) -> Result, Error>>, Error> { + let (tx, rx) = flume::bounded(chan_size); + + self.command_tx + .send_async(( + Command::Execute { + query, + arguments: args, + persistent, + tx, + limit, + }, + Span::current(), + )) + .await + .map_err(|_| Error::WorkerCrashed)?; + + Ok(rx) + } + + pub(crate) async fn begin(&mut self, statement: Option) -> Result<(), Error> { + self.oneshot_cmd_with_ack(|tx| Command::Begin { tx, statement }) + .await? + } + + pub(crate) async fn commit(&mut self) -> Result<(), Error> { + self.oneshot_cmd_with_ack(|tx| Command::Commit { tx }) + .await? + } + + pub(crate) async fn rollback(&mut self) -> Result<(), Error> { + self.oneshot_cmd_with_ack(|tx| Command::Rollback { tx: Some(tx) }) + .await? + } + + pub(crate) fn start_rollback(&mut self) -> Result<(), Error> { + self.command_tx + .send((Command::Rollback { tx: None }, Span::current())) + .map_err(|_| Error::WorkerCrashed) + } + + pub(crate) async fn ping(&mut self) -> Result<(), Error> { + self.oneshot_cmd(|tx| Command::Ping { tx }).await + } + + #[cfg(feature = "deserialize")] + pub(crate) async fn deserialize( + &mut self, + schema: Option, + data: SqliteOwnedBuf, + read_only: bool, + ) -> Result<(), Error> { + self.oneshot_cmd(|tx| Command::Deserialize { + schema, + data, + read_only, + tx, + }) + .await? + } + + #[cfg(feature = "deserialize")] + pub(crate) async fn serialize( + &mut self, + schema: Option, + ) -> Result { + self.oneshot_cmd(|tx| Command::Serialize { schema, tx }) + .await? + } + + async fn oneshot_cmd(&mut self, command: F) -> Result + where + F: FnOnce(oneshot::Sender) -> Command, + { + let (tx, rx) = oneshot::channel(); + + self.command_tx + .send_async((command(tx), Span::current())) + .await + .map_err(|_| Error::WorkerCrashed)?; + + rx.await.map_err(|_| Error::WorkerCrashed) + } + + async fn oneshot_cmd_with_ack(&mut self, command: F) -> Result + where + F: FnOnce(rendezvous_oneshot::Sender) -> Command, + { + let (tx, rx) = rendezvous_oneshot::channel(); + + self.command_tx + .send_async((command(tx), Span::current())) + .await + .map_err(|_| Error::WorkerCrashed)?; + + rx.recv().await.map_err(|_| Error::WorkerCrashed) + } + + pub(crate) async fn clear_cache(&mut self) -> Result<(), Error> { + self.oneshot_cmd(|tx| Command::ClearCache { tx }).await + } + + pub(crate) async fn unlock_db(&mut self) -> Result, Error> { + let (guard, res) = futures_util::future::join( + // we need to join the wait queue for the lock before we send the message + self.shared.conn.lock(), + self.command_tx + .send_async((Command::UnlockDb, Span::current())), + ) + .await; + + res.map_err(|_| Error::WorkerCrashed)?; + + Ok(guard) + } + + /// Send a command to the worker to shut down the processing thread. + /// + /// A `WorkerCrashed` error may be returned if the thread has already stopped. + pub(crate) fn shutdown(&mut self) -> impl Future> { + let (tx, rx) = oneshot::channel(); + + let send_res = self + .command_tx + .send((Command::Shutdown { tx }, Span::current())) + .map_err(|_| Error::WorkerCrashed); + + async move { + send_res?; + + // wait for the response + rx.await.map_err(|_| Error::WorkerCrashed) + } + } +} + +fn prepare(conn: &mut ConnectionState, query: SqlStr) -> Result { + // prepare statement object (or checkout from cache) + let statement = conn.statements.get(query.as_str(), true)?; + + let mut parameters = 0; + let mut columns = None; + let mut column_names = None; + + while let Some(statement) = statement.prepare_next(&mut conn.handle)? { + parameters += statement.handle.bind_parameter_count(); + + // the first non-empty statement is chosen as the statement we pull columns from + if !statement.columns.is_empty() && columns.is_none() { + columns = Some(Arc::clone(statement.columns)); + column_names = Some(Arc::clone(statement.column_names)); + } + } + + Ok(SqliteStatement { + sql: query, + columns: columns.unwrap_or_default(), + column_names: column_names.unwrap_or_default(), + parameters, + }) +} + +fn update_cached_statements_size(conn: &ConnectionState, size: &AtomicUsize) { + size.store(conn.statements.len(), Ordering::Release); +} + +// A oneshot channel where send completes only after the receiver receives the value. +mod rendezvous_oneshot { + use super::oneshot::{self, Canceled}; + + pub fn channel() -> (Sender, Receiver) { + let (inner_tx, inner_rx) = oneshot::channel(); + (Sender { inner: inner_tx }, Receiver { inner: inner_rx }) + } + + pub struct Sender { + inner: oneshot::Sender<(T, oneshot::Sender<()>)>, + } + + impl Sender { + pub async fn send(self, value: T) -> Result<(), Canceled> { + let (ack_tx, ack_rx) = oneshot::channel(); + self.inner.send((value, ack_tx)).map_err(|_| Canceled)?; + ack_rx.await + } + + pub fn blocking_send(self, value: T) -> Result<(), Canceled> { + futures_executor::block_on(self.send(value)) + } + } + + pub struct Receiver { + inner: oneshot::Receiver<(T, oneshot::Sender<()>)>, + } + + impl Receiver { + pub async fn recv(self) -> Result { + let (value, ack_tx) = self.inner.await?; + ack_tx.send(()).map_err(|_| Canceled)?; + Ok(value) + } + } +} diff --git a/vendor/sqlx-sqlite/src/database.rs b/vendor/sqlx-sqlite/src/database.rs new file mode 100755 index 000000000000..ca52d1cf6b9e --- /dev/null +++ b/vendor/sqlx-sqlite/src/database.rs @@ -0,0 +1,39 @@ +pub(crate) use sqlx_core::database::{Database, HasStatementCache}; + +use crate::arguments::SqliteArgumentsBuffer; +use crate::{ + SqliteArguments, SqliteColumn, SqliteConnection, SqliteQueryResult, SqliteRow, SqliteStatement, + SqliteTransactionManager, SqliteTypeInfo, SqliteValue, SqliteValueRef, +}; + +/// Sqlite database driver. +#[derive(Debug)] +pub struct Sqlite; + +impl Database for Sqlite { + type Connection = SqliteConnection; + + type TransactionManager = SqliteTransactionManager; + + type Row = SqliteRow; + + type QueryResult = SqliteQueryResult; + + type Column = SqliteColumn; + + type TypeInfo = SqliteTypeInfo; + + type Value = SqliteValue; + type ValueRef<'r> = SqliteValueRef<'r>; + + type Arguments = SqliteArguments; + type ArgumentBuffer = SqliteArgumentsBuffer; + + type Statement = SqliteStatement; + + const NAME: &'static str = "SQLite"; + + const URL_SCHEMES: &'static [&'static str] = &["sqlite"]; +} + +impl HasStatementCache for Sqlite {} diff --git a/vendor/sqlx-sqlite/src/error.rs b/vendor/sqlx-sqlite/src/error.rs new file mode 100755 index 000000000000..5510e25d9716 --- /dev/null +++ b/vendor/sqlx-sqlite/src/error.rs @@ -0,0 +1,139 @@ +use std::error::Error as StdError; +use std::ffi::CStr; +use std::fmt::{self, Display, Formatter}; +use std::os::raw::c_int; +use std::{borrow::Cow, str}; + +use libsqlite3_sys::{ + sqlite3, sqlite3_errmsg, sqlite3_errstr, sqlite3_extended_errcode, SQLITE_CONSTRAINT_CHECK, + SQLITE_CONSTRAINT_FOREIGNKEY, SQLITE_CONSTRAINT_NOTNULL, SQLITE_CONSTRAINT_PRIMARYKEY, + SQLITE_CONSTRAINT_UNIQUE, SQLITE_ERROR, SQLITE_NOMEM, +}; + +pub(crate) use sqlx_core::error::*; + +// Error Codes And Messages +// https://www.sqlite.org/c3ref/errcode.html + +#[derive(Debug)] +pub struct SqliteError { + code: c_int, + message: Cow<'static, str>, +} + +impl SqliteError { + pub(crate) unsafe fn new(handle: *mut sqlite3) -> Self { + Self::try_new(handle).expect("There should be an error") + } + + pub(crate) unsafe fn try_new(handle: *mut sqlite3) -> Option { + // returns the extended result code even when extended result codes are disabled + let code: c_int = unsafe { sqlite3_extended_errcode(handle) }; + + if code == 0 { + return None; + } + + // return English-language text that describes the error + let message = unsafe { + let msg = sqlite3_errmsg(handle); + debug_assert!(!msg.is_null()); + + String::from_utf8_lossy(CStr::from_ptr(msg).to_bytes()).into_owned() + }; + + Some(Self { + code, + message: message.into(), + }) + } + + /// For errors during extension load, the error message is supplied via a separate pointer + #[allow(dead_code)] + pub(crate) fn with_message(mut self, error_msg: String) -> Self { + self.message = error_msg.into(); + self + } + + #[allow(dead_code)] + pub(crate) fn from_code(code: c_int) -> Self { + let message = unsafe { + let errstr = sqlite3_errstr(code); + + if !errstr.is_null() { + // SAFETY: `errstr` is guaranteed to be UTF-8 + // The lifetime of the string is "internally managed"; + // the implementation just selects from an array of static strings. + // We copy to an owned buffer in case `libsqlite3` is dynamically loaded somehow. + Cow::Owned(str::from_utf8_unchecked(CStr::from_ptr(errstr).to_bytes()).into()) + } else { + Cow::Borrowed("") + } + }; + + SqliteError { code, message } + } + + #[allow(dead_code)] + pub(crate) fn generic(message: impl Into>) -> Self { + Self { + code: SQLITE_ERROR, + message: message.into(), + } + } + + /// Return `SQLITE_NOMEM`. + pub(crate) fn nomem() -> Self { + Self::from_code(SQLITE_NOMEM) + } +} + +impl Display for SqliteError { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + // We include the code as some produce ambiguous messages: + // SQLITE_BUSY: "database is locked" + // SQLITE_LOCKED: "database table is locked" + // Sadly there's no function to get the string label back from an error code. + write!(f, "(code: {}) {}", self.code, self.message) + } +} + +impl StdError for SqliteError {} + +impl DatabaseError for SqliteError { + #[inline] + fn message(&self) -> &str { + &self.message + } + + /// The extended result code. + #[inline] + fn code(&self) -> Option> { + Some(format!("{}", self.code).into()) + } + + #[doc(hidden)] + fn as_error(&self) -> &(dyn StdError + Send + Sync + 'static) { + self + } + + #[doc(hidden)] + fn as_error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) { + self + } + + #[doc(hidden)] + fn into_error(self: Box) -> Box { + self + } + + fn kind(&self) -> ErrorKind { + match self.code { + SQLITE_CONSTRAINT_UNIQUE | SQLITE_CONSTRAINT_PRIMARYKEY => ErrorKind::UniqueViolation, + SQLITE_CONSTRAINT_FOREIGNKEY => ErrorKind::ForeignKeyViolation, + SQLITE_CONSTRAINT_NOTNULL => ErrorKind::NotNullViolation, + SQLITE_CONSTRAINT_CHECK => ErrorKind::CheckViolation, + _ => ErrorKind::Other, + } + } +} diff --git a/vendor/sqlx-sqlite/src/lib.rs b/vendor/sqlx-sqlite/src/lib.rs new file mode 100755 index 000000000000..17b4bed1ca40 --- /dev/null +++ b/vendor/sqlx-sqlite/src/lib.rs @@ -0,0 +1,183 @@ +//! **SQLite** database driver. +//! +//! ### Note: `libsqlite3-sys` Version +//! This driver uses the `libsqlite3-sys` crate which links the native library for SQLite 3. +//! Only one version of `libsqlite3-sys` may appear in the dependency tree of your project. +//! +//! As of SQLx 0.9.0, the version of `libsqlite3-sys` is now a range instead of any specific version. +//! See the `Cargo.toml` of the `sqlx-sqlite` crate for the current version range. +//! +//! If you are using `rusqlite` or any other crate that indirectly depends on `libsqlite3-sys`, +//! this should allow Cargo to select a compatible version. +//! +//! If Cargo **fails to select a compatible version**, this means the other crate is using +//! a `libsqlite3-sys` version outside of this range. +//! +//! We may increase the *maximum* version of the range at our discretion, +//! in patch (SemVer-compatible) releases, to allow users to upgrade to newer versions as desired. +//! +//! The *minimum* version of the range may be increased over time to drop very old or +//! insecure versions of SQLite, but this will only occur in major (SemVer-incompatible) releases. +//! +//! Note that this means a `cargo update` may increase the `libsqlite3-sys` version, +//! which could, in rare cases, break your build. +//! +//! To prevent this, you can pin the `libsqlite3-sys` version in your own dependencies: +//! +//! ```toml +//! [dependencies] +//! # for example, if 0.35.0 breaks the build +//! libsqlite3-sys = "0.34" +//! ``` +//! +//! ### Static Linking (Default) +//! The `sqlite` feature enables the `bundled` feature of `libsqlite3-sys`, +//! which builds SQLite 3 from included source code and statically links it into the final binary. +//! +//! This requires some C build tools to be installed on the system; see +//! [the `rusqlite` README][rusqlite-readme-building] for details. +//! +//! This version of SQLite is generally much newer than system-installed versions of SQLite +//! (especially for LTS Linux distributions), and can be updated with a `cargo update`, +//! so this is the recommended option for ease of use and keeping up-to-date. +//! +//! ### Dynamic linking +//! To dynamically link to an existing SQLite library, the `sqlite-unbundled` feature can be used +//! instead. +//! +//! This allows updating SQLite independently of SQLx or using forked versions, but you must have +//! SQLite installed on the system or provide a path to the library at build time (see +//! [the `rusqlite` README][rusqlite-readme-building] for details). +//! +//! Note that this _may_ result in link errors if the SQLite version is too old, +//! or has [certain features disabled at compile-time](https://www.sqlite.org/compile.html). +//! +//! SQLite version `3.20.0` (released August 2018) or newer is recommended. +//! +//! **Please check your SQLite version and the flags it was built with before opening +//! a GitHub issue because of errors in `libsqlite3-sys`.** Thank you. +//! +//! [rusqlite-readme-building]: https://github.com/rusqlite/rusqlite?tab=readme-ov-file#notes-on-building-rusqlite-and-libsqlite3-sys +//! +//! ### Optional Features +//! +//! The following features +//! + +// SQLite is a C library. All interactions require FFI which is unsafe. +// All unsafe blocks should have comments pointing to SQLite docs and ensuring that we maintain +// invariants. +#![allow(unsafe_code)] + +#[macro_use] +extern crate sqlx_core; + +use std::sync::atomic::AtomicBool; + +pub use arguments::{SqliteArgumentValue, SqliteArguments, SqliteArgumentsBuffer}; +pub use column::SqliteColumn; +#[cfg(feature = "deserialize")] +#[cfg_attr(docsrs, doc(cfg(feature = "deserialize")))] +pub use connection::deserialize::SqliteOwnedBuf; +#[cfg(feature = "preupdate-hook")] +#[cfg_attr(docsrs, doc(cfg(feature = "preupdate-hook")))] +pub use connection::PreupdateHookResult; +pub use connection::{LockedSqliteHandle, SqliteConnection, SqliteOperation, UpdateHookResult}; +pub use database::Sqlite; +pub use error::SqliteError; +pub use options::{ + SqliteAutoVacuum, SqliteConnectOptions, SqliteJournalMode, SqliteLockingMode, SqliteSynchronous, +}; +pub use query_result::SqliteQueryResult; +pub use row::SqliteRow; +pub use statement::SqliteStatement; +pub use transaction::SqliteTransactionManager; +pub use type_info::SqliteTypeInfo; +pub use value::{SqliteValue, SqliteValueRef}; + +use crate::connection::establish::EstablishParams; + +pub(crate) use sqlx_core::driver_prelude::*; + +use sqlx_core::config; +use sqlx_core::describe::Describe; +use sqlx_core::error::Error; +use sqlx_core::executor::Executor; +use sqlx_core::sql_str::{AssertSqlSafe, SqlSafeStr}; + +mod arguments; +mod column; +mod connection; +mod database; +mod error; +mod logger; +mod options; +mod query_result; +mod row; +mod statement; +mod transaction; +mod type_checking; +mod type_info; +pub mod types; +mod value; + +#[cfg(feature = "any")] +pub mod any; + +#[cfg(feature = "regexp")] +mod regexp; + +#[cfg(feature = "migrate")] +mod migrate; + +#[cfg(feature = "migrate")] +mod testing; + +/// An alias for [`Pool`][crate::pool::Pool], specialized for SQLite. +pub type SqlitePool = crate::pool::Pool; + +/// An alias for [`PoolOptions`][crate::pool::PoolOptions], specialized for SQLite. +pub type SqlitePoolOptions = crate::pool::PoolOptions; + +/// An alias for [`Executor<'_, Database = Sqlite>`][Executor]. +pub trait SqliteExecutor<'c>: Executor<'c, Database = Sqlite> {} +impl<'c, T: Executor<'c, Database = Sqlite>> SqliteExecutor<'c> for T {} + +/// An alias for [`Transaction`][sqlx_core::transaction::Transaction], specialized for SQLite. +pub type SqliteTransaction<'c> = sqlx_core::transaction::Transaction<'c, Sqlite>; + +// NOTE: required due to the lack of lazy normalization +impl_into_arguments_for_arguments!(SqliteArguments); +impl_column_index_for_row!(SqliteRow); +impl_column_index_for_statement!(SqliteStatement); +impl_acquire!(Sqlite, SqliteConnection); + +// required because some databases have a different handling of NULL +impl_encode_for_option!(Sqlite); + +/// UNSTABLE: for use by `sqlx-cli` only. +#[doc(hidden)] +pub static CREATE_DB_WAL: AtomicBool = AtomicBool::new(true); + +/// UNSTABLE: for use by `sqlite-macros-core` only. +#[doc(hidden)] +pub fn describe_blocking( + query: &str, + database_url: &str, + driver_config: &config::drivers::Config, +) -> Result, Error> { + let mut opts: SqliteConnectOptions = database_url.parse()?; + + opts = opts.apply_driver_config(&driver_config.sqlite)?; + + let params = EstablishParams::from_options(&opts)?; + let mut conn = params.establish()?; + + // Execute any ancillary `PRAGMA`s + connection::execute::iter(&mut conn, AssertSqlSafe(opts.pragma_string()), None, false)? + .finish()?; + + connection::describe::describe(&mut conn, AssertSqlSafe(query.to_string()).into_sql_str()) + + // SQLite database is closed immediately when `conn` is dropped +} diff --git a/vendor/sqlx-sqlite/src/logger.rs b/vendor/sqlx-sqlite/src/logger.rs new file mode 100755 index 000000000000..1464a730c772 --- /dev/null +++ b/vendor/sqlx-sqlite/src/logger.rs @@ -0,0 +1,443 @@ +// Bad casts in this module SHOULD NOT result in a SQL injection +// https://github.com/launchbadge/sqlx/issues/3440 +#![allow( + clippy::cast_possible_truncation, + clippy::cast_possible_wrap, + clippy::cast_sign_loss +)] + +use crate::connection::intmap::IntMap; +use std::collections::HashSet; +use std::fmt::Debug; +use std::hash::Hash; + +pub(crate) use sqlx_core::logger::*; + +#[derive(Debug)] +pub(crate) enum BranchResult { + Result(R), + Dedup(BranchParent), + Halt, + Error, + GasLimit, + LoopLimit, + Branched, +} + +#[derive(Debug, Clone, Copy, PartialEq, Hash, Eq, Ord, PartialOrd)] +pub(crate) struct BranchParent { + pub id: i64, + pub idx: i64, +} + +#[derive(Debug)] +pub(crate) struct InstructionHistory { + pub program_i: usize, + pub state: S, +} + +pub(crate) trait DebugDiff { + fn diff(&self, prev: &Self) -> String; +} + +pub struct QueryPlanLogger<'q, R: Debug + 'static, S: Debug + DebugDiff + 'static, P: Debug> { + sql: &'q str, + unknown_operations: HashSet, + branch_origins: IntMap, + branch_results: IntMap>, + branch_operations: IntMap>>, + program: &'q [P], +} + +/// convert a string into dot format +fn dot_escape_string(value: impl AsRef) -> String { + value + .as_ref() + .replace('\\', r#"\\"#) + .replace('"', "'") + .replace('\n', r#"\n"#) + .to_string() +} + +impl core::fmt::Display for QueryPlanLogger<'_, R, S, P> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + //writes query plan history in dot format + f.write_str("digraph {\n")?; + + f.write_str("subgraph operations {\n")?; + f.write_str("style=\"rounded\";\nnode [shape=\"point\"];\n")?; + + let all_states: std::collections::HashMap> = self + .branch_operations + .iter_entries() + .flat_map( + |(branch_id, instructions): (i64, &IntMap>)| { + instructions.iter_entries().map( + move |(idx, ih): (i64, &InstructionHistory)| { + (BranchParent { id: branch_id, idx }, ih) + }, + ) + }, + ) + .collect(); + + let mut instruction_uses: IntMap> = Default::default(); + for (k, state) in all_states.iter() { + let entry = instruction_uses.get_mut_or_default(&(state.program_i as i64)); + entry.push(*k); + } + + let mut branch_children: std::collections::HashMap> = + Default::default(); + + let mut branched_with_state: std::collections::HashSet = Default::default(); + + for (branch_id, branch_parent) in self.branch_origins.iter_entries() { + let entry = branch_children.entry(*branch_parent).or_default(); + entry.push(BranchParent { + id: branch_id, + idx: 0, + }); + } + + for (idx, instruction) in self.program.iter().enumerate() { + let escaped_instruction = dot_escape_string(format!("{:?}", instruction)); + write!( + f, + "subgraph cluster_{} {{ label=\"{}\"", + idx, escaped_instruction + )?; + + if self.unknown_operations.contains(&idx) { + f.write_str(" style=dashed")?; + } + + f.write_str(";\n")?; + + let mut state_list: std::collections::BTreeMap< + String, + Vec<(BranchParent, Option)>, + > = Default::default(); + + write!(f, "i{}[style=invis];", idx)?; + + if let Some(this_instruction_uses) = instruction_uses.get(&(idx as i64)) { + for curr_ref in this_instruction_uses.iter() { + if let Some(curr_state) = all_states.get(curr_ref) { + let next_ref = BranchParent { + id: curr_ref.id, + idx: curr_ref.idx + 1, + }; + + if let Some(next_state) = all_states.get(&next_ref) { + let state_diff = next_state.state.diff(&curr_state.state); + + state_list + .entry(state_diff) + .or_default() + .push((*curr_ref, Some(next_ref))); + } else { + state_list + .entry(Default::default()) + .or_default() + .push((*curr_ref, None)); + }; + + if let Some(children) = branch_children.get(curr_ref) { + for next_ref in children { + if let Some(next_state) = all_states.get(next_ref) { + let state_diff = next_state.state.diff(&curr_state.state); + + if !state_diff.is_empty() { + branched_with_state.insert(*next_ref); + } + + state_list + .entry(state_diff) + .or_default() + .push((*curr_ref, Some(*next_ref))); + } + } + }; + } + } + + for curr_ref in this_instruction_uses { + if branch_children.contains_key(curr_ref) { + write!(f, "\"b{}p{}\";", curr_ref.id, curr_ref.idx)?; + } + } + } else { + write!(f, "i{}->i{}[style=invis];", idx - 1, idx)?; + } + + for (state_num, (state_diff, ref_list)) in state_list.iter().enumerate() { + if !state_diff.is_empty() { + let escaped_state = dot_escape_string(state_diff); + write!( + f, + "subgraph \"cluster_i{}s{}\" {{\nlabel=\"{}\"\n", + idx, state_num, escaped_state + )?; + } + + for (curr_ref, next_ref) in ref_list { + if let Some(next_ref) = next_ref { + let next_program_i = all_states + .get(next_ref) + .map(|s| s.program_i.to_string()) + .unwrap_or_default(); + + if branched_with_state.contains(next_ref) { + write!( + f, + "\"b{}p{}_b{}p{}\"[tooltip=\"next:{}\"];", + curr_ref.id, + curr_ref.idx, + next_ref.id, + next_ref.idx, + next_program_i + )?; + continue; + } else { + write!( + f, + "\"b{}p{}\"[tooltip=\"next:{}\"];", + curr_ref.id, curr_ref.idx, next_program_i + )?; + } + } else { + write!(f, "\"b{}p{}\";", curr_ref.id, curr_ref.idx)?; + } + } + + if !state_diff.is_empty() { + f.write_str("}\n")?; + } + } + + f.write_str("}\n")?; + } + + f.write_str("};\n")?; //subgraph operations + + let max_branch_id: i64 = [ + self.branch_operations.last_index().unwrap_or(0), + self.branch_results.last_index().unwrap_or(0), + self.branch_results.last_index().unwrap_or(0), + ] + .into_iter() + .max() + .unwrap_or(0); + + f.write_str("subgraph branches {\n")?; + for branch_id in 0..=max_branch_id { + write!(f, "subgraph b{}{{", branch_id)?; + + let branch_num = branch_id as usize; + let color_names = [ + "blue", + "red", + "cyan", + "yellow", + "green", + "magenta", + "orange", + "purple", + "orangered", + "sienna", + "olivedrab", + "pink", + ]; + let color_name_root = color_names[branch_num % color_names.len()]; + let color_name_suffix = match (branch_num / color_names.len()) % 4 { + 0 => "1", + 1 => "4", + 2 => "3", + 3 => "2", + _ => "", + }; //colors are easily confused after color_names.len() * 2, and outright reused after color_names.len() * 4 + write!( + f, + "edge [colorscheme=x11 color={}{}];", + color_name_root, color_name_suffix + )?; + + let mut instruction_list: Vec<(BranchParent, &InstructionHistory)> = Vec::new(); + if let Some(parent) = self.branch_origins.get(&branch_id) { + if let Some(parent_state) = all_states.get(parent) { + instruction_list.push((*parent, parent_state)); + } + } + if let Some(instructions) = self.branch_operations.get(&branch_id) { + for instruction in instructions.iter_entries() { + instruction_list.push(( + BranchParent { + id: branch_id, + idx: instruction.0, + }, + instruction.1, + )) + } + } + + let mut instructions_iter = instruction_list.into_iter(); + + if let Some((cur_ref, _)) = instructions_iter.next() { + let mut prev_ref = cur_ref; + + for (cur_ref, _) in instructions_iter { + if branched_with_state.contains(&cur_ref) { + writeln!( + f, + "\"b{}p{}\" -> \"b{}p{}_b{}p{}\" -> \"b{}p{}\"", + prev_ref.id, + prev_ref.idx, + prev_ref.id, + prev_ref.idx, + cur_ref.id, + cur_ref.idx, + cur_ref.id, + cur_ref.idx + )?; + } else { + write!( + f, + "\"b{}p{}\" -> \"b{}p{}\";", + prev_ref.id, prev_ref.idx, cur_ref.id, cur_ref.idx + )?; + } + prev_ref = cur_ref; + } + + //draw edge to the result of this branch + if let Some(result) = self.branch_results.get(&branch_id) { + if let BranchResult::Dedup(dedup_ref) = result { + write!( + f, + "\"b{}p{}\"->\"b{}p{}\" [style=dotted]", + prev_ref.id, prev_ref.idx, dedup_ref.id, dedup_ref.idx + )?; + } else { + let escaped_result = dot_escape_string(format!("{:?}", result)); + write!( + f, + "\"b{}p{}\" ->\"{}\"; \"{}\" [shape=box];", + prev_ref.id, prev_ref.idx, escaped_result, escaped_result + )?; + } + } else { + write!( + f, + "\"b{}p{}\" ->\"NoResult\"; \"NoResult\" [shape=box];", + prev_ref.id, prev_ref.idx + )?; + } + } + f.write_str("};\n")?; + } + f.write_str("};\n")?; //branches + + f.write_str("}\n")?; + Ok(()) + } +} + +impl<'q, R: Debug, S: Debug + DebugDiff, P: Debug> QueryPlanLogger<'q, R, S, P> { + pub fn new(sql: &'q str, program: &'q [P]) -> Self { + Self { + sql, + unknown_operations: HashSet::new(), + branch_origins: IntMap::new(), + branch_results: IntMap::new(), + branch_operations: IntMap::new(), + program, + } + } + + pub fn log_enabled(&self) -> bool { + log::log_enabled!(target: "sqlx::explain", log::Level::Trace) + || private_tracing_dynamic_enabled!(target: "sqlx::explain", tracing::Level::TRACE) + } + + pub fn add_branch(&mut self, state: I, parent: &BranchParent) + where + BranchParent: From, + { + if !self.log_enabled() { + return; + } + let branch: BranchParent = BranchParent::from(state); + self.branch_origins.insert(branch.id, *parent); + } + + pub fn add_operation(&mut self, program_i: usize, state: I) + where + BranchParent: From, + S: From, + { + if !self.log_enabled() { + return; + } + let branch: BranchParent = BranchParent::from(state); + let state: S = S::from(state); + self.branch_operations + .get_mut_or_default(&branch.id) + .insert(branch.idx, InstructionHistory { program_i, state }); + } + + pub fn add_result(&mut self, state: I, result: BranchResult) + where + BranchParent: for<'a> From<&'a I>, + S: From, + { + if !self.log_enabled() { + return; + } + let branch: BranchParent = BranchParent::from(&state); + self.branch_results.insert(branch.id, result); + } + + pub fn add_unknown_operation(&mut self, operation: usize) { + if !self.log_enabled() { + return; + } + self.unknown_operations.insert(operation); + } + + pub fn finish(&self) { + if !self.log_enabled() { + return; + } + + let mut summary = parse_query_summary(self.sql); + + let sql = if summary != self.sql { + summary.push_str(" …"); + format!( + "\n\n{}\n", + self.sql /* + sqlformat::format( + self.sql, + &sqlformat::QueryParams::None, + sqlformat::FormatOptions::default() + ) + */ + ) + } else { + String::new() + }; + + sqlx_core::private_tracing_dynamic_event!( + target: "sqlx::explain", + tracing::Level::TRACE, + "{}; program:\n{}\n\n{:?}", summary, self, sql + ); + } +} + +impl Drop for QueryPlanLogger<'_, R, S, P> { + fn drop(&mut self) { + self.finish(); + } +} diff --git a/vendor/sqlx-sqlite/src/migrate.rs b/vendor/sqlx-sqlite/src/migrate.rs new file mode 100755 index 000000000000..586402389134 --- /dev/null +++ b/vendor/sqlx-sqlite/src/migrate.rs @@ -0,0 +1,297 @@ +use crate::connection::{ConnectOptions, Connection}; +use crate::error::Error; +use crate::executor::Executor; +use crate::fs; +use crate::migrate::MigrateError; +use crate::migrate::{AppliedMigration, Migration}; +use crate::migrate::{Migrate, MigrateDatabase}; +use crate::query::query; +use crate::query_as::query_as; +use crate::{Sqlite, SqliteConnectOptions, SqliteConnection, SqliteJournalMode}; +use futures_core::future::BoxFuture; +use sqlx_core::sql_str::AssertSqlSafe; +use std::str::FromStr; +use std::sync::atomic::Ordering; +use std::time::Duration; +use std::time::Instant; + +pub(crate) use sqlx_core::migrate::*; +use sqlx_core::query_scalar::query_scalar; + +impl MigrateDatabase for Sqlite { + async fn create_database(url: &str) -> Result<(), Error> { + let mut opts = SqliteConnectOptions::from_str(url)?.create_if_missing(true); + + // Since it doesn't make sense to include this flag in the connection URL, + // we just use an `AtomicBool` to pass it. + if super::CREATE_DB_WAL.load(Ordering::Acquire) { + opts = opts.journal_mode(SqliteJournalMode::Wal); + } + + // Opening a connection to sqlite creates the database + opts.connect() + .await? + // Ensure WAL mode tempfiles are cleaned up + .close() + .await?; + + Ok(()) + } + + async fn database_exists(url: &str) -> Result { + let options = SqliteConnectOptions::from_str(url)?; + + if options.in_memory { + Ok(true) + } else { + Ok(options.filename.exists()) + } + } + + async fn drop_database(url: &str) -> Result<(), Error> { + let options = SqliteConnectOptions::from_str(url)?; + + if !options.in_memory { + fs::remove_file(&*options.filename).await?; + } + + Ok(()) + } +} + +impl Migrate for SqliteConnection { + fn create_schema_if_not_exists<'e>( + &'e mut self, + schema_name: &'e str, + ) -> BoxFuture<'e, Result<(), MigrateError>> { + Box::pin(async move { + // Check if the schema already exists; if so, don't error. + let schema_version: Option = query_scalar(AssertSqlSafe(format!( + "PRAGMA {schema_name}.schema_version" + ))) + .fetch_optional(&mut *self) + .await?; + + if schema_version.is_some() { + return Ok(()); + } + + Err(MigrateError::CreateSchemasNotSupported( + format!("cannot create new schema {schema_name}; creation of additional schemas in SQLite requires attaching extra database files"), + )) + }) + } + + fn ensure_migrations_table<'e>( + &'e mut self, + table_name: &'e str, + ) -> BoxFuture<'e, Result<(), MigrateError>> { + Box::pin(async move { + // language=SQLite + self.execute(AssertSqlSafe(format!( + r#" +CREATE TABLE IF NOT EXISTS {table_name} ( + version BIGINT PRIMARY KEY, + description TEXT NOT NULL, + installed_on TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + success BOOLEAN NOT NULL, + checksum BLOB NOT NULL, + execution_time BIGINT NOT NULL +); + "# + ))) + .await?; + + Ok(()) + }) + } + + fn dirty_version<'e>( + &'e mut self, + table_name: &'e str, + ) -> BoxFuture<'e, Result, MigrateError>> { + Box::pin(async move { + // language=SQLite + let row: Option<(i64,)> = query_as(AssertSqlSafe(format!( + "SELECT version FROM {table_name} WHERE success = false ORDER BY version LIMIT 1" + ))) + .fetch_optional(self) + .await?; + + Ok(row.map(|r| r.0)) + }) + } + + fn list_applied_migrations<'e>( + &'e mut self, + table_name: &'e str, + ) -> BoxFuture<'e, Result, MigrateError>> { + Box::pin(async move { + // language=SQLite + let rows: Vec<(i64, Vec)> = query_as(AssertSqlSafe(format!( + "SELECT version, checksum FROM {table_name} ORDER BY version" + ))) + .fetch_all(self) + .await?; + + let migrations = rows + .into_iter() + .map(|(version, checksum)| AppliedMigration { + version, + checksum: checksum.into(), + }) + .collect(); + + Ok(migrations) + }) + } + + fn lock(&mut self) -> BoxFuture<'_, Result<(), MigrateError>> { + Box::pin(async move { Ok(()) }) + } + + fn unlock(&mut self) -> BoxFuture<'_, Result<(), MigrateError>> { + Box::pin(async move { Ok(()) }) + } + + fn apply<'e>( + &'e mut self, + table_name: &'e str, + migration: &'e Migration, + ) -> BoxFuture<'e, Result> { + Box::pin(async move { + let start = Instant::now(); + + if migration.no_tx { + execute_migration(self, table_name, migration).await?; + } else { + // Use a single transaction for the actual migration script and the essential bookkeeping so we never + // execute migrations twice. See https://github.com/launchbadge/sqlx/issues/1966. + // The `execution_time` however can only be measured for the whole transaction. This value _only_ exists for + // data lineage and debugging reasons, so it is not super important if it is lost. So we initialize it to -1 + // and update it once the actual transaction completed. + let mut tx = self.begin().await?; + execute_migration(&mut tx, table_name, migration).await?; + tx.commit().await?; + } + + // Update `elapsed_time`. + // NOTE: The process may disconnect/die at this point, so the elapsed time value might be lost. We accept + // this small risk since this value is not super important. + let elapsed = start.elapsed(); + + // language=SQLite + #[allow(clippy::cast_possible_truncation)] + let _ = query(AssertSqlSafe(format!( + r#" + UPDATE {table_name} + SET execution_time = ?1 + WHERE version = ?2 + "# + ))) + .bind(elapsed.as_nanos() as i64) + .bind(migration.version) + .execute(self) + .await?; + + Ok(elapsed) + }) + } + + fn revert<'e>( + &'e mut self, + table_name: &'e str, + migration: &'e Migration, + ) -> BoxFuture<'e, Result> { + Box::pin(async move { + let start = Instant::now(); + + if migration.no_tx { + revert_migration(self, table_name, migration).await?; + } else { + // Use a single transaction for the actual migration script and the essential bookkeeping so we never + // execute migrations twice. See https://github.com/launchbadge/sqlx/issues/1966. + let mut tx = self.begin().await?; + revert_migration(&mut tx, table_name, migration).await?; + tx.commit().await?; + } + + let elapsed = start.elapsed(); + + Ok(elapsed) + }) + } + + fn skip<'e>( + &'e mut self, + table_name: &'e str, + migration: &'e Migration, + ) -> BoxFuture<'e, Result<(), MigrateError>> { + Box::pin(async move { + // language=SQLite + let _ = query(AssertSqlSafe(format!( + r#" + INSERT INTO {table_name} ( version, description, success, checksum, execution_time ) + VALUES ( ?1, ?2, TRUE, ?3, -1 ) + "# + ))) + .bind(migration.version) + .bind(&*migration.description) + .bind(&*migration.checksum) + .execute(self) + .await?; + + Ok(()) + }) + } +} + +async fn execute_migration( + conn: &mut SqliteConnection, + table_name: &str, + migration: &Migration, +) -> Result<(), MigrateError> { + let _ = conn + .execute(migration.sql.clone()) + .await + .map_err(|e| MigrateError::ExecuteMigration(e, migration.version))?; + + // language=SQLite + let _ = query(AssertSqlSafe(format!( + r#" + INSERT INTO {table_name} ( version, description, success, checksum, execution_time ) + VALUES ( ?1, ?2, TRUE, ?3, -1 ) + "# + ))) + .bind(migration.version) + .bind(&*migration.description) + .bind(&*migration.checksum) + .execute(conn) + .await?; + + Ok(()) +} + +async fn revert_migration( + conn: &mut SqliteConnection, + table_name: &str, + migration: &Migration, +) -> Result<(), MigrateError> { + let _ = conn + .execute(migration.sql.clone()) + .await + .map_err(|e| MigrateError::ExecuteMigration(e, migration.version))?; + + // language=SQLite + let _ = query(AssertSqlSafe(format!( + r#" + DELETE FROM {table_name} + WHERE version = ?1 + "# + ))) + .bind(migration.version) + .execute(conn) + .await?; + + Ok(()) +} diff --git a/vendor/sqlx-sqlite/src/options/auto_vacuum.rs b/vendor/sqlx-sqlite/src/options/auto_vacuum.rs new file mode 100755 index 000000000000..582631c5bd63 --- /dev/null +++ b/vendor/sqlx-sqlite/src/options/auto_vacuum.rs @@ -0,0 +1,38 @@ +use crate::error::Error; +use std::str::FromStr; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum SqliteAutoVacuum { + #[default] + None, + Full, + Incremental, +} + +impl SqliteAutoVacuum { + pub(crate) fn as_str(&self) -> &'static str { + match self { + SqliteAutoVacuum::None => "NONE", + SqliteAutoVacuum::Full => "FULL", + SqliteAutoVacuum::Incremental => "INCREMENTAL", + } + } +} + +impl FromStr for SqliteAutoVacuum { + type Err = Error; + + fn from_str(s: &str) -> Result { + Ok(match &*s.to_ascii_lowercase() { + "none" => SqliteAutoVacuum::None, + "full" => SqliteAutoVacuum::Full, + "incremental" => SqliteAutoVacuum::Incremental, + + _ => { + return Err(Error::Configuration( + format!("unknown value {s:?} for `auto_vacuum`").into(), + )); + } + }) + } +} diff --git a/vendor/sqlx-sqlite/src/options/connect.rs b/vendor/sqlx-sqlite/src/options/connect.rs new file mode 100755 index 000000000000..cfa25872b2c1 --- /dev/null +++ b/vendor/sqlx-sqlite/src/options/connect.rs @@ -0,0 +1,83 @@ +use crate::{SqliteConnectOptions, SqliteConnection}; +use log::LevelFilter; +use sqlx_core::config; +use sqlx_core::connection::ConnectOptions; +use sqlx_core::error::Error; +use sqlx_core::executor::Executor; +use sqlx_core::sql_str::AssertSqlSafe; +use std::fmt::Write; +use std::str::FromStr; +use std::time::Duration; +use url::Url; + +impl ConnectOptions for SqliteConnectOptions { + type Connection = SqliteConnection; + + fn from_url(url: &Url) -> Result { + // SQLite URL parsing is handled specially; + // we want to treat the following URLs as equivalent: + // + // * sqlite:foo.db + // * sqlite://foo.db + // + // If we used `Url::path()`, the latter would return an empty string + // because `foo.db` gets parsed as the hostname. + Self::from_str(url.as_str()) + } + + fn to_url_lossy(&self) -> Url { + self.build_url() + } + + async fn connect(&self) -> Result + where + Self::Connection: Sized, + { + let mut conn = SqliteConnection::establish(self).await?; + + // Execute PRAGMAs + conn.execute(AssertSqlSafe(self.pragma_string())).await?; + + if !self.collations.is_empty() { + let mut locked = conn.lock_handle().await?; + + for collation in &self.collations { + collation.create(&mut locked.guard.handle)?; + } + } + + Ok(conn) + } + + fn log_statements(mut self, level: LevelFilter) -> Self { + self.log_settings.log_statements(level); + self + } + + fn log_slow_statements(mut self, level: LevelFilter, duration: Duration) -> Self { + self.log_settings.log_slow_statements(level, duration); + self + } + + fn __unstable_apply_driver_config( + self, + config: &config::drivers::Config, + ) -> crate::Result { + self.apply_driver_config(&config.sqlite) + } +} + +impl SqliteConnectOptions { + /// Collect all `PRAMGA` commands into a single string + pub(crate) fn pragma_string(&self) -> String { + let mut string = String::new(); + + for (key, opt_value) in &self.pragmas { + if let Some(value) = opt_value { + write!(string, "PRAGMA {key} = {value}; ").ok(); + } + } + + string + } +} diff --git a/vendor/sqlx-sqlite/src/options/journal_mode.rs b/vendor/sqlx-sqlite/src/options/journal_mode.rs new file mode 100755 index 000000000000..5750ce97ec1f --- /dev/null +++ b/vendor/sqlx-sqlite/src/options/journal_mode.rs @@ -0,0 +1,50 @@ +use crate::error::Error; +use std::str::FromStr; + +/// Refer to [SQLite documentation] for the meaning of the database journaling mode. +/// +/// [SQLite documentation]: https://www.sqlite.org/pragma.html#pragma_journal_mode +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum SqliteJournalMode { + Delete, + Truncate, + Persist, + Memory, + #[default] + Wal, + Off, +} + +impl SqliteJournalMode { + pub(crate) fn as_str(&self) -> &'static str { + match self { + SqliteJournalMode::Delete => "DELETE", + SqliteJournalMode::Truncate => "TRUNCATE", + SqliteJournalMode::Persist => "PERSIST", + SqliteJournalMode::Memory => "MEMORY", + SqliteJournalMode::Wal => "WAL", + SqliteJournalMode::Off => "OFF", + } + } +} + +impl FromStr for SqliteJournalMode { + type Err = Error; + + fn from_str(s: &str) -> Result { + Ok(match &*s.to_ascii_lowercase() { + "delete" => SqliteJournalMode::Delete, + "truncate" => SqliteJournalMode::Truncate, + "persist" => SqliteJournalMode::Persist, + "memory" => SqliteJournalMode::Memory, + "wal" => SqliteJournalMode::Wal, + "off" => SqliteJournalMode::Off, + + _ => { + return Err(Error::Configuration( + format!("unknown value {s:?} for `journal_mode`").into(), + )); + } + }) + } +} diff --git a/vendor/sqlx-sqlite/src/options/locking_mode.rs b/vendor/sqlx-sqlite/src/options/locking_mode.rs new file mode 100755 index 000000000000..99afd43eef69 --- /dev/null +++ b/vendor/sqlx-sqlite/src/options/locking_mode.rs @@ -0,0 +1,38 @@ +use crate::error::Error; +use std::str::FromStr; + +/// Refer to [SQLite documentation] for the meaning of the connection locking mode. +/// +/// [SQLite documentation]: https://www.sqlite.org/pragma.html#pragma_locking_mode +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum SqliteLockingMode { + #[default] + Normal, + Exclusive, +} + +impl SqliteLockingMode { + pub(crate) fn as_str(&self) -> &'static str { + match self { + SqliteLockingMode::Normal => "NORMAL", + SqliteLockingMode::Exclusive => "EXCLUSIVE", + } + } +} + +impl FromStr for SqliteLockingMode { + type Err = Error; + + fn from_str(s: &str) -> Result { + Ok(match &*s.to_ascii_lowercase() { + "normal" => SqliteLockingMode::Normal, + "exclusive" => SqliteLockingMode::Exclusive, + + _ => { + return Err(Error::Configuration( + format!("unknown value {s:?} for `locking_mode`").into(), + )); + } + }) + } +} diff --git a/vendor/sqlx-sqlite/src/options/mod.rs b/vendor/sqlx-sqlite/src/options/mod.rs new file mode 100755 index 000000000000..0cafc4d08c4c --- /dev/null +++ b/vendor/sqlx-sqlite/src/options/mod.rs @@ -0,0 +1,675 @@ +use std::path::Path; + +mod auto_vacuum; +mod connect; +mod journal_mode; +mod locking_mode; +mod parse; +mod synchronous; + +use crate::connection::LogSettings; +pub use auto_vacuum::SqliteAutoVacuum; +pub use journal_mode::SqliteJournalMode; +pub use locking_mode::SqliteLockingMode; +use std::cmp::Ordering; +use std::sync::Arc; +use std::{borrow::Cow, time::Duration}; +pub use synchronous::SqliteSynchronous; + +use crate::common::DebugFn; +use crate::connection::collation::Collation; +use sqlx_core::{config, IndexMap}; + +/// Options and flags which can be used to configure a SQLite connection. +/// +/// A value of `SqliteConnectOptions` can be parsed from a connection URL, +/// as described by [SQLite](https://www.sqlite.org/uri.html). +/// +/// This type also implements [`FromStr`][std::str::FromStr] so you can parse it from a string +/// containing a connection URL and then further adjust options if necessary (see example below). +/// +/// | URL | Description | +/// | -- | -- | +/// `sqlite::memory:` | Open an in-memory database. | +/// `sqlite:data.db` | Open the file `data.db` in the current directory. | +/// `sqlite://data.db` | Open the file `data.db` in the current directory. | +/// `sqlite:///data.db` | Open the file `data.db` from the root (`/`) directory. | +/// `sqlite://data.db?mode=ro` | Open the file `data.db` for read-only access. | +/// +/// # Example +/// +/// ```rust,no_run +/// # async fn example() -> sqlx::Result<()> { +/// use sqlx::ConnectOptions; +/// use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePool}; +/// use std::str::FromStr; +/// +/// let opts = SqliteConnectOptions::from_str("sqlite://data.db")? +/// .journal_mode(SqliteJournalMode::Wal) +/// .read_only(true); +/// +/// // use in a pool +/// let pool = SqlitePool::connect_with(opts).await?; +/// +/// // or connect directly +/// # let opts = SqliteConnectOptions::from_str("sqlite://data.db")?; +/// let conn = opts.connect().await?; +/// # +/// # Ok(()) +/// # } +/// ``` +#[derive(Clone, Debug)] +pub struct SqliteConnectOptions { + pub(crate) filename: Cow<'static, Path>, + pub(crate) in_memory: bool, + pub(crate) read_only: bool, + pub(crate) create_if_missing: bool, + pub(crate) shared_cache: bool, + pub(crate) statement_cache_capacity: usize, + pub(crate) busy_timeout: Duration, + pub(crate) log_settings: LogSettings, + pub(crate) immutable: bool, + pub(crate) vfs: Option>, + + pub(crate) pragmas: IndexMap, Option>>, + + /// Extensions are specified as a pair of \, the majority + /// of SQLite extensions will use the default entry points specified in the docs, these should + /// be added to the map with a `None` value. + /// + #[cfg(feature = "load-extension")] + pub(crate) extensions: IndexMap, Option>>, + + pub(crate) command_channel_size: usize, + pub(crate) row_channel_size: usize, + + pub(crate) collations: Vec, + + pub(crate) serialized: bool, + pub(crate) thread_name: Arc String + Send + Sync + 'static>>, + + pub(crate) optimize_on_close: OptimizeOnClose, + + #[cfg(feature = "regexp")] + pub(crate) register_regexp_function: bool, +} + +#[derive(Clone, Debug)] +pub enum OptimizeOnClose { + Enabled { analysis_limit: Option }, + Disabled, +} + +impl Default for SqliteConnectOptions { + fn default() -> Self { + Self::new() + } +} + +impl SqliteConnectOptions { + /// Construct `Self` with default options. + /// + /// See the source of this method for the current defaults. + pub fn new() -> Self { + let mut pragmas: IndexMap, Option>> = IndexMap::new(); + + // Standard pragmas + // + // Most of these don't actually need to be sent because they would be set to their + // default values anyway. See the SQLite documentation for default values of these PRAGMAs: + // https://www.sqlite.org/pragma.html + // + // However, by inserting into the map here, we can ensure that they're set in the proper + // order, even if they're overwritten later by their respective setters or + // directly by `pragma()` + + // SQLCipher special case: if the `key` pragma is set, it must be executed first. + pragmas.insert("key".into(), None); + + // Other SQLCipher pragmas that has to be after the key, but before any other operation on the database. + // https://www.zetetic.net/sqlcipher/sqlcipher-api/ + + // Bytes of the database file that is not encrypted + // Default for SQLCipher v4 is 0 + // If greater than zero 'cipher_salt' pragma must be also defined + pragmas.insert("cipher_plaintext_header_size".into(), None); + + // Allows to provide salt manually + // By default SQLCipher sets salt automatically, use only in conjunction with + // 'cipher_plaintext_header_size' pragma + pragmas.insert("cipher_salt".into(), None); + + // Number of iterations used in PBKDF2 key derivation. + // Default for SQLCipher v4 is 256000 + pragmas.insert("kdf_iter".into(), None); + + // Define KDF algorithm to be used. + // Default for SQLCipher v4 is PBKDF2_HMAC_SHA512. + pragmas.insert("cipher_kdf_algorithm".into(), None); + + // Enable or disable HMAC functionality. + // Default for SQLCipher v4 is 1. + pragmas.insert("cipher_use_hmac".into(), None); + + // Set default encryption settings depending on the version 1,2,3, or 4. + pragmas.insert("cipher_compatibility".into(), None); + + // Page size of encrypted database. + // Default for SQLCipher v4 is 4096. + pragmas.insert("cipher_page_size".into(), None); + + // Choose algorithm used for HMAC. + // Default for SQLCipher v4 is HMAC_SHA512. + pragmas.insert("cipher_hmac_algorithm".into(), None); + + // Normally, page_size must be set before any other action on the database. + // Defaults to 4096 for new databases. + pragmas.insert("page_size".into(), None); + + // locking_mode should be set before journal_mode: + // https://www.sqlite.org/wal.html#use_of_wal_without_shared_memory + pragmas.insert("locking_mode".into(), None); + + // `auto_vacuum` needs to be executed before `journal_mode`, if set. + // + // Otherwise, a change in the `journal_mode` setting appears to mark even an empty database as dirty, + // requiring a `vacuum` command to be executed to actually apply the new `auto_vacuum` setting. + pragmas.insert("auto_vacuum".into(), None); + + // Don't set `journal_mode` unless the user requested it. + // WAL mode is a permanent setting for created databases and changing into or out of it + // requires an exclusive lock that can't be waited on with `sqlite3_busy_timeout()`. + // https://github.com/launchbadge/sqlx/pull/1930#issuecomment-1168165414 + pragmas.insert("journal_mode".into(), None); + + // We choose to enable foreign key enforcement by default, though SQLite normally + // leaves it off for backward compatibility: https://www.sqlite.org/foreignkeys.html#fk_enable + pragmas.insert("foreign_keys".into(), Some("ON".into())); + + // The `synchronous` pragma defaults to FULL + // https://www.sqlite.org/compile.html#default_synchronous. + pragmas.insert("synchronous".into(), None); + + // Soft limit on the number of rows that `ANALYZE` touches per index. + pragmas.insert("analysis_limit".into(), None); + + Self { + filename: Cow::Borrowed(Path::new(":memory:")), + in_memory: false, + read_only: false, + create_if_missing: false, + shared_cache: false, + statement_cache_capacity: 100, + busy_timeout: Duration::from_secs(5), + log_settings: Default::default(), + immutable: false, + vfs: None, + pragmas, + #[cfg(feature = "load-extension")] + extensions: Default::default(), + collations: Default::default(), + serialized: false, + thread_name: Arc::new(DebugFn(|id| format!("sqlx-sqlite-worker-{id}"))), + command_channel_size: 50, + row_channel_size: 50, + optimize_on_close: OptimizeOnClose::Disabled, + #[cfg(feature = "regexp")] + register_regexp_function: false, + } + } + + /// Sets the name of the database file. + /// + /// This is a low-level API, and SQLx will apply no special treatment for `":memory:"` as an + /// in-memory database using this method. Using [`SqliteConnectOptions::from_str()`][SqliteConnectOptions#from_str] may be + /// preferred for simple use cases. + pub fn filename(mut self, filename: impl AsRef) -> Self { + self.filename = Cow::Owned(filename.as_ref().to_owned()); + self + } + + /// Gets the current name of the database file. + pub fn get_filename(&self) -> &Path { + &self.filename + } + + /// Set the enforcement of [foreign key constraints](https://www.sqlite.org/pragma.html#pragma_foreign_keys). + /// + /// SQLx chooses to enable this by default so that foreign keys function as expected, + /// compared to other database flavors. + pub fn foreign_keys(self, on: bool) -> Self { + self.pragma("foreign_keys", if on { "ON" } else { "OFF" }) + } + + /// Set the [`SQLITE_OPEN_MEMORY` flag](https://sqlite.org/c3ref/open.html). + /// + /// By default, this is disabled. + pub fn in_memory(mut self, in_memory: bool) -> Self { + self.in_memory = in_memory; + self + } + + /// Set the [`SQLITE_OPEN_SHAREDCACHE` flag](https://sqlite.org/sharedcache.html). + /// + /// By default, this is disabled. + pub fn shared_cache(mut self, on: bool) -> Self { + self.shared_cache = on; + self + } + + /// Sets the [journal mode](https://www.sqlite.org/pragma.html#pragma_journal_mode) for the database connection. + /// + /// Journal modes are ephemeral per connection, with the exception of the + /// [Write-Ahead Log (WAL) mode](https://www.sqlite.org/wal.html). + /// + /// A database created in WAL mode retains the setting and will apply it to all connections + /// opened against it that don't set a `journal_mode`. + /// + /// Opening a connection to a database created in WAL mode with a different `journal_mode` will + /// erase the setting on the database, requiring an exclusive lock to do so. + /// You may get a `database is locked` (corresponding to `SQLITE_BUSY`) error if another + /// connection is accessing the database file at the same time. + /// + /// SQLx does not set a journal mode by default, to avoid unintentionally changing a database + /// into or out of WAL mode. + /// + /// The default journal mode for non-WAL databases is `DELETE`, or `MEMORY` for in-memory + /// databases. + /// + /// For consistency, any commands in `sqlx-cli` which create a SQLite database will create it + /// in WAL mode. + pub fn journal_mode(self, mode: SqliteJournalMode) -> Self { + self.pragma("journal_mode", mode.as_str()) + } + + /// Sets the [locking mode](https://www.sqlite.org/pragma.html#pragma_locking_mode) for the database connection. + /// + /// The default locking mode is NORMAL. + pub fn locking_mode(self, mode: SqliteLockingMode) -> Self { + self.pragma("locking_mode", mode.as_str()) + } + + /// Sets the [access mode](https://www.sqlite.org/c3ref/open.html) to open the database + /// for read-only access. + pub fn read_only(mut self, read_only: bool) -> Self { + self.read_only = read_only; + self + } + + /// Sets the [access mode](https://www.sqlite.org/c3ref/open.html) to create the database file + /// if the file does not exist. + /// + /// By default, a new file **will not be created** if one is not found. + pub fn create_if_missing(mut self, create: bool) -> Self { + self.create_if_missing = create; + self + } + + /// Sets the capacity of the connection's statement cache in a number of stored + /// distinct statements. Caching is handled using LRU, meaning when the + /// amount of queries hits the defined limit, the oldest statement will get + /// dropped. + /// + /// The default cache capacity is 100 statements. + pub fn statement_cache_capacity(mut self, capacity: usize) -> Self { + self.statement_cache_capacity = capacity; + self + } + + /// Sets a timeout value to wait when the database is locked, before + /// returning a busy timeout error. + /// + /// The default busy timeout is 5 seconds. + pub fn busy_timeout(mut self, timeout: Duration) -> Self { + self.busy_timeout = timeout; + self + } + + /// Sets the [synchronous](https://www.sqlite.org/pragma.html#pragma_synchronous) setting for the database connection. + /// + /// The default synchronous settings is FULL. However, if durability is not a concern, + /// then NORMAL is normally all one needs in WAL mode. + pub fn synchronous(self, synchronous: SqliteSynchronous) -> Self { + self.pragma("synchronous", synchronous.as_str()) + } + + /// Sets the [auto_vacuum](https://www.sqlite.org/pragma.html#pragma_auto_vacuum) setting for the database connection. + /// + /// The default auto_vacuum setting is NONE. + /// + /// For existing databases, a change to this value does not take effect unless a + /// [`VACUUM` command](https://www.sqlite.org/lang_vacuum.html) is executed. + pub fn auto_vacuum(self, auto_vacuum: SqliteAutoVacuum) -> Self { + self.pragma("auto_vacuum", auto_vacuum.as_str()) + } + + /// Sets the [page_size](https://www.sqlite.org/pragma.html#pragma_page_size) setting for the database connection. + /// + /// The default page_size setting is 4096. + /// + /// For existing databases, a change to this value does not take effect unless a + /// [`VACUUM` command](https://www.sqlite.org/lang_vacuum.html) is executed. + /// However, it cannot be changed in WAL mode. + pub fn page_size(self, page_size: u32) -> Self { + self.pragma("page_size", page_size.to_string()) + } + + /// Sets custom initial pragma for the database connection. + pub fn pragma(mut self, key: K, value: V) -> Self + where + K: Into>, + V: Into>, + { + self.pragmas.insert(key.into(), Some(value.into())); + self + } + + /// Add a custom collation for comparing strings in SQL. + /// + /// If a collation with the same name already exists, it will be replaced. + /// + /// See [`sqlite3_create_collation()`](https://www.sqlite.org/c3ref/create_collation.html) for details. + /// + /// Note this excerpt: + /// > The collating function must obey the following properties for all strings A, B, and C: + /// > + /// > If A==B then B==A. + /// > If A==B and B==C then A==C. + /// > If A\A. + /// > If A + /// > If a collating function fails any of the above constraints and that collating function is + /// > registered and used, then the behavior of SQLite is undefined. + pub fn collation(mut self, name: N, collate: F) -> Self + where + N: Into>, + F: Fn(&str, &str) -> Ordering + Send + Sync + 'static, + { + self.collations.push(Collation::new(name, collate)); + self + } + + /// Set to `true` to signal to SQLite that the database file is on read-only media. + /// + /// If enabled, SQLite assumes the database file _cannot_ be modified, even by higher + /// privileged processes, and so disables locking and change detection. This is intended + /// to improve performance but can produce incorrect query results or errors if the file + /// _does_ change. + /// + /// Note that this is different from the `SQLITE_OPEN_READONLY` flag set by + /// [`.read_only()`][Self::read_only], though the documentation suggests that this + /// does _imply_ `SQLITE_OPEN_READONLY`. + /// + /// See [`sqlite3_open`](https://www.sqlite.org/capi3ref.html#sqlite3_open) (subheading + /// "URI Filenames") for details. + pub fn immutable(mut self, immutable: bool) -> Self { + self.immutable = immutable; + self + } + + /// Sets the [threading mode](https://www.sqlite.org/threadsafe.html) for the database connection. + /// + /// The default setting is `false` corresponding to using `OPEN_NOMUTEX`. + /// If set to `true` then `OPEN_FULLMUTEX`. + /// + /// See [open](https://www.sqlite.org/c3ref/open.html) for more details. + /// + /// ### Note + /// Setting this to `true` may help if you are getting access violation errors or segmentation + /// faults, but will also incur a significant performance penalty. You should leave this + /// set to `false` if at all possible. + /// + /// If you do end up needing to set this to `true` for some reason, please + /// [open an issue](https://github.com/launchbadge/sqlx/issues/new/choose) as this may indicate + /// a concurrency bug in SQLx. Please provide clear instructions for reproducing the issue, + /// including a sample database schema if applicable. + pub fn serialized(mut self, serialized: bool) -> Self { + self.serialized = serialized; + self + } + + /// Provide a callback to generate the name of the background worker thread. + /// + /// The value passed to the callback is an auto-incremented integer for use as the thread ID. + pub fn thread_name( + mut self, + generator: impl Fn(u64) -> String + Send + Sync + 'static, + ) -> Self { + self.thread_name = Arc::new(DebugFn(generator)); + self + } + + /// Set the maximum number of commands to buffer for the worker thread before backpressure is + /// applied. + /// + /// Given that most commands sent to the worker thread involve waiting for a result, + /// the command channel is unlikely to fill up unless a lot queries are executed in a short + /// period but cancelled before their full resultsets are returned. + pub fn command_buffer_size(mut self, size: usize) -> Self { + self.command_channel_size = size; + self + } + + /// Set the maximum number of rows to buffer back to the calling task when a query is executed. + /// + /// If the calling task cannot keep up, backpressure will be applied to the worker thread + /// in order to limit CPU and memory usage. + pub fn row_buffer_size(mut self, size: usize) -> Self { + self.row_channel_size = size; + self + } + + /// Sets the [`vfs`](https://www.sqlite.org/vfs.html) parameter of the database connection. + /// + /// The default value is empty, and sqlite will use the default VFS object depending on the + /// operating system. + pub fn vfs(mut self, vfs_name: impl Into>) -> Self { + self.vfs = Some(vfs_name.into()); + self + } + + /// Add a [SQLite extension](https://www.sqlite.org/loadext.html) to be loaded into the database + /// connection at startup, using the default entrypoint. + /// + /// Most common SQLite extensions can be loaded using this method. + /// For extensions where you need to override the entry point, + /// use [`.extension_with_entrypoint()`]. + /// + /// Multiple extensions can be loaded by calling this method, + /// or [`.extension_with_entrypoint()`] where applicable, + /// once for each extension. + /// + /// Extension loading is only enabled during the initialization of the connection, + /// and disabled before `connect()` returns by setting + /// [`SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION`] to 0. + /// + /// This will not enable the SQL `load_extension()` function. + /// + /// [`SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION`]: https://www.sqlite.org/c3ref/c_dbconfig_defensive.html#sqlitedbconfigenableloadextension + /// [`.extension_with_entrypoint()`]: Self::extension_with_entrypoint + /// + /// # Safety + /// This causes arbitrary DLLs on the filesystem to be loaded at runtime, + /// which can easily result in undefined behavior, memory corruption, + /// or exploitable vulnerabilities if misused. + /// + /// It is not possible to provide a truly safe version of this API. + /// + /// Use this method with care, and only load extensions that you trust. + /// + /// # Example + /// ```rust,no_run + /// # use sqlx_core::error::Error; + /// # use std::str::FromStr; + /// # use sqlx_sqlite::SqliteConnectOptions; + /// # fn options() -> Result { + /// let mut options = SqliteConnectOptions::from_str("sqlite://data.db")?; + /// + /// // SAFETY: these are trusted extensions. + /// unsafe { + /// options = options + /// .extension("vsv") + /// .extension("mod_spatialite"); + /// } + /// + /// # Ok(options) + /// # } + /// ``` + #[cfg(feature = "load-extension")] + #[cfg_attr(docsrs, doc(cfg(feature = "sqlite-load-extension")))] + pub unsafe fn extension(mut self, extension_name: impl Into>) -> Self { + self.extensions.insert(extension_name.into(), None); + self + } + + /// Add a [SQLite extension](https://www.sqlite.org/loadext.html) to be loaded into the database + /// connection at startup, overriding the entrypoint. + /// + /// See also [`.extension()`] for extensions using the standard entrypoint name + /// `sqlite3_extension_init` or `sqlite3__init`. + /// + /// Multiple extensions can be loaded by calling this method, + /// or [`.extension()`] where applicable, + /// once for each extension. + /// + /// Extension loading is only enabled during the initialization of the connection, + /// and disabled before `connect()` returns by setting + /// [`SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION`] to 0. + /// + /// This will not enable the SQL `load_extension()` function. + /// + /// [`SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION`]: https://www.sqlite.org/c3ref/c_dbconfig_defensive.html#sqlitedbconfigenableloadextension + /// [`.extension_with_entrypoint()`]: Self::extension_with_entrypoint + /// + /// # Safety + /// This causes arbitrary DLLs on the filesystem to be loaded at runtime, + /// which can easily result in undefined behavior, memory corruption, + /// or exploitable vulnerabilities if misused. + /// + /// If you specify the wrong entrypoint name, it _may_ simply result in an error, + /// or it may end up invoking the wrong routine, leading to undefined behavior. + /// + /// It is not possible to provide a truly safe version of this API. + /// + /// Use this method with care, only load extensions that you trust, + /// and double-check the entrypoint name with the extension's documentation or source code. + #[cfg(feature = "load-extension")] + #[cfg_attr(docsrs, doc(cfg(feature = "sqlite-load-extension")))] + pub unsafe fn extension_with_entrypoint( + mut self, + extension_name: impl Into>, + entry_point: impl Into>, + ) -> Self { + self.extensions + .insert(extension_name.into(), Some(entry_point.into())); + self + } + + /// Execute `PRAGMA optimize;` on the SQLite connection before closing. + /// + /// The SQLite manual recommends using this for long-lived databases. + /// + /// This will collect and store statistics about the layout of data in your tables to help the query planner make better decisions. + /// Over the connection's lifetime, the query planner will make notes about which tables could use up-to-date statistics so this + /// command doesn't have to scan the whole database every time. Thus, the best time to execute this is on connection close. + /// + /// `analysis_limit` sets a soft limit on the maximum number of rows to scan per index. + /// It is equivalent to setting [`Self::analysis_limit`] but only takes effect for the `PRAGMA optimize;` call + /// and does not affect the behavior of any `ANALYZE` statements made during the connection's lifetime. + /// + /// If not `None`, the `analysis_limit` here overrides the global `analysis_limit` setting, + /// but only for the `PRAGMA optimize;` call. + /// + /// Not enabled by default. + /// + /// See [the SQLite manual](https://www.sqlite.org/lang_analyze.html#automatically_running_analyze) for details. + pub fn optimize_on_close( + mut self, + enabled: bool, + analysis_limit: impl Into>, + ) -> Self { + self.optimize_on_close = if enabled { + OptimizeOnClose::Enabled { + analysis_limit: (analysis_limit.into()), + } + } else { + OptimizeOnClose::Disabled + }; + self + } + + /// Set a soft limit on the number of rows that `ANALYZE` touches per index. + /// + /// This also affects `PRAGMA optimize` which is set by [Self::optimize_on_close]. + /// + /// The value recommended by SQLite is `400`. There is no default. + /// + /// See [the SQLite manual](https://www.sqlite.org/lang_analyze.html#approx) for details. + pub fn analysis_limit(mut self, limit: impl Into>) -> Self { + if let Some(limit) = limit.into() { + return self.pragma("analysis_limit", limit.to_string()); + } + self.pragmas.insert("analysis_limit".into(), None); + self + } + + /// Register a regexp function that allows using regular expressions in queries. + /// + /// ``` + /// # use std::str::FromStr; + /// # use sqlx::{ConnectOptions, Connection, Row}; + /// # use sqlx_sqlite::SqliteConnectOptions; + /// # async fn run() -> sqlx::Result<()> { + /// let mut sqlite = SqliteConnectOptions::from_str("sqlite://:memory:")? + /// .with_regexp() + /// .connect() + /// .await?; + /// let tables = sqlx::query("SELECT name FROM sqlite_schema WHERE name REGEXP 'foo(\\d+)bar'") + /// .fetch_all(&mut sqlite) + /// .await?; + /// # Ok(()) + /// # } + /// ``` + /// + /// This uses the [`regex`] crate, and is only enabled when you enable the `regex` feature is enabled on sqlx + #[cfg(feature = "regexp")] + pub fn with_regexp(mut self) -> Self { + self.register_regexp_function = true; + self + } + + #[cfg_attr(not(feature = "load-extension"), expect(unused_mut))] + pub(crate) fn apply_driver_config( + mut self, + config: &config::drivers::SqliteConfig, + ) -> crate::Result { + #[cfg(feature = "load-extension")] + for extension in &config.unsafe_load_extensions { + // SAFETY: the documentation warns the user about loading extensions + match extension { + config::drivers::SqliteExtension::Path(path) => { + self = unsafe { self.extension(path.clone()) } + } + config::drivers::SqliteExtension::PathWithEntrypoint { path, entrypoint } => { + self = + unsafe { self.extension_with_entrypoint(path.clone(), entrypoint.clone()) } + } + } + } + + #[cfg(not(feature = "load-extension"))] + if !config.unsafe_load_extensions.is_empty() { + return Err(sqlx_core::Error::Configuration( + format!( + "sqlx.toml specifies `drivers.sqlite.unsafe-load-extensions = {:?}` \ + but extension loading is not enabled; \ + enable the `sqlite-load-extension` feature of SQLx to use SQLite extensions", + config.unsafe_load_extensions, + ) + .into(), + )); + } + + Ok(self) + } +} diff --git a/vendor/sqlx-sqlite/src/options/parse.rs b/vendor/sqlx-sqlite/src/options/parse.rs new file mode 100755 index 000000000000..0530f4204cf7 --- /dev/null +++ b/vendor/sqlx-sqlite/src/options/parse.rs @@ -0,0 +1,231 @@ +use std::borrow::Cow; +use std::path::{Path, PathBuf}; +use std::str::FromStr; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use percent_encoding::{percent_decode_str, percent_encode, AsciiSet}; +use url::Url; + +use crate::error::Error; +use crate::SqliteConnectOptions; + +// https://www.sqlite.org/uri.html + +static IN_MEMORY_DB_SEQ: AtomicUsize = AtomicUsize::new(0); + +impl SqliteConnectOptions { + pub(crate) fn from_db_and_params(database: &str, params: Option<&str>) -> Result { + let mut options = Self::default(); + + if database == ":memory:" { + options.in_memory = true; + options.shared_cache = true; + let seqno = IN_MEMORY_DB_SEQ.fetch_add(1, Ordering::Relaxed); + options.filename = Cow::Owned(PathBuf::from(format!("file:sqlx-in-memory-{seqno}"))); + } else { + // % decode to allow for `?` or `#` in the filename + options.filename = Cow::Owned( + Path::new( + &*percent_decode_str(database) + .decode_utf8() + .map_err(Error::config)?, + ) + .to_path_buf(), + ); + } + + if let Some(params) = params { + for (key, value) in url::form_urlencoded::parse(params.as_bytes()) { + match &*key { + // The mode query parameter determines if the new database is opened read-only, + // read-write, read-write and created if it does not exist, or that the + // database is a pure in-memory database that never interacts with disk, + // respectively. + "mode" => { + match &*value { + "ro" => { + options.read_only = true; + } + + // default + "rw" => {} + + "rwc" => { + options.create_if_missing = true; + } + + "memory" => { + options.in_memory = true; + options.shared_cache = true; + } + + _ => { + return Err(Error::Configuration( + format!("unknown value {value:?} for `mode`").into(), + )); + } + } + } + + // The cache query parameter specifies the cache behaviour across multiple + // connections to the same database within the process. A shared cache is + // essential for persisting data across connections to an in-memory database. + "cache" => match &*value { + "private" => { + options.shared_cache = false; + } + + "shared" => { + options.shared_cache = true; + } + + _ => { + return Err(Error::Configuration( + format!("unknown value {value:?} for `cache`").into(), + )); + } + }, + + "immutable" => match &*value { + "true" | "1" => { + options.immutable = true; + } + "false" | "0" => { + options.immutable = false; + } + _ => { + return Err(Error::Configuration( + format!("unknown value {value:?} for `immutable`").into(), + )); + } + }, + + "vfs" => options.vfs = Some(Cow::Owned(value.into_owned())), + + _ => { + return Err(Error::Configuration( + format!("unknown query parameter `{key}` while parsing connection URL") + .into(), + )); + } + } + } + } + + Ok(options) + } + + pub(crate) fn build_url(&self) -> Url { + // https://url.spec.whatwg.org/#path-percent-encode-set + static PATH_ENCODE_SET: AsciiSet = percent_encoding::CONTROLS + .add(b' ') + .add(b'"') + .add(b'#') + .add(b'<') + .add(b'>') + .add(b'?') + .add(b'`') + .add(b'{') + .add(b'}'); + + let filename_encoded = percent_encode( + self.filename.as_os_str().as_encoded_bytes(), + &PATH_ENCODE_SET, + ); + + let mut url = Url::parse(&format!("sqlite://{filename_encoded}")) + .expect("BUG: generated un-parseable URL"); + + let mode = match (self.in_memory, self.create_if_missing, self.read_only) { + (true, _, _) => "memory", + (false, true, _) => "rwc", + (false, false, true) => "ro", + (false, false, false) => "rw", + }; + url.query_pairs_mut().append_pair("mode", mode); + + let cache = match self.shared_cache { + true => "shared", + false => "private", + }; + url.query_pairs_mut().append_pair("cache", cache); + + if self.immutable { + url.query_pairs_mut().append_pair("immutable", "true"); + } + + if let Some(vfs) = &self.vfs { + url.query_pairs_mut().append_pair("vfs", vfs); + } + + url + } +} + +impl FromStr for SqliteConnectOptions { + type Err = Error; + + fn from_str(mut url: &str) -> Result { + // remove scheme from the URL + url = url + .trim_start_matches("sqlite://") + .trim_start_matches("sqlite:"); + + let mut database_and_params = url.splitn(2, '?'); + + let database = database_and_params.next().unwrap_or_default(); + let params = database_and_params.next(); + + Self::from_db_and_params(database, params) + } +} + +#[test] +fn test_parse_in_memory() -> Result<(), Error> { + let options: SqliteConnectOptions = "sqlite::memory:".parse()?; + assert!(options.in_memory); + assert!(options.shared_cache); + + let options: SqliteConnectOptions = "sqlite://?mode=memory".parse()?; + assert!(options.in_memory); + assert!(options.shared_cache); + + let options: SqliteConnectOptions = "sqlite://:memory:".parse()?; + assert!(options.in_memory); + assert!(options.shared_cache); + + let options: SqliteConnectOptions = "sqlite://?mode=memory&cache=private".parse()?; + assert!(options.in_memory); + assert!(!options.shared_cache); + + Ok(()) +} + +#[test] +fn test_parse_read_only() -> Result<(), Error> { + let options: SqliteConnectOptions = "sqlite://a.db?mode=ro".parse()?; + assert!(options.read_only); + assert_eq!(&*options.filename.to_string_lossy(), "a.db"); + + Ok(()) +} + +#[test] +fn test_parse_shared_in_memory() -> Result<(), Error> { + let options: SqliteConnectOptions = "sqlite://a.db?cache=shared".parse()?; + assert!(options.shared_cache); + assert_eq!(&*options.filename.to_string_lossy(), "a.db"); + + Ok(()) +} + +#[test] +fn it_returns_the_parsed_url() -> Result<(), Error> { + let url = "sqlite://test.db?mode=rw&cache=shared"; + let options: SqliteConnectOptions = url.parse()?; + + let expected_url = Url::parse(url).unwrap(); + assert_eq!(options.build_url(), expected_url); + + Ok(()) +} diff --git a/vendor/sqlx-sqlite/src/options/synchronous.rs b/vendor/sqlx-sqlite/src/options/synchronous.rs new file mode 100755 index 000000000000..709b805bc76e --- /dev/null +++ b/vendor/sqlx-sqlite/src/options/synchronous.rs @@ -0,0 +1,44 @@ +use crate::error::Error; +use std::str::FromStr; + +/// Refer to [SQLite documentation] for the meaning of various synchronous settings. +/// +/// [SQLite documentation]: https://www.sqlite.org/pragma.html#pragma_synchronous +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum SqliteSynchronous { + Off, + Normal, + #[default] + Full, + Extra, +} + +impl SqliteSynchronous { + pub(crate) fn as_str(&self) -> &'static str { + match self { + SqliteSynchronous::Off => "OFF", + SqliteSynchronous::Normal => "NORMAL", + SqliteSynchronous::Full => "FULL", + SqliteSynchronous::Extra => "EXTRA", + } + } +} + +impl FromStr for SqliteSynchronous { + type Err = Error; + + fn from_str(s: &str) -> Result { + Ok(match &*s.to_ascii_lowercase() { + "off" => SqliteSynchronous::Off, + "normal" => SqliteSynchronous::Normal, + "full" => SqliteSynchronous::Full, + "extra" => SqliteSynchronous::Extra, + + _ => { + return Err(Error::Configuration( + format!("unknown value {s:?} for `synchronous`").into(), + )); + } + }) + } +} diff --git a/vendor/sqlx-sqlite/src/query_result.rs b/vendor/sqlx-sqlite/src/query_result.rs new file mode 100755 index 000000000000..8c8c27fcf493 --- /dev/null +++ b/vendor/sqlx-sqlite/src/query_result.rs @@ -0,0 +1,40 @@ +use std::iter::{Extend, IntoIterator}; + +#[derive(Debug, Default)] +pub struct SqliteQueryResult { + pub(super) changes: u64, + pub(super) last_insert_rowid: i64, +} + +impl SqliteQueryResult { + pub fn rows_affected(&self) -> u64 { + self.changes + } + + pub fn last_insert_rowid(&self) -> i64 { + self.last_insert_rowid + } +} + +impl Extend for SqliteQueryResult { + fn extend>(&mut self, iter: T) { + for elem in iter { + self.changes += elem.changes; + self.last_insert_rowid = elem.last_insert_rowid; + } + } +} + +#[cfg(feature = "any")] +impl From for sqlx_core::any::AnyQueryResult { + fn from(done: SqliteQueryResult) -> Self { + let last_insert_id = match done.last_insert_rowid() { + 0 => None, + n => Some(n), + }; + sqlx_core::any::AnyQueryResult { + rows_affected: done.rows_affected(), + last_insert_id, + } + } +} diff --git a/vendor/sqlx-sqlite/src/regexp.rs b/vendor/sqlx-sqlite/src/regexp.rs new file mode 100755 index 000000000000..735200e9be9b --- /dev/null +++ b/vendor/sqlx-sqlite/src/regexp.rs @@ -0,0 +1,281 @@ +#![deny(missing_docs, clippy::pedantic)] +#![allow(clippy::cast_sign_loss)] // some lengths returned from sqlite3 are `i32`, but rust needs `usize` + +//! Here be dragons +//! +//! We need to register a custom REGEX implementation for sqlite +//! some useful resources: +//! - rusqlite has an example implementation: +//! - sqlite supports registering custom C functions: +//! - sqlite also supports a `A REGEXP B` syntax, but ONLY if the user implements `regex(B, A)` +//! - Note that A and B are indeed swapped: the regex comes first, the field comes second +//! - +//! - sqlx has a way to safely get a sqlite3 pointer: +//! - +//! - + +use libsqlite3_sys as ffi; +use log::error; +use regex::Regex; +use std::sync::Arc; + +/// The function name for sqlite3. This must be "regexp\0" +static FN_NAME: &[u8] = b"regexp\0"; + +/// Register the regex function with sqlite. +/// +/// Returns the result code of `sqlite3_create_function_v2` +pub fn register(sqlite3: *mut ffi::sqlite3) -> i32 { + unsafe { + ffi::sqlite3_create_function_v2( + // the database connection + sqlite3, + // the function name. Must be up to 255 bytes, and 0-terminated + FN_NAME.as_ptr().cast(), + // the number of arguments this function accepts. We want 2 arguments: The regex and the field + 2, + // we want all our strings to be UTF8, and this function will return the same output with the same inputs + ffi::SQLITE_UTF8 | ffi::SQLITE_DETERMINISTIC, + // pointer to user data. We're not using user data + std::ptr::null_mut(), + // xFunc to be executed when we are invoked + Some(sqlite3_regexp_func), + // xStep, should be NULL for scalar functions + None, + // xFinal, should be NULL for scalar functions + None, + // xDestroy, called when this function is deregistered. Should be used to clean up our pointer to user-data + None, + ) + } +} + +/// A function to be called on each invocation of `regex(REGEX, FIELD)` from sqlite3 +/// +/// - `ctx`: a pointer to the current sqlite3 context +/// - `n_arg`: The length of `args` +/// - `args`: the arguments of this function call +unsafe extern "C" fn sqlite3_regexp_func( + ctx: *mut ffi::sqlite3_context, + n_arg: i32, + args: *mut *mut ffi::sqlite3_value, +) { + // check the arg size. sqlite3 should already ensure this is only 2 args but we want to double check + if n_arg != 2 { + eprintln!("n_arg expected to be 2, is {n_arg}"); + ffi::sqlite3_result_error_code(ctx, ffi::SQLITE_CONSTRAINT_FUNCTION); + return; + } + + // arg0: Regex + let Some(regex) = get_regex_from_arg(ctx, *args, 0) else { + return; + }; + + // arg1: value + let Some(value) = get_text_from_arg(ctx, *args.add(1)) else { + return; + }; + + // if the regex matches the value, set the result int as 1, else as 0 + if regex.is_match(value) { + ffi::sqlite3_result_int(ctx, 1); + } else { + ffi::sqlite3_result_int(ctx, 0); + } +} + +/// Get the regex from the given `arg` at the given `index`. +/// +/// First this will check to see if the value exists in sqlite's `auxdata`. If it does, that regex will be returned. +/// sqlite is able to clean up this data at any point, but rust's [`Arc`] guarantees make sure things don't break. +/// +/// If this value does not exist in `auxdata`, [`try_load_value`] is called and a regex is created from this. If any of +/// those fail, a message is printed and `None` is returned. +/// +/// After this regex is created it is stored in `auxdata` and loaded again. If it fails to load, this means that +/// something inside of sqlite3 went wrong, and we return `None`. +/// +/// If this value is stored correctly, or if it already existed, the arc reference counter is increased and this value is returned. +unsafe fn get_regex_from_arg( + ctx: *mut ffi::sqlite3_context, + arg: *mut ffi::sqlite3_value, + index: i32, +) -> Option> { + // try to get the auxdata for this field + let ptr = ffi::sqlite3_get_auxdata(ctx, index); + if !ptr.is_null() { + // if we have it, turn it into an Arc. + // we need to make sure to call `increment_strong_count` because the returned `Arc` decrement this when it goes out of scope + let ptr = ptr as *const Regex; + Arc::increment_strong_count(ptr); + return Some(Arc::from_raw(ptr)); + } + // get the text for this field + let value = get_text_from_arg(ctx, arg)?; + // try to compile it into a regex + let regex = match Regex::new(value) { + Ok(regex) => Arc::new(regex), + Err(e) => { + error!("Invalid regex {value:?}: {e:?}"); + ffi::sqlite3_result_error_code(ctx, ffi::SQLITE_CONSTRAINT_FUNCTION); + return None; + } + }; + // set the regex as auxdata for the next time around + ffi::sqlite3_set_auxdata( + ctx, + index, + // make sure to call `Arc::clone` here, setting the strong count to 2. + // this will be cleaned up at 2 points: + // - when the returned arc goes out of scope + // - when sqlite decides to clean it up an calls `cleanup_arc_regex_pointer` + Arc::into_raw(Arc::clone(®ex)) as *mut _, + Some(cleanup_arc_regex_pointer), + ); + Some(regex) +} + +/// Get a text reference of the value of `arg`. Returns `None` for NULL values. +/// +/// For non-NULL values, `sqlite3_value_text()` is called directly, which lets SQLite +/// coerce INTEGER, REAL, and BLOB values to their text representation. This matches +/// the coercion behavior documented at . +/// +/// The returned `&str` is valid for lifetime `'a` which can be determined by the caller. This lifetime should **not** +/// outlive `ctx`. +unsafe fn get_text_from_arg<'a>( + ctx: *mut ffi::sqlite3_context, + arg: *mut ffi::sqlite3_value, +) -> Option<&'a str> { + let ty = ffi::sqlite3_value_type(arg); + if ty == ffi::SQLITE_NULL { + return None; + } + let ptr = ffi::sqlite3_value_text(arg); + let len = ffi::sqlite3_value_bytes(arg); + let slice = std::slice::from_raw_parts(ptr.cast(), len as usize); + match std::str::from_utf8(slice) { + Ok(result) => Some(result), + Err(e) => { + log::error!("Incoming text is not valid UTF8: {e:?}"); + ffi::sqlite3_result_error_code(ctx, ffi::SQLITE_CONSTRAINT_FUNCTION); + None + } + } +} + +/// Clean up the `Arc` that is stored in the given `ptr`. +unsafe extern "C" fn cleanup_arc_regex_pointer(ptr: *mut std::ffi::c_void) { + Arc::decrement_strong_count(ptr.cast::()); +} + +#[cfg(test)] +mod tests { + use sqlx::{ConnectOptions, Row}; + use std::str::FromStr; + + async fn test_db() -> crate::SqliteConnection { + let mut conn = crate::SqliteConnectOptions::from_str("sqlite://:memory:") + .unwrap() + .with_regexp() + .connect() + .await + .unwrap(); + sqlx::query("CREATE TABLE test (col TEXT NOT NULL)") + .execute(&mut conn) + .await + .unwrap(); + for i in 0..10 { + sqlx::query("INSERT INTO test VALUES (?)") + .bind(format!("value {i}")) + .execute(&mut conn) + .await + .unwrap(); + } + conn + } + + #[sqlx::test] + async fn test_regexp_does_not_fail() { + let mut conn = test_db().await; + let result = sqlx::query("SELECT col FROM test WHERE col REGEXP 'foo.*bar'") + .fetch_all(&mut conn) + .await + .expect("Could not execute query"); + assert!(result.is_empty()); + } + + #[sqlx::test] + async fn test_regexp_filters_correctly() { + let mut conn = test_db().await; + + let result = sqlx::query("SELECT col FROM test WHERE col REGEXP '.*2'") + .fetch_all(&mut conn) + .await + .expect("Could not execute query"); + assert_eq!(result.len(), 1); + assert_eq!(result[0].get::(0), String::from("value 2")); + + let result = sqlx::query("SELECT col FROM test WHERE col REGEXP '^3'") + .fetch_all(&mut conn) + .await + .expect("Could not execute query"); + assert!(result.is_empty()); + } + + #[sqlx::test] + async fn test_regexp_coerces_non_text_values() { + let mut conn = crate::SqliteConnectOptions::from_str("sqlite://:memory:") + .unwrap() + .with_regexp() + .connect() + .await + .unwrap(); + + // INTEGER coercion + let result: Option = sqlx::query_scalar("SELECT 123 REGEXP '23'") + .fetch_one(&mut conn) + .await + .unwrap(); + assert_eq!(result, Some(1)); + + // REAL coercion + let result: Option = sqlx::query_scalar("SELECT 12.5 REGEXP '12\\.5'") + .fetch_one(&mut conn) + .await + .unwrap(); + assert_eq!(result, Some(1)); + + // INTEGER column + sqlx::query("CREATE TABLE int_test (x INTEGER NOT NULL)") + .execute(&mut conn) + .await + .unwrap(); + sqlx::query("INSERT INTO int_test VALUES (123), (45)") + .execute(&mut conn) + .await + .unwrap(); + let rows: Vec = sqlx::query_scalar("SELECT x FROM int_test WHERE x REGEXP '23'") + .fetch_all(&mut conn) + .await + .unwrap(); + assert_eq!(rows, vec![123]); + + // NULL should return NULL, not match + let result: Option = sqlx::query_scalar("SELECT NULL REGEXP '.*'") + .fetch_one(&mut conn) + .await + .unwrap(); + assert_eq!(result, None); + } + + #[sqlx::test] + async fn test_invalid_regexp_should_fail() { + let mut conn = test_db().await; + let result = sqlx::query("SELECT col from test WHERE col REGEXP '(?:?)'") + .execute(&mut conn) + .await; + assert!(matches!(result, Err(sqlx::Error::Database(_)))); + } +} diff --git a/vendor/sqlx-sqlite/src/row.rs b/vendor/sqlx-sqlite/src/row.rs new file mode 100755 index 000000000000..ec038b6d4019 --- /dev/null +++ b/vendor/sqlx-sqlite/src/row.rs @@ -0,0 +1,95 @@ +#![allow(clippy::rc_buffer)] + +use std::sync::Arc; + +use sqlx_core::column::ColumnIndex; +use sqlx_core::error::Error; +use sqlx_core::ext::ustr::UStr; +use sqlx_core::row::{debug_row, Row}; +use sqlx_core::HashMap; + +use crate::statement::StatementHandle; +use crate::{Sqlite, SqliteColumn, SqliteValue, SqliteValueRef}; + +/// Implementation of [`Row`] for SQLite. +pub struct SqliteRow { + pub(crate) values: Box<[SqliteValue]>, + pub(crate) columns: Arc>, + pub(crate) column_names: Arc>, +} + +// Accessing values from the statement object is +// safe across threads as long as we don't call [sqlite3_step] + +// we block ourselves from doing that by only exposing +// a set interface on [StatementHandle] + +unsafe impl Send for SqliteRow {} +unsafe impl Sync for SqliteRow {} + +impl SqliteRow { + pub(crate) fn current( + statement: &StatementHandle, + columns: &Arc>, + column_names: &Arc>, + ) -> Self { + let size = statement.column_count(); + let mut values = Vec::with_capacity(size); + + for i in 0..size { + values.push(unsafe { + let raw = statement.column_value(i); + + SqliteValue::dup(raw, Some(columns[i].type_info.clone())) + }); + } + + Self { + values: values.into_boxed_slice(), + columns: Arc::clone(columns), + column_names: Arc::clone(column_names), + } + } +} + +impl Row for SqliteRow { + type Database = Sqlite; + + fn columns(&self) -> &[SqliteColumn] { + &self.columns + } + + fn try_get_raw(&self, index: I) -> Result, Error> + where + I: ColumnIndex, + { + let index = index.index(self)?; + Ok(SqliteValueRef::value(&self.values[index])) + } +} + +impl ColumnIndex for &'_ str { + fn index(&self, row: &SqliteRow) -> Result { + row.column_names + .get(*self) + .ok_or_else(|| Error::ColumnNotFound((*self).into())) + .copied() + } +} + +impl std::fmt::Debug for SqliteRow { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + debug_row(self, f) + } +} + +// #[cfg(feature = "any")] +// impl From for crate::any::AnyRow { +// #[inline] +// fn from(row: SqliteRow) -> Self { +// crate::any::AnyRow { +// columns: row.columns.iter().map(|col| col.clone().into()).collect(), +// kind: crate::any::row::AnyRowKind::Sqlite(row), +// } +// } +// } diff --git a/vendor/sqlx-sqlite/src/statement/handle.rs b/vendor/sqlx-sqlite/src/statement/handle.rs new file mode 100755 index 000000000000..c78ce984144e --- /dev/null +++ b/vendor/sqlx-sqlite/src/statement/handle.rs @@ -0,0 +1,466 @@ +use std::ffi::c_void; +use std::ffi::CStr; + +use crate::error::{BoxDynError, Error}; +use crate::type_info::DataType; +use crate::{SqliteError, SqliteTypeInfo}; +use libsqlite3_sys::{ + sqlite3, sqlite3_bind_blob64, sqlite3_bind_double, sqlite3_bind_int, sqlite3_bind_int64, + sqlite3_bind_null, sqlite3_bind_parameter_count, sqlite3_bind_parameter_name, + sqlite3_bind_text64, sqlite3_changes, sqlite3_clear_bindings, sqlite3_column_blob, + sqlite3_column_bytes, sqlite3_column_count, sqlite3_column_database_name, + sqlite3_column_decltype, sqlite3_column_double, sqlite3_column_int, sqlite3_column_int64, + sqlite3_column_name, sqlite3_column_origin_name, sqlite3_column_table_name, + sqlite3_column_type, sqlite3_column_value, sqlite3_db_handle, sqlite3_finalize, sqlite3_reset, + sqlite3_sql, sqlite3_step, sqlite3_stmt, sqlite3_stmt_readonly, sqlite3_table_column_metadata, + sqlite3_value, SQLITE_DONE, SQLITE_MISUSE, SQLITE_OK, SQLITE_ROW, SQLITE_TRANSIENT, + SQLITE_UTF8, +}; +use sqlx_core::column::{ColumnOrigin, TableColumn}; +use std::os::raw::{c_char, c_int}; +use std::ptr; +use std::ptr::NonNull; +use std::slice::from_raw_parts; +use std::str::from_utf8; +use std::sync::Arc; + +#[derive(Debug)] +pub(crate) struct StatementHandle(NonNull); + +// access to SQLite3 statement handles are safe to send and share between threads +// as long as the `sqlite3_step` call is serialized. + +unsafe impl Send for StatementHandle {} + +// Most of the getters below allocate internally, and unsynchronized access is undefined. +// unsafe impl !Sync for StatementHandle {} + +macro_rules! expect_ret_valid { + ($fn_name:ident($($args:tt)*)) => {{ + let val = $fn_name($($args)*); + + TryFrom::try_from(val) + // This likely means UB in SQLite itself or our usage of it; + // signed integer overflow is UB in the C standard. + .unwrap_or_else(|_| panic!("{}() returned invalid value: {val:?}", stringify!($fn_name))) + }} +} + +macro_rules! check_col_idx { + ($idx:ident) => { + c_int::try_from($idx).unwrap_or_else(|_| panic!("invalid column index: {}", $idx)) + }; +} + +// might use some of this later +#[allow(dead_code)] +impl StatementHandle { + pub(super) fn new(ptr: NonNull) -> Self { + Self(ptr) + } + + #[inline] + pub(super) unsafe fn db_handle(&self) -> *mut sqlite3 { + // O(c) access to the connection handle for this statement handle + // https://sqlite.org/c3ref/db_handle.html + sqlite3_db_handle(self.0.as_ptr()) + } + + pub(crate) fn read_only(&self) -> bool { + // https://sqlite.org/c3ref/stmt_readonly.html + unsafe { sqlite3_stmt_readonly(self.0.as_ptr()) != 0 } + } + + pub(crate) fn sql(&self) -> &str { + // https://sqlite.org/c3ref/expanded_sql.html + unsafe { + let raw = sqlite3_sql(self.0.as_ptr()); + debug_assert!(!raw.is_null()); + + from_utf8(CStr::from_ptr(raw).to_bytes()) + .expect("sqlite3_sql() returned non-UTF-8 string") + } + } + + #[inline] + pub(crate) fn last_error(&mut self) -> SqliteError { + unsafe { SqliteError::new(self.db_handle()) } + } + + #[inline] + pub(crate) fn column_count(&self) -> usize { + // https://sqlite.org/c3ref/column_count.html + unsafe { expect_ret_valid!(sqlite3_column_count(self.0.as_ptr())) } + } + + #[inline] + pub(crate) fn changes(&self) -> u64 { + // returns the number of changes of the *last* statement; not + // necessarily this statement. + // https://sqlite.org/c3ref/changes.html + unsafe { expect_ret_valid!(sqlite3_changes(self.db_handle())) } + } + + #[inline] + pub(crate) fn column_name(&self, index: usize) -> &str { + // https://sqlite.org/c3ref/column_name.html + unsafe { + let name = sqlite3_column_name(self.0.as_ptr(), check_col_idx!(index)); + debug_assert!(!name.is_null()); + + from_utf8(CStr::from_ptr(name).to_bytes()) + .expect("sqlite3_column_name() returned non-UTF-8 column name") + } + } + + pub(crate) fn column_origin(&self, index: usize) -> ColumnOrigin { + if let Some((table, name)) = self + .column_table_name(index) + .zip(self.column_origin_name(index)) + { + let table: Arc = self + .column_db_name(index) + .filter(|&db| db != "main") + .map_or_else( + || table.into(), + // TODO: check that SQLite returns the names properly quoted if necessary + |db| format!("{db}.{table}").into(), + ); + + ColumnOrigin::Table(TableColumn { + table, + name: name.into(), + }) + } else { + ColumnOrigin::Expression + } + } + + fn column_db_name(&self, index: usize) -> Option<&str> { + unsafe { + let db_name = sqlite3_column_database_name(self.0.as_ptr(), check_col_idx!(index)); + + if !db_name.is_null() { + Some( + from_utf8(CStr::from_ptr(db_name).to_bytes()) + .expect("sqlite3_column_database_name() returned non-UTF-8 string"), + ) + } else { + None + } + } + } + + fn column_table_name(&self, index: usize) -> Option<&str> { + unsafe { + let table_name = sqlite3_column_table_name(self.0.as_ptr(), check_col_idx!(index)); + + if !table_name.is_null() { + Some( + from_utf8(CStr::from_ptr(table_name).to_bytes()) + .expect("sqlite3_column_table_name() returned non-UTF-8 string"), + ) + } else { + None + } + } + } + + fn column_origin_name(&self, index: usize) -> Option<&str> { + unsafe { + let origin_name = sqlite3_column_origin_name(self.0.as_ptr(), check_col_idx!(index)); + + if !origin_name.is_null() { + Some( + from_utf8(CStr::from_ptr(origin_name).to_bytes()) + .expect("sqlite3_column_origin_name() returned non-UTF-8 string"), + ) + } else { + None + } + } + } + + pub(crate) fn column_type_info(&self, index: usize) -> SqliteTypeInfo { + SqliteTypeInfo(DataType::from_code(self.column_type(index))) + } + + pub(crate) fn column_type_info_opt(&self, index: usize) -> Option { + match DataType::from_code(self.column_type(index)) { + DataType::Null => None, + dt => Some(SqliteTypeInfo(dt)), + } + } + + #[inline] + pub(crate) fn column_decltype(&self, index: usize) -> Option { + unsafe { + let decl = sqlite3_column_decltype(self.0.as_ptr(), check_col_idx!(index)); + if decl.is_null() { + // If the Nth column of the result set is an expression or subquery, + // then a NULL pointer is returned. + return None; + } + + let decl = from_utf8(CStr::from_ptr(decl).to_bytes()) + .expect("sqlite3_column_decltype() returned non-UTF-8 string"); + let ty: DataType = decl.parse().ok()?; + + Some(SqliteTypeInfo(ty)) + } + } + + /// Use sqlite3_column_metadata to determine if a specific column is nullable. + /// + /// Returns None in the case of INTEGER PRIMARY KEYs + /// This is because this column is an alias to rowid if the table does not use a compound + /// primary key. In this case the row is not nullable, and the output of + /// sqlite3_column_metadata may be incorrect. + pub(crate) fn column_nullable(&self, index: usize) -> Result, Error> { + unsafe { + let index = check_col_idx!(index); + // https://sqlite.org/c3ref/column_database_name.html + // + // ### Note + // The returned string is valid until the prepared statement is destroyed using + // sqlite3_finalize() or until the statement is automatically reprepared by the + // first call to sqlite3_step() for a particular run or until the same information + // is requested again in a different encoding. + let db_name = sqlite3_column_database_name(self.0.as_ptr(), index); + let table_name = sqlite3_column_table_name(self.0.as_ptr(), index); + let origin_name = sqlite3_column_origin_name(self.0.as_ptr(), index); + if db_name.is_null() || table_name.is_null() || origin_name.is_null() { + return Ok(None); + } + + let mut not_null: c_int = 0; + let mut datatype: *const c_char = ptr::null(); + let mut primary_key: c_int = 0; + + // https://sqlite.org/c3ref/table_column_metadata.html + let status = sqlite3_table_column_metadata( + self.db_handle(), + db_name, + table_name, + origin_name, + &mut datatype, + // function docs state to provide NULL for return values you don't care about + ptr::null_mut(), + &mut not_null, + &mut primary_key, + ptr::null_mut(), + ); + + if status != SQLITE_OK { + // implementation note: the docs for sqlite3_table_column_metadata() specify + // that an error can be returned if the column came from a view; however, + // experimentally we found that the above functions give us the true origin + // for columns in views that came from real tables and so we should never hit this + // error; for view columns that are expressions we are given NULL for their origins + // so we don't need special handling for that case either. + // + // this is confirmed in the `tests/sqlite-macros.rs` integration test + return Err(SqliteError::new(self.db_handle()).into()); + } + + let datatype = CStr::from_ptr(datatype); + + Ok( + if primary_key != 0 + && datatype + .to_bytes() + .eq_ignore_ascii_case("integer".as_bytes()) + { + None + } else { + Some(not_null == 0) + }, + ) + } + } + + // Number Of SQL Parameters + #[inline] + pub(crate) fn bind_parameter_count(&self) -> usize { + // https://www.sqlite.org/c3ref/bind_parameter_count.html + unsafe { expect_ret_valid!(sqlite3_bind_parameter_count(self.0.as_ptr())) } + } + + // Name Of A Host Parameter + // NOTE: The first host parameter has an index of 1, not 0. + #[inline] + pub(crate) fn bind_parameter_name(&self, index: usize) -> Option<&str> { + unsafe { + // https://www.sqlite.org/c3ref/bind_parameter_name.html + let name = sqlite3_bind_parameter_name(self.0.as_ptr(), check_col_idx!(index)); + if name.is_null() { + return None; + } + + Some( + from_utf8(CStr::from_ptr(name).to_bytes()) + .expect("sqlite3_bind_parameter_name() returned non-UTF-8 string"), + ) + } + } + + // Binding Values To Prepared Statements + // https://www.sqlite.org/c3ref/bind_blob.html + + #[inline] + pub(crate) fn bind_blob(&self, index: usize, v: &[u8]) -> c_int { + unsafe { + sqlite3_bind_blob64( + self.0.as_ptr(), + check_col_idx!(index), + v.as_ptr() as *const c_void, + v.len() as u64, + SQLITE_TRANSIENT(), + ) + } + } + + #[inline] + pub(crate) fn bind_text(&self, index: usize, v: &str) -> c_int { + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let encoding = SQLITE_UTF8 as u8; + + unsafe { + sqlite3_bind_text64( + self.0.as_ptr(), + check_col_idx!(index), + v.as_ptr() as *const c_char, + v.len() as u64, + SQLITE_TRANSIENT(), + encoding, + ) + } + } + + #[inline] + pub(crate) fn bind_int(&self, index: usize, v: i32) -> c_int { + unsafe { sqlite3_bind_int(self.0.as_ptr(), check_col_idx!(index), v as c_int) } + } + + #[inline] + pub(crate) fn bind_int64(&self, index: usize, v: i64) -> c_int { + unsafe { sqlite3_bind_int64(self.0.as_ptr(), check_col_idx!(index), v) } + } + + #[inline] + pub(crate) fn bind_double(&self, index: usize, v: f64) -> c_int { + unsafe { sqlite3_bind_double(self.0.as_ptr(), check_col_idx!(index), v) } + } + + #[inline] + pub(crate) fn bind_null(&self, index: usize) -> c_int { + unsafe { sqlite3_bind_null(self.0.as_ptr(), check_col_idx!(index)) } + } + + // result values from the query + // https://www.sqlite.org/c3ref/column_blob.html + + #[inline] + pub(crate) fn column_type(&self, index: usize) -> c_int { + unsafe { sqlite3_column_type(self.0.as_ptr(), check_col_idx!(index)) } + } + + #[inline] + pub(crate) fn column_int(&self, index: usize) -> i32 { + unsafe { sqlite3_column_int(self.0.as_ptr(), check_col_idx!(index)) as i32 } + } + + #[inline] + pub(crate) fn column_int64(&self, index: usize) -> i64 { + unsafe { sqlite3_column_int64(self.0.as_ptr(), check_col_idx!(index)) as i64 } + } + + #[inline] + pub(crate) fn column_double(&self, index: usize) -> f64 { + unsafe { sqlite3_column_double(self.0.as_ptr(), check_col_idx!(index)) } + } + + #[inline] + pub(crate) fn column_value(&self, index: usize) -> *mut sqlite3_value { + unsafe { sqlite3_column_value(self.0.as_ptr(), check_col_idx!(index)) } + } + + pub(crate) fn column_blob(&self, index: usize) -> &[u8] { + let len = unsafe { + expect_ret_valid!(sqlite3_column_bytes(self.0.as_ptr(), check_col_idx!(index))) + }; + + if len == 0 { + // empty blobs are NULL so just return an empty slice + return &[]; + } + + let ptr = + unsafe { sqlite3_column_blob(self.0.as_ptr(), check_col_idx!(index)) } as *const u8; + debug_assert!(!ptr.is_null()); + + unsafe { from_raw_parts(ptr, len) } + } + + pub(crate) fn column_text(&self, index: usize) -> Result<&str, BoxDynError> { + Ok(from_utf8(self.column_blob(index))?) + } + + pub(crate) fn clear_bindings(&self) { + unsafe { sqlite3_clear_bindings(self.0.as_ptr()) }; + } + + pub(crate) fn reset(&mut self) -> Result<(), SqliteError> { + // SAFETY: we have exclusive access to the handle + unsafe { + if sqlite3_reset(self.0.as_ptr()) != SQLITE_OK { + return Err(SqliteError::new(self.db_handle())); + } + } + + Ok(()) + } + + pub(crate) fn step(&mut self) -> Result { + // SAFETY: we have exclusive access to the handle + unsafe { + #[cfg_attr(not(feature = "unlock-notify"), expect(clippy::never_loop))] + loop { + match sqlite3_step(self.0.as_ptr()) { + SQLITE_ROW => return Ok(true), + SQLITE_DONE => return Ok(false), + SQLITE_MISUSE => panic!("misuse!"), + #[cfg(feature = "unlock-notify")] + libsqlite3_sys::SQLITE_LOCKED_SHAREDCACHE => { + // The shared cache is locked by another connection. Wait for unlock + // notification and try again. + super::unlock_notify::wait(self.db_handle())?; + // Need to reset the handle after the unlock + // (https://www.sqlite.org/unlock_notify.html) + sqlite3_reset(self.0.as_ptr()); + } + _ => return Err(SqliteError::new(self.db_handle())), + } + } + } + } +} + +impl Drop for StatementHandle { + fn drop(&mut self) { + // SAFETY: we have exclusive access to the `StatementHandle` here + unsafe { + // https://sqlite.org/c3ref/finalize.html + let status = sqlite3_finalize(self.0.as_ptr()); + if status == SQLITE_MISUSE { + // Panic in case of detected misuse of SQLite API. + // + // sqlite3_finalize returns it at least in the + // case of detected double free, i.e. calling + // sqlite3_finalize on already finalized + // statement. + panic!("Detected sqlite3_finalize misuse."); + } + } + } +} diff --git a/vendor/sqlx-sqlite/src/statement/mod.rs b/vendor/sqlx-sqlite/src/statement/mod.rs new file mode 100755 index 000000000000..93485397d3c2 --- /dev/null +++ b/vendor/sqlx-sqlite/src/statement/mod.rs @@ -0,0 +1,59 @@ +use crate::column::ColumnIndex; +use crate::error::Error; +use crate::ext::ustr::UStr; +use crate::{Sqlite, SqliteArguments, SqliteColumn, SqliteTypeInfo}; +use sqlx_core::sql_str::SqlStr; +use sqlx_core::{Either, HashMap}; +use std::sync::Arc; + +pub(crate) use sqlx_core::statement::*; + +mod handle; + +#[cfg(feature = "unlock-notify")] +pub(super) mod unlock_notify; +mod r#virtual; + +pub(crate) use handle::StatementHandle; +pub(crate) use r#virtual::VirtualStatement; + +#[derive(Debug, Clone)] +#[allow(clippy::rc_buffer)] +pub struct SqliteStatement { + pub(crate) sql: SqlStr, + pub(crate) parameters: usize, + pub(crate) columns: Arc>, + pub(crate) column_names: Arc>, +} + +impl Statement for SqliteStatement { + type Database = Sqlite; + + fn into_sql(self) -> SqlStr { + self.sql + } + + fn sql(&self) -> &SqlStr { + &self.sql + } + + fn parameters(&self) -> Option> { + Some(Either::Right(self.parameters)) + } + + fn columns(&self) -> &[SqliteColumn] { + &self.columns + } + + impl_statement_query!(SqliteArguments); +} + +impl ColumnIndex for &'_ str { + fn index(&self, statement: &SqliteStatement) -> Result { + statement + .column_names + .get(*self) + .ok_or_else(|| Error::ColumnNotFound((*self).into())) + .copied() + } +} diff --git a/vendor/sqlx-sqlite/src/statement/unlock_notify.rs b/vendor/sqlx-sqlite/src/statement/unlock_notify.rs new file mode 100755 index 000000000000..5821c23ae3c8 --- /dev/null +++ b/vendor/sqlx-sqlite/src/statement/unlock_notify.rs @@ -0,0 +1,65 @@ +use std::ffi::c_void; +use std::os::raw::c_int; +use std::slice; +use std::sync::{Condvar, Mutex}; + +use libsqlite3_sys::{sqlite3, sqlite3_unlock_notify, SQLITE_OK}; + +use crate::SqliteError; + +// Wait for unlock notification (https://www.sqlite.org/unlock_notify.html) +pub unsafe fn wait(conn: *mut sqlite3) -> Result<(), SqliteError> { + let notify = Notify::new(); + + if sqlite3_unlock_notify( + conn, + Some(unlock_notify_cb), + ¬ify as *const Notify as *mut Notify as *mut _, + ) != SQLITE_OK + { + return Err(SqliteError::new(conn)); + } + + notify.wait(); + + Ok(()) +} + +unsafe extern "C" fn unlock_notify_cb(ptr: *mut *mut c_void, len: c_int) { + let ptr = ptr as *mut &Notify; + // We don't have a choice; we can't panic and unwind into FFI here. + let slice = slice::from_raw_parts(ptr, usize::try_from(len).unwrap_or(0)); + + for notify in slice { + notify.fire(); + } +} + +struct Notify { + mutex: Mutex, + condvar: Condvar, +} + +impl Notify { + fn new() -> Self { + Self { + mutex: Mutex::new(false), + condvar: Condvar::new(), + } + } + + fn wait(&self) { + // We only want to wait until the lock is available again. + #[allow(let_underscore_lock)] + let _ = self + .condvar + .wait_while(self.mutex.lock().unwrap(), |fired| !*fired) + .unwrap(); + } + + fn fire(&self) { + let mut lock = self.mutex.lock().unwrap(); + *lock = true; + self.condvar.notify_one(); + } +} diff --git a/vendor/sqlx-sqlite/src/statement/virtual.rs b/vendor/sqlx-sqlite/src/statement/virtual.rs new file mode 100755 index 000000000000..b25aa69e47c7 --- /dev/null +++ b/vendor/sqlx-sqlite/src/statement/virtual.rs @@ -0,0 +1,204 @@ +#![allow(clippy::rc_buffer)] + +use std::cmp; +use std::os::raw::c_char; +use std::ptr::{null, null_mut, NonNull}; +use std::sync::Arc; + +use libsqlite3_sys::{ + sqlite3, sqlite3_prepare_v3, sqlite3_stmt, SQLITE_OK, SQLITE_PREPARE_PERSISTENT, +}; + +use sqlx_core::bytes::{Buf, Bytes}; +use sqlx_core::error::Error; +use sqlx_core::ext::ustr::UStr; +use sqlx_core::{HashMap, SmallVec}; + +use crate::connection::ConnectionHandle; +use crate::statement::StatementHandle; +use crate::{SqliteColumn, SqliteError}; + +// A virtual statement consists of *zero* or more raw SQLite3 statements. We chop up a SQL statement +// on `;` to support multiple statements in one query. + +#[derive(Debug)] +pub struct VirtualStatement { + persistent: bool, + + /// the current index of the actual statement that is executing + /// if `None`, no statement is executing and `prepare()` must be called; + /// if `Some(self.handles.len())` and `self.tail.is_empty()`, + /// there are no more statements to execute and `reset()` must be called + index: Option, + + /// tail of the most recently prepared SQL statement within this container + tail: Bytes, + + /// underlying sqlite handles for each inner statement + /// a SQL query string in SQLite is broken up into N statements + /// we use a [`SmallVec`] to optimize for the most likely case of a single statement + pub(crate) handles: SmallVec<[StatementHandle; 1]>, + + // each set of columns + pub(crate) columns: SmallVec<[Arc>; 1]>, + + // each set of column names + pub(crate) column_names: SmallVec<[Arc>; 1]>, +} + +pub struct PreparedStatement<'a> { + pub(crate) handle: &'a mut StatementHandle, + pub(crate) columns: &'a Arc>, + pub(crate) column_names: &'a Arc>, +} + +impl VirtualStatement { + pub(crate) fn new(mut query: &str, persistent: bool) -> Result { + query = query.trim(); + + if query.len() > i32::MAX as usize { + return Err(err_protocol!( + "query string must be smaller than {} bytes", + i32::MAX + )); + } + + Ok(Self { + persistent, + tail: Bytes::from(String::from(query)), + handles: SmallVec::with_capacity(1), + index: None, + columns: SmallVec::with_capacity(1), + column_names: SmallVec::with_capacity(1), + }) + } + + pub(crate) fn prepare_next( + &mut self, + conn: &mut ConnectionHandle, + ) -> Result>, Error> { + // increment `self.index` up to `self.handles.len()` + self.index = self + .index + .map(|idx| cmp::min(idx + 1, self.handles.len())) + .or(Some(0)); + + while self.handles.len() <= self.index.unwrap_or(0) { + if self.tail.is_empty() { + return Ok(None); + } + + if let Some(statement) = prepare(conn.as_ptr(), &mut self.tail, self.persistent)? { + let num = statement.column_count(); + + let mut columns = Vec::with_capacity(num); + let mut column_names = HashMap::with_capacity(num); + + for i in 0..num { + let name: UStr = statement.column_name(i).to_owned().into(); + let type_info = statement + .column_decltype(i) + .unwrap_or_else(|| statement.column_type_info(i)); + + columns.push(SqliteColumn { + ordinal: i, + name: name.clone(), + type_info, + origin: statement.column_origin(i), + }); + + column_names.insert(name, i); + } + + self.handles.push(statement); + self.columns.push(Arc::new(columns)); + self.column_names.push(Arc::new(column_names)); + } + } + + Ok(self.current()) + } + + pub fn current(&mut self) -> Option> { + self.index + .filter(|&idx| idx < self.handles.len()) + .map(move |idx| PreparedStatement { + handle: &mut self.handles[idx], + columns: &self.columns[idx], + column_names: &self.column_names[idx], + }) + } + + pub fn reset(&mut self) -> Result<(), Error> { + self.index = None; + + for handle in self.handles.iter_mut() { + handle.reset()?; + handle.clear_bindings(); + } + + Ok(()) + } +} + +fn prepare( + conn: *mut sqlite3, + query: &mut Bytes, + persistent: bool, +) -> Result, Error> { + let mut flags = 0; + + // For some reason, when building with the `sqlcipher` feature enabled + // `SQLITE_PREPARE_PERSISTENT` ends up being `i32` instead of `u32`. Crazy, right? + #[allow(trivial_casts, clippy::unnecessary_cast)] + if persistent { + // SQLITE_PREPARE_PERSISTENT + // The SQLITE_PREPARE_PERSISTENT flag is a hint to the query + // planner that the prepared statement will be retained for a long time + // and probably reused many times. + flags |= SQLITE_PREPARE_PERSISTENT as u32; + } + + while !query.is_empty() { + let mut statement_handle: *mut sqlite3_stmt = null_mut(); + let mut tail: *const c_char = null(); + + let query_ptr = query.as_ptr() as *const c_char; + let query_len = i32::try_from(query.len()).map_err(|_| { + err_protocol!( + "query string too large for SQLite3 API ({} bytes); \ + try breaking it into smaller chunks (< 2 GiB), executed separately", + query.len() + ) + })?; + + // + let status = unsafe { + sqlite3_prepare_v3( + conn, + query_ptr, + query_len, + flags, + &mut statement_handle, + &mut tail, + ) + }; + + if status != SQLITE_OK { + return Err(unsafe { SqliteError::new(conn).into() }); + } + + // tail should point to the first byte past the end of the first SQL + // statement in zSql. these routines only compile the first statement, + // so tail is left pointing to what remains un-compiled. + + let n = (tail as usize) - (query_ptr as usize); + query.advance(n); + + if let Some(handle) = NonNull::new(statement_handle) { + return Ok(Some(StatementHandle::new(handle))); + } + } + + Ok(None) +} diff --git a/vendor/sqlx-sqlite/src/testing/mod.rs b/vendor/sqlx-sqlite/src/testing/mod.rs new file mode 100755 index 000000000000..058a24c52b79 --- /dev/null +++ b/vendor/sqlx-sqlite/src/testing/mod.rs @@ -0,0 +1,83 @@ +use crate::error::Error; +use crate::pool::PoolOptions; +use crate::testing::{FixtureSnapshot, TestArgs, TestContext, TestSupport}; +use crate::{Sqlite, SqliteConnectOptions}; +use std::future::Future; +use std::path::{Path, PathBuf}; + +pub(crate) use sqlx_core::testing::*; + +const BASE_PATH: &str = "target/sqlx/test-dbs"; + +impl TestSupport for Sqlite { + fn test_context( + args: &TestArgs, + ) -> impl Future, Error>> + Send + '_ { + test_context(args) + } + + async fn cleanup_test(db_name: &str) -> Result<(), Error> { + crate::fs::remove_file(db_name).await?; + Ok(()) + } + + async fn cleanup_test_dbs() -> Result, Error> { + crate::fs::remove_dir_all(BASE_PATH).await?; + Ok(None) + } + + async fn snapshot(_conn: &mut Self::Connection) -> Result, Error> { + todo!() + } + + fn db_name(args: &TestArgs) -> String { + convert_path(args.test_path) + } +} + +async fn test_context(args: &TestArgs) -> Result, Error> { + let db_path = convert_path(args.test_path); + + if let Some(parent_path) = Path::parent(db_path.as_ref()) { + crate::fs::create_dir_all(parent_path) + .await + .expect("failed to create folders"); + } + + if Path::exists(db_path.as_ref()) { + crate::fs::remove_file(&db_path) + .await + .expect("failed to remove database from previous test run"); + } + + Ok(TestContext { + connect_opts: SqliteConnectOptions::new() + .filename(&db_path) + .create_if_missing(true), + // This doesn't really matter for SQLite as the databases are independent of each other. + // The main limitation is going to be the number of concurrent running tests. + pool_opts: PoolOptions::new().max_connections(1000), + db_name: db_path, + }) +} + +fn convert_path(test_path: &str) -> String { + let mut path = PathBuf::from(BASE_PATH); + + for segment in test_path.split("::") { + path.push(segment); + } + + path.set_extension("sqlite"); + + path.into_os_string() + .into_string() + .expect("path should be UTF-8") +} + +#[test] +fn test_convert_path() { + let path = convert_path("foo::bar::baz::quux"); + + assert_eq!(path, "target/sqlx/test-dbs/foo/bar/baz/quux.sqlite"); +} diff --git a/vendor/sqlx-sqlite/src/transaction.rs b/vendor/sqlx-sqlite/src/transaction.rs new file mode 100755 index 000000000000..1c57d0163f35 --- /dev/null +++ b/vendor/sqlx-sqlite/src/transaction.rs @@ -0,0 +1,35 @@ +use std::future::Future; + +use sqlx_core::transaction::TransactionManager; +use sqlx_core::{error::Error, sql_str::SqlStr}; + +use crate::{Sqlite, SqliteConnection}; + +/// Implementation of [`TransactionManager`] for SQLite. +pub struct SqliteTransactionManager; + +impl TransactionManager for SqliteTransactionManager { + type Database = Sqlite; + + async fn begin(conn: &mut SqliteConnection, statement: Option) -> Result<(), Error> { + conn.worker.begin(statement).await + } + + fn commit(conn: &mut SqliteConnection) -> impl Future> + Send + '_ { + conn.worker.commit() + } + + fn rollback( + conn: &mut SqliteConnection, + ) -> impl Future> + Send + '_ { + conn.worker.rollback() + } + + fn start_rollback(conn: &mut SqliteConnection) { + conn.worker.start_rollback().ok(); + } + + fn get_transaction_depth(conn: &SqliteConnection) -> usize { + conn.worker.shared.get_transaction_depth() + } +} diff --git a/vendor/sqlx-sqlite/src/type_checking.rs b/vendor/sqlx-sqlite/src/type_checking.rs new file mode 100755 index 000000000000..97af601c86b9 --- /dev/null +++ b/vendor/sqlx-sqlite/src/type_checking.rs @@ -0,0 +1,56 @@ +use crate::Sqlite; +#[allow(unused_imports)] +use sqlx_core as sqlx; + +// f32 is not included below as REAL represents a floating point value +// stored as an 8-byte IEEE floating point number (i.e. an f64) +// For more info see: https://www.sqlite.org/datatype3.html#storage_classes_and_datatypes +impl_type_checking!( + Sqlite { + // Note that since the macro checks `column_type_info == ::type_info()` first, + // we can list `bool` without it being automatically picked for all integer types + // due to its `TypeInfo::compatible()` impl. + bool, + // Since it returns `DataType::Int4` for `type_info()`, + // `i32` should only be chosen IFF the column decltype is `INT4` + i32, + i64, + f64, + String, + Vec, + + #[cfg(feature = "uuid")] + sqlx::types::Uuid, + }, + ParamChecking::Weak, + // While there are type integrations that must be enabled via Cargo feature, + // SQLite's type system doesn't actually have any type that we cannot decode by default. + // + // The type integrations simply allow the user to skip some intermediate representation, + // which is usually TEXT. + feature-types: _info => None, + + // The expansion of the macro automatically applies the correct feature name + // and checks `[macros.preferred-crates]` + datetime-types: { + chrono: { + sqlx::types::chrono::NaiveDate, + + sqlx::types::chrono::NaiveDateTime, + + sqlx::types::chrono::DateTime + | sqlx::types::chrono::DateTime<_>, + }, + time: { + sqlx::types::time::OffsetDateTime, + + sqlx::types::time::PrimitiveDateTime, + + sqlx::types::time::Date, + }, + }, + numeric-types: { + bigdecimal: { }, + rust_decimal: { }, + }, +); diff --git a/vendor/sqlx-sqlite/src/type_info.rs b/vendor/sqlx-sqlite/src/type_info.rs new file mode 100755 index 000000000000..38a0fc4169ec --- /dev/null +++ b/vendor/sqlx-sqlite/src/type_info.rs @@ -0,0 +1,161 @@ +use std::fmt::{self, Display, Formatter}; +use std::os::raw::c_int; +use std::str::FromStr; + +use libsqlite3_sys::{SQLITE_BLOB, SQLITE_FLOAT, SQLITE_INTEGER, SQLITE_NULL, SQLITE_TEXT}; + +use crate::error::BoxDynError; + +pub(crate) use sqlx_core::type_info::*; + +#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] +#[cfg_attr(feature = "offline", derive(serde::Serialize, serde::Deserialize))] +pub(crate) enum DataType { + // These variants should correspond to `SQLITE_*` type constants. + Null, + /// Note: SQLite's type system has no notion of integer widths. + /// The `INTEGER` type affinity can store up to 8 byte integers, + /// making `i64` the only safe choice when mapping integer types to Rust. + Integer, + Float, + Text, + Blob, + + // Explicitly not supported: see documentation in `types/mod.rs` + #[allow(dead_code)] + Numeric, + + // non-standard extensions (chosen based on the column's declared type) + /// Chosen if the column's declared type is `BOOLEAN`. + Bool, + /// Chosen if the column's declared type is `INT4`; + /// instructs the macros to use `i32` instead of `i64`. + /// Legacy feature; no idea if this is actually used anywhere. + Int4, + Date, + Time, + Datetime, +} + +/// Type information for a SQLite type. +#[derive(Debug, Clone, Eq, PartialEq, Hash)] +#[cfg_attr(feature = "offline", derive(serde::Serialize, serde::Deserialize))] +pub struct SqliteTypeInfo(pub(crate) DataType); + +impl Display for SqliteTypeInfo { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.pad(self.name()) + } +} + +impl TypeInfo for SqliteTypeInfo { + fn is_null(&self) -> bool { + matches!(self.0, DataType::Null) + } + + fn name(&self) -> &str { + match self.0 { + DataType::Null => "NULL", + DataType::Text => "TEXT", + DataType::Float => "REAL", + DataType::Blob => "BLOB", + DataType::Int4 | DataType::Integer => "INTEGER", + DataType::Numeric => "NUMERIC", + + // non-standard extensions + DataType::Bool => "BOOLEAN", + DataType::Date => "DATE", + DataType::Time => "TIME", + DataType::Datetime => "DATETIME", + } + } +} + +impl DataType { + pub(crate) fn from_code(code: c_int) -> Self { + match code { + SQLITE_INTEGER => DataType::Integer, + SQLITE_FLOAT => DataType::Float, + SQLITE_BLOB => DataType::Blob, + SQLITE_NULL => DataType::Null, + SQLITE_TEXT => DataType::Text, + + // https://sqlite.org/c3ref/c_blob.html + _ => panic!("unknown data type code {code}"), + } + } +} + +// note: this implementation is particularly important as this is how the macros determine +// what Rust type maps to what *declared* SQL type +// +impl FromStr for DataType { + type Err = BoxDynError; + + fn from_str(s: &str) -> Result { + let s = s.to_ascii_lowercase(); + Ok(match &*s { + "int4" => DataType::Int4, + "int8" => DataType::Integer, + "boolean" | "bool" => DataType::Bool, + + "date" => DataType::Date, + "time" => DataType::Time, + "datetime" | "timestamp" => DataType::Datetime, + + _ if s.contains("int") => DataType::Integer, + + _ if s.contains("char") || s.contains("clob") || s.contains("text") => DataType::Text, + + _ if s.contains("blob") => DataType::Blob, + + _ if s.contains("real") || s.contains("floa") || s.contains("doub") => DataType::Float, + + _ => { + return Err(format!("unknown type: `{s}`").into()); + } + }) + } +} + +// #[cfg(feature = "any")] +// impl From for crate::any::AnyTypeInfo { +// #[inline] +// fn from(ty: SqliteTypeInfo) -> Self { +// crate::any::AnyTypeInfo(crate::any::type_info::AnyTypeInfoKind::Sqlite(ty)) +// } +// } + +#[test] +fn test_data_type_from_str() -> Result<(), BoxDynError> { + assert_eq!(DataType::Int4, "INT4".parse()?); + + assert_eq!(DataType::Integer, "INT".parse()?); + assert_eq!(DataType::Integer, "INTEGER".parse()?); + assert_eq!(DataType::Integer, "INTBIG".parse()?); + assert_eq!(DataType::Integer, "MEDIUMINT".parse()?); + + assert_eq!(DataType::Integer, "BIGINT".parse()?); + assert_eq!(DataType::Integer, "UNSIGNED BIG INT".parse()?); + assert_eq!(DataType::Integer, "INT8".parse()?); + + assert_eq!(DataType::Text, "CHARACTER(20)".parse()?); + assert_eq!(DataType::Text, "NCHAR(55)".parse()?); + assert_eq!(DataType::Text, "TEXT".parse()?); + assert_eq!(DataType::Text, "CLOB".parse()?); + + assert_eq!(DataType::Blob, "BLOB".parse()?); + + assert_eq!(DataType::Float, "REAL".parse()?); + assert_eq!(DataType::Float, "FLOAT".parse()?); + assert_eq!(DataType::Float, "DOUBLE PRECISION".parse()?); + + assert_eq!(DataType::Bool, "BOOLEAN".parse()?); + assert_eq!(DataType::Bool, "BOOL".parse()?); + + assert_eq!(DataType::Datetime, "DATETIME".parse()?); + assert_eq!(DataType::Time, "TIME".parse()?); + assert_eq!(DataType::Date, "DATE".parse()?); + + Ok(()) +} diff --git a/vendor/sqlx-sqlite/src/types/bool.rs b/vendor/sqlx-sqlite/src/types/bool.rs new file mode 100755 index 000000000000..9228eef23617 --- /dev/null +++ b/vendor/sqlx-sqlite/src/types/bool.rs @@ -0,0 +1,31 @@ +use crate::arguments::SqliteArgumentsBuffer; +use crate::decode::Decode; +use crate::encode::{Encode, IsNull}; +use crate::error::BoxDynError; +use crate::type_info::DataType; +use crate::types::Type; +use crate::{Sqlite, SqliteArgumentValue, SqliteTypeInfo, SqliteValueRef}; + +impl Type for bool { + fn type_info() -> SqliteTypeInfo { + SqliteTypeInfo(DataType::Bool) + } + + fn compatible(ty: &SqliteTypeInfo) -> bool { + matches!(ty.0, DataType::Bool | DataType::Int4 | DataType::Integer) + } +} + +impl Encode<'_, Sqlite> for bool { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Int((*self).into())); + + Ok(IsNull::No) + } +} + +impl<'r> Decode<'r, Sqlite> for bool { + fn decode(value: SqliteValueRef<'r>) -> Result { + Ok(value.int64()? != 0) + } +} diff --git a/vendor/sqlx-sqlite/src/types/bytes.rs b/vendor/sqlx-sqlite/src/types/bytes.rs new file mode 100755 index 000000000000..6453007bc9fb --- /dev/null +++ b/vendor/sqlx-sqlite/src/types/bytes.rs @@ -0,0 +1,105 @@ +use std::borrow::Cow; +use std::rc::Rc; +use std::sync::Arc; + +use crate::arguments::SqliteArgumentsBuffer; +use crate::decode::Decode; +use crate::encode::{Encode, IsNull}; +use crate::error::BoxDynError; +use crate::type_info::DataType; +use crate::types::Type; +use crate::{Sqlite, SqliteArgumentValue, SqliteTypeInfo, SqliteValueRef}; + +impl Type for [u8] { + fn type_info() -> SqliteTypeInfo { + SqliteTypeInfo(DataType::Blob) + } + + fn compatible(ty: &SqliteTypeInfo) -> bool { + matches!(ty.0, DataType::Blob | DataType::Text) + } +} + +impl Encode<'_, Sqlite> for &'_ [u8] { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Blob(Arc::new(self.to_vec()))); + + Ok(IsNull::No) + } +} + +impl<'r> Decode<'r, Sqlite> for &'r [u8] { + fn decode(value: SqliteValueRef<'r>) -> Result { + Ok(value.blob_borrowed()) + } +} + +impl Encode<'_, Sqlite> for Box<[u8]> { + fn encode(self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Blob(Arc::new(self.into_vec()))); + + Ok(IsNull::No) + } + + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Blob(Arc::new(self.clone().into_vec()))); + + Ok(IsNull::No) + } +} + +impl Type for Vec { + fn type_info() -> SqliteTypeInfo { + <&[u8] as Type>::type_info() + } + + fn compatible(ty: &SqliteTypeInfo) -> bool { + <&[u8] as Type>::compatible(ty) + } +} + +impl Encode<'_, Sqlite> for Vec { + fn encode(self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Blob(Arc::new(self))); + + Ok(IsNull::No) + } + + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Blob(Arc::new(self.clone()))); + + Ok(IsNull::No) + } +} + +impl<'r> Decode<'r, Sqlite> for Vec { + fn decode(value: SqliteValueRef<'r>) -> Result { + Ok(value.blob_owned()) + } +} + +impl Encode<'_, Sqlite> for Cow<'_, [u8]> { + fn encode(self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Blob(Arc::new(self.into()))); + + Ok(IsNull::No) + } + + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Blob(Arc::new(self.to_vec()))); + + Ok(IsNull::No) + } +} + +impl Encode<'_, Sqlite> for Arc<[u8]> { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + as Encode<'_, Sqlite>>::encode(self.to_vec(), args) + } +} + +impl Encode<'_, Sqlite> for Rc<[u8]> { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + as Encode<'_, Sqlite>>::encode(self.to_vec(), args) + } +} diff --git a/vendor/sqlx-sqlite/src/types/chrono.rs b/vendor/sqlx-sqlite/src/types/chrono.rs new file mode 100755 index 000000000000..8d987538d014 --- /dev/null +++ b/vendor/sqlx-sqlite/src/types/chrono.rs @@ -0,0 +1,220 @@ +use std::fmt::Display; + +use crate::value::ValueRef; +use crate::{ + decode::Decode, + encode::{Encode, IsNull}, + error::BoxDynError, + type_info::DataType, + types::Type, + Sqlite, SqliteArgumentsBuffer, SqliteTypeInfo, SqliteValueRef, +}; +use chrono::FixedOffset; +use chrono::{ + DateTime, Local, NaiveDate, NaiveDateTime, NaiveTime, Offset, SecondsFormat, TimeZone, Utc, +}; + +impl Type for DateTime { + fn type_info() -> SqliteTypeInfo { + SqliteTypeInfo(DataType::Datetime) + } + + fn compatible(ty: &SqliteTypeInfo) -> bool { + >::compatible(ty) + } +} + +impl Type for NaiveDateTime { + fn type_info() -> SqliteTypeInfo { + SqliteTypeInfo(DataType::Datetime) + } + + fn compatible(ty: &SqliteTypeInfo) -> bool { + matches!( + ty.0, + DataType::Datetime + | DataType::Text + | DataType::Integer + | DataType::Int4 + | DataType::Float + ) + } +} + +impl Type for NaiveDate { + fn type_info() -> SqliteTypeInfo { + SqliteTypeInfo(DataType::Date) + } + + fn compatible(ty: &SqliteTypeInfo) -> bool { + matches!(ty.0, DataType::Date | DataType::Text) + } +} + +impl Type for NaiveTime { + fn type_info() -> SqliteTypeInfo { + SqliteTypeInfo(DataType::Time) + } + + fn compatible(ty: &SqliteTypeInfo) -> bool { + matches!(ty.0, DataType::Time | DataType::Text) + } +} + +impl Encode<'_, Sqlite> for DateTime +where + Tz::Offset: Display, +{ + fn encode_by_ref(&self, buf: &mut SqliteArgumentsBuffer) -> Result { + Encode::::encode(self.to_rfc3339_opts(SecondsFormat::AutoSi, false), buf) + } +} + +impl Encode<'_, Sqlite> for NaiveDateTime { + fn encode_by_ref(&self, buf: &mut SqliteArgumentsBuffer) -> Result { + Encode::::encode(self.format("%F %T%.f").to_string(), buf) + } +} + +impl Encode<'_, Sqlite> for NaiveDate { + fn encode_by_ref(&self, buf: &mut SqliteArgumentsBuffer) -> Result { + Encode::::encode(self.format("%F").to_string(), buf) + } +} + +impl Encode<'_, Sqlite> for NaiveTime { + fn encode_by_ref(&self, buf: &mut SqliteArgumentsBuffer) -> Result { + Encode::::encode(self.format("%T%.f").to_string(), buf) + } +} + +impl<'r> Decode<'r, Sqlite> for DateTime { + fn decode(value: SqliteValueRef<'r>) -> Result { + Ok(Utc.from_utc_datetime(&decode_datetime(value)?.naive_utc())) + } +} + +impl<'r> Decode<'r, Sqlite> for DateTime { + fn decode(value: SqliteValueRef<'r>) -> Result { + Ok(Local.from_utc_datetime(&decode_datetime(value)?.naive_utc())) + } +} + +impl<'r> Decode<'r, Sqlite> for DateTime { + fn decode(value: SqliteValueRef<'r>) -> Result { + decode_datetime(value) + } +} + +fn decode_datetime(value: SqliteValueRef<'_>) -> Result, BoxDynError> { + let dt = match value.type_info().0 { + DataType::Text => decode_datetime_from_text(value.text_borrowed()?), + DataType::Int4 | DataType::Integer => decode_datetime_from_int(value.int64()?), + DataType::Float => decode_datetime_from_float(value.double()?), + + _ => None, + }; + + if let Some(dt) = dt { + Ok(dt) + } else { + Err(format!("invalid datetime: {}", value.text_borrowed()?).into()) + } +} + +fn decode_datetime_from_text(value: &str) -> Option> { + if let Ok(dt) = DateTime::parse_from_rfc3339(value) { + return Some(dt); + } + + // Loop over common date time patterns, inspired by Diesel + // https://github.com/diesel-rs/diesel/blob/93ab183bcb06c69c0aee4a7557b6798fd52dd0d8/diesel/src/sqlite/types/date_and_time/chrono.rs#L56-L97 + let sqlite_datetime_formats = &[ + // Most likely format + "%F %T%.f", + // Other formats in order of appearance in docs + "%F %R", + "%F %RZ", + "%F %R%:z", + "%F %T%.fZ", + "%F %T%.f%:z", + "%FT%R", + "%FT%RZ", + "%FT%R%:z", + "%FT%T%.f", + "%FT%T%.fZ", + "%FT%T%.f%:z", + ]; + + for format in sqlite_datetime_formats { + if let Ok(dt) = DateTime::parse_from_str(value, format) { + return Some(dt); + } + + if let Ok(dt) = NaiveDateTime::parse_from_str(value, format) { + return Some(Utc.fix().from_utc_datetime(&dt)); + } + } + + None +} + +fn decode_datetime_from_int(value: i64) -> Option> { + Utc.fix().timestamp_opt(value, 0).single() +} + +fn decode_datetime_from_float(value: f64) -> Option> { + let epoch_in_julian_days = 2_440_587.5; + let seconds_in_day = 86400.0; + let timestamp = (value - epoch_in_julian_days) * seconds_in_day; + + if !timestamp.is_finite() { + return None; + } + + // We don't really have a choice but to do lossy casts for this conversion + // We checked above if the value is infinite or NaN which could otherwise cause problems + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + { + let seconds = timestamp.trunc() as i64; + let nanos = (timestamp.fract() * 1E9).abs() as u32; + + Utc.fix().timestamp_opt(seconds, nanos).single() + } +} + +impl<'r> Decode<'r, Sqlite> for NaiveDateTime { + fn decode(value: SqliteValueRef<'r>) -> Result { + Ok(decode_datetime(value)?.naive_local()) + } +} + +impl<'r> Decode<'r, Sqlite> for NaiveDate { + fn decode(value: SqliteValueRef<'r>) -> Result { + Ok(NaiveDate::parse_from_str(value.text_borrowed()?, "%F")?) + } +} + +impl<'r> Decode<'r, Sqlite> for NaiveTime { + fn decode(value: SqliteValueRef<'r>) -> Result { + let value = value.text_borrowed()?; + + // Loop over common time patterns, inspired by Diesel + // https://github.com/diesel-rs/diesel/blob/93ab183bcb06c69c0aee4a7557b6798fd52dd0d8/diesel/src/sqlite/types/date_and_time/chrono.rs#L29-L47 + #[rustfmt::skip] // don't like how rustfmt mangles the comments + let sqlite_time_formats = &[ + // Most likely format + "%T.f", "%T%.f", + // Other formats in order of appearance in docs + "%R", "%RZ", "%T%.fZ", "%R%:z", "%T%.f%:z", + ]; + + for format in sqlite_time_formats { + if let Ok(dt) = NaiveTime::parse_from_str(value, format) { + return Ok(dt); + } + } + + Err(format!("invalid time: {value}").into()) + } +} diff --git a/vendor/sqlx-sqlite/src/types/float.rs b/vendor/sqlx-sqlite/src/types/float.rs new file mode 100755 index 000000000000..d23b3f3a0886 --- /dev/null +++ b/vendor/sqlx-sqlite/src/types/float.rs @@ -0,0 +1,49 @@ +use crate::arguments::SqliteArgumentsBuffer; +use crate::decode::Decode; +use crate::encode::{Encode, IsNull}; +use crate::error::BoxDynError; +use crate::type_info::DataType; +use crate::types::Type; +use crate::{Sqlite, SqliteArgumentValue, SqliteTypeInfo, SqliteValueRef}; + +impl Type for f32 { + fn type_info() -> SqliteTypeInfo { + SqliteTypeInfo(DataType::Float) + } +} + +impl Encode<'_, Sqlite> for f32 { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Double((*self).into())); + + Ok(IsNull::No) + } +} + +impl<'r> Decode<'r, Sqlite> for f32 { + fn decode(value: SqliteValueRef<'r>) -> Result { + // Truncation is intentional + #[allow(clippy::cast_possible_truncation)] + Ok(value.double()? as f32) + } +} + +impl Type for f64 { + fn type_info() -> SqliteTypeInfo { + SqliteTypeInfo(DataType::Float) + } +} + +impl Encode<'_, Sqlite> for f64 { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Double(*self)); + + Ok(IsNull::No) + } +} + +impl<'r> Decode<'r, Sqlite> for f64 { + fn decode(value: SqliteValueRef<'r>) -> Result { + Ok(value.double()?) + } +} diff --git a/vendor/sqlx-sqlite/src/types/int.rs b/vendor/sqlx-sqlite/src/types/int.rs new file mode 100755 index 000000000000..2cf4209ad697 --- /dev/null +++ b/vendor/sqlx-sqlite/src/types/int.rs @@ -0,0 +1,107 @@ +use crate::arguments::SqliteArgumentsBuffer; +use crate::decode::Decode; +use crate::encode::{Encode, IsNull}; +use crate::error::BoxDynError; +use crate::type_info::DataType; +use crate::types::Type; +use crate::{Sqlite, SqliteArgumentValue, SqliteTypeInfo, SqliteValueRef}; + +impl Type for i8 { + fn type_info() -> SqliteTypeInfo { + SqliteTypeInfo(DataType::Int4) + } + + fn compatible(ty: &SqliteTypeInfo) -> bool { + matches!(ty.0, DataType::Int4 | DataType::Integer) + } +} + +impl Encode<'_, Sqlite> for i8 { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Int(*self as i32)); + + Ok(IsNull::No) + } +} + +impl<'r> Decode<'r, Sqlite> for i8 { + fn decode(value: SqliteValueRef<'r>) -> Result { + // NOTE: using `sqlite3_value_int64()` here because `sqlite3_value_int()` silently truncates + // which leads to bugs, e.g.: + // https://github.com/launchbadge/sqlx/issues/3179 + // Similar bug in Postgres: https://github.com/launchbadge/sqlx/issues/3161 + Ok(value.int64()?.try_into()?) + } +} + +impl Type for i16 { + fn type_info() -> SqliteTypeInfo { + SqliteTypeInfo(DataType::Int4) + } + + fn compatible(ty: &SqliteTypeInfo) -> bool { + matches!(ty.0, DataType::Int4 | DataType::Integer) + } +} + +impl Encode<'_, Sqlite> for i16 { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Int(*self as i32)); + + Ok(IsNull::No) + } +} + +impl<'r> Decode<'r, Sqlite> for i16 { + fn decode(value: SqliteValueRef<'r>) -> Result { + Ok(value.int64()?.try_into()?) + } +} + +impl Type for i32 { + fn type_info() -> SqliteTypeInfo { + SqliteTypeInfo(DataType::Int4) + } + + fn compatible(ty: &SqliteTypeInfo) -> bool { + matches!(ty.0, DataType::Int4 | DataType::Integer) + } +} + +impl Encode<'_, Sqlite> for i32 { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Int(*self)); + + Ok(IsNull::No) + } +} + +impl<'r> Decode<'r, Sqlite> for i32 { + fn decode(value: SqliteValueRef<'r>) -> Result { + Ok(value.int64()?.try_into()?) + } +} + +impl Type for i64 { + fn type_info() -> SqliteTypeInfo { + SqliteTypeInfo(DataType::Integer) + } + + fn compatible(ty: &SqliteTypeInfo) -> bool { + matches!(ty.0, DataType::Int4 | DataType::Integer) + } +} + +impl Encode<'_, Sqlite> for i64 { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Int64(*self)); + + Ok(IsNull::No) + } +} + +impl<'r> Decode<'r, Sqlite> for i64 { + fn decode(value: SqliteValueRef<'r>) -> Result { + Ok(value.int64()?) + } +} diff --git a/vendor/sqlx-sqlite/src/types/json.rs b/vendor/sqlx-sqlite/src/types/json.rs new file mode 100755 index 000000000000..dafd4836587c --- /dev/null +++ b/vendor/sqlx-sqlite/src/types/json.rs @@ -0,0 +1,37 @@ +use serde::{Deserialize, Serialize}; + +use crate::arguments::SqliteArgumentsBuffer; +use crate::decode::Decode; +use crate::encode::{Encode, IsNull}; +use crate::error::BoxDynError; +use crate::types::{Json, Type}; +use crate::{type_info::DataType, Sqlite, SqliteTypeInfo, SqliteValueRef}; + +impl Type for Json { + fn type_info() -> SqliteTypeInfo { + SqliteTypeInfo(DataType::Text) + } + + fn compatible(ty: &SqliteTypeInfo) -> bool { + <&str as Type>::compatible(ty) + } +} + +impl Encode<'_, Sqlite> for Json +where + T: Serialize, +{ + fn encode_by_ref(&self, buf: &mut SqliteArgumentsBuffer) -> Result { + Encode::::encode(self.encode_to_string()?, buf) + } +} + +impl<'r, T> Decode<'r, Sqlite> for Json +where + T: 'r + Deserialize<'r>, +{ + fn decode(value: SqliteValueRef<'r>) -> Result { + // Saves a pass over the data by making `serde_json` check UTF-8. + Self::decode_from_bytes(Decode::::decode(value)?) + } +} diff --git a/vendor/sqlx-sqlite/src/types/mod.rs b/vendor/sqlx-sqlite/src/types/mod.rs new file mode 100755 index 000000000000..d36af7ea1493 --- /dev/null +++ b/vendor/sqlx-sqlite/src/types/mod.rs @@ -0,0 +1,240 @@ +//! Conversions between Rust and **SQLite** types. +//! +//! # Types +//! +//! | Rust type | SQLite type(s) | +//! |---------------------------------------|------------------------------------------------------| +//! | `bool` | BOOLEAN | +//! | `i8` | INTEGER | +//! | `i16` | INTEGER | +//! | `i32` | INTEGER, INT4 | +//! | `i64` | BIGINT, INT8 | +//! | `u8` | INTEGER | +//! | `u16` | INTEGER | +//! | `u32` | INTEGER | +//! | `u64` | INTEGER (Decode only; see note) | +//! | `f32` | REAL | +//! | `f64` | REAL | +//! | `&str`, [`String`] | TEXT | +//! | `&[u8]`, `Vec` | BLOB | +//! +//! #### Note: Unsigned Integers +//! Decoding of unsigned integer types simply performs a checked conversion +//! to ensure that overflow does not occur. +//! +//! Encoding of the unsigned integer types `u8`, `u16` and `u32` is implemented by zero-extending to +//! the next-larger signed type. So `u8` becomes `i16`, `u16` becomes `i32`, and `u32` becomes `i64` +//! while still retaining their semantic values. +//! +//! SQLite stores integers in a variable-width encoding and always handles them in memory as 64-bit +//! signed values, so no space is wasted by this implicit widening. +//! +//! However, there is no corresponding larger type for `u64` in SQLite +//! (it would require a native 16-byte integer, i.e. the equivalent of `i128`), +//! and so encoding is not supported for this type. +//! +//! Bit-casting `u64` to `i64`, or storing it as `REAL`, `BLOB` or `TEXT`, +//! would change the semantics of the value in SQL and so violates the principle of least surprise. +//! +//! ### [`chrono`](https://crates.io/crates/chrono) +//! +//! Requires the `chrono` Cargo feature flag. +//! +//! | Rust type | Sqlite type(s) | +//! |---------------------------------------|------------------------------------------------------| +//! | `chrono::NaiveDateTime` | DATETIME (TEXT, INTEGER, REAL) | +//! | `chrono::DateTime` | DATETIME (TEXT, INTEGER, REAL) | +//! | `chrono::DateTime` | DATETIME (TEXT, INTEGER, REAL) | +//! | `chrono::DateTime` | DATETIME (TEXT, INTEGER, REAL) | +//! | `chrono::NaiveDate` | DATE (TEXT only) | +//! | `chrono::NaiveTime` | TIME (TEXT only) | +//! +//! ##### NOTE: `DATETIME` conversions +//! SQLite may represent `DATETIME` values as one of three types: `TEXT`, `REAL`, or `INTEGER`. +//! Which one is used is entirely up to you and how you store timestamps in your database. +//! +//! The deserialization for `NaiveDateTime`, `DateTime` and `DateTime` infer the date +//! format from the type of the value they're being decoded from: +//! +//! * If `TEXT`, the format is assumed to be an ISO-8601 compatible datetime string. +//! A number of possible formats are tried; see `sqlx-sqlite/src/types/chrono.rs` for the current +//! set of formats. +//! * If `INTEGER`, it is expected to be the number of seconds since January 1, 1970 00:00 UTC, +//! as if returned from the `unixepoch()` function (without the `subsec` modifier). +//! * If `REAL`, it is expected to be the (possibly fractional) number of days since the Julian epoch, +//! November 24, 4714 BCE 12:00 UTC, as if returned from the `julianday()` function. +//! +//! These types will always encode to a datetime string, either +//! with a timezone offset (`DateTime` for any `Tz: TimeZone`) or without (`NaiveDateTime`). +//! +//! ##### NOTE: `CURRENT_TIMESTAMP` and comparison/interoperability of `DATETIME` values +//! As stated previously, `DateTime` always encodes to a date-time string +//! _with_ a timezone offset, +//! in [RFC 3339 format][::chrono::DateTime::to_rfc3339_opts] (with `use_z: false`). +//! +//! However, most of SQLite's datetime functions +//! (including `datetime()` and `DEFAULT CURRENT_TIMESTAMP`) +//! do not use this format. They instead use `YYYY-MM-DD HH:MM:SS.SSSS` without a timezone offset. +//! +//! This may cause problems with interoperability with other applications, and especially +//! when comparing datetime values, which compares the actual string values lexicographically. +//! +//! Date-time strings in the SQLite format will generally _not_ compare consistently +//! with date-time strings in the RFC 3339 format. +//! +//! We recommend that you decide up-front whether `DATETIME` values should be stored +//! with explicit time zones or not, and use the corresponding type +//! (and its corresponding offset, if applicable) _consistently_ throughout your +//! application: +//! +//! * RFC 3339 format: `DateTime` (e.g. `DateTime`, `DateTime`, `DateTime`) +//! * Changing or mixing and matching offsets may break comparisons with existing timestamps. +//! * `DateTime` is **not recommended** for portable applications. +//! * `DateTime` is only recommended if the offset is **constant**. +//! * SQLite format: `NaiveDateTime` +//! +//! Note that non-constant offsets may still cause issues when comparing timestamps, +//! as the comparison operators are not timezone-aware. +//! +//! ### [`time`](https://crates.io/crates/time) +//! +//! Requires the `time` Cargo feature flag. +//! +//! | Rust type | Sqlite type(s) | +//! |---------------------------------------|------------------------------------------------------| +//! | `time::PrimitiveDateTime` | DATETIME (TEXT, INTEGER) | +//! | `time::OffsetDateTime` | DATETIME (TEXT, INTEGER) | +//! | `time::Date` | DATE (TEXT only) | +//! | `time::Time` | TIME (TEXT only) | +//! +//! ##### NOTE: `DATETIME` conversions +//! The behavior here is identical to the corresponding `chrono` types, minus the support for `REAL` +//! values as Julian days (it's just not implemented). +//! +//! `PrimitiveDateTime` and `OffsetDateTime` will always encode to a datetime string, either +//! with a timezone offset (`OffsetDateTime`) or without (`PrimitiveDateTime`). +//! +//! ##### NOTE: `CURRENT_TIMESTAMP` and comparison/interoperability of `DATETIME` values +//! As stated previously, `OffsetDateTime` always encodes to a datetime string _with_ a timezone offset, +//! in [RFC 3339 format][::time::format_description::well_known::Rfc3339] (using `Z` for UTC offsets). +//! +//! However, most of SQLite's datetime functions +//! (including `datetime()` and `DEFAULT CURRENT_TIMESTAMP`) +//! do not use this format. They instead use `YYYY-MM-DD HH:MM:SS.SSSS` without a timezone offset. +//! +//! This may cause problems with interoperability with other applications, and especially +//! when comparing datetime values, which compares the actual string values lexicographically. +//! +//! Date-time strings in the SQLite format will generally _not_ compare consistently +//! with date-time strings in the RFC 3339 format. +//! +//! We recommend that you decide up-front whether `DATETIME` values should be stored +//! with explicit time zones or not, and use the corresponding type +//! (and its corresponding offset, if applicable) _consistently_ throughout your +//! application: +//! +//! * RFC 3339 format: `OffsetDateTime` with a **constant** offset. +//! * Changing or mixing and matching offsets may break comparisons with existing timestamps. +//! * `OffsetDateTime::now_local()` is **not recommended** for portable applications. +//! * Non-UTC offsets are only recommended if the offset is **constant**. +//! * SQLite format: `PrimitiveDateTime` +//! +//! Note that non-constant offsets may still cause issues when comparing timestamps, +//! as the comparison operators are not timezone-aware. +//! +//! ### [`uuid`](https://crates.io/crates/uuid) +//! +//! Requires the `uuid` Cargo feature flag. +//! +//! | Rust type | Sqlite type(s) | +//! |---------------------------------------|------------------------------------------------------| +//! | `uuid::Uuid` | BLOB, TEXT | +//! | `uuid::fmt::Hyphenated` | TEXT | +//! | `uuid::fmt::Simple` | TEXT | +//! +//! ### [`json`](https://crates.io/crates/serde_json) +//! +//! Requires the `json` Cargo feature flag. +//! +//! | Rust type | Sqlite type(s) | +//! |---------------------------------------|------------------------------------------------------| +//! | [`Json`] | TEXT | +//! | `serde_json::JsonValue` | TEXT | +//! | `&serde_json::value::RawValue` | TEXT | +//! +//! # Nullable +//! +//! In addition, `Option` is supported where `T` implements `Type`. An `Option` represents +//! a potentially `NULL` value from SQLite. +//! +//! # Non-feature: `NUMERIC` / `rust_decimal` / `bigdecimal` Support +//! Support for mapping `rust_decimal::Decimal` and `bigdecimal::BigDecimal` to SQLite has been +//! deliberately omitted because SQLite does not have native support for high- +//! or arbitrary-precision decimal arithmetic, and to pretend so otherwise would be a +//! significant misstep in API design. +//! +//! The in-tree [`decimal.c`] extension is unfortunately not included in the [amalgamation], +//! which is used to build the bundled version of SQLite3 for `libsqlite3-sys` (which we have +//! enabled by default for the simpler setup experience), otherwise we could support that. +//! +//! The `NUMERIC` type affinity, while seemingly designed for storing decimal values, +//! stores non-integer real numbers as double-precision IEEE-754 floating point, +//! i.e. `REAL` in SQLite, `f64` in Rust, `double` in C/C++, etc. +//! +//! [Datatypes in SQLite: Type Affinity][type-affinity] (accessed 2023/11/20): +//! +//! > A column with NUMERIC affinity may contain values using all five storage classes. +//! > When text data is inserted into a NUMERIC column, the storage class of the text is converted to +//! > INTEGER or REAL (in order of preference) if the text is a well-formed integer or real literal, +//! > respectively. If the TEXT value is a well-formed integer literal that is too large to fit in a +//! > 64-bit signed integer, it is converted to REAL. For conversions between TEXT and REAL storage +//! > classes, only the first 15 significant decimal digits of the number are preserved. +//! +//! With the SQLite3 interactive CLI, we can see that a higher-precision value +//! (20 digits in this case) is rounded off: +//! +//! ```text +//! sqlite> CREATE TABLE foo(bar NUMERIC); +//! sqlite> INSERT INTO foo(bar) VALUES('1.2345678901234567890'); +//! sqlite> SELECT * FROM foo; +//! 1.23456789012346 +//! ``` +//! +//! It appears the `TEXT` storage class is only used if the value contains invalid characters +//! or extra whitespace. +//! +//! Thus, the `NUMERIC` type affinity is **unsuitable** for storage of high-precision decimal values +//! and should be **avoided at all costs**. +//! +//! Support for `rust_decimal` and `bigdecimal` would only be a trap because users will naturally +//! want to use the `NUMERIC` type affinity, and might otherwise encounter serious bugs caused by +//! rounding errors that they were deliberately avoiding when they chose an arbitrary-precision type +//! over a floating-point type in the first place. +//! +//! Instead, you should only use a type affinity that SQLite will not attempt to convert implicitly, +//! such as `TEXT` or `BLOB`, and map values to/from SQLite as strings. You can do this easily +//! using [the `Text` adapter]. +//! +//! +//! [`decimal.c`]: https://www.sqlite.org/floatingpoint.html#the_decimal_c_extension +//! [amalgamation]: https://www.sqlite.org/amalgamation.html +//! [type-affinity]: https://www.sqlite.org/datatype3.html#type_affinity +//! [the `Text` adapter]: Text + +pub(crate) use sqlx_core::types::*; + +mod bool; +mod bytes; +#[cfg(feature = "chrono")] +mod chrono; +mod float; +mod int; +#[cfg(feature = "json")] +mod json; +mod str; +mod text; +#[cfg(feature = "time")] +mod time; +mod uint; +#[cfg(feature = "uuid")] +mod uuid; diff --git a/vendor/sqlx-sqlite/src/types/str.rs b/vendor/sqlx-sqlite/src/types/str.rs new file mode 100755 index 000000000000..a28f778b63b9 --- /dev/null +++ b/vendor/sqlx-sqlite/src/types/str.rs @@ -0,0 +1,106 @@ +use crate::arguments::SqliteArgumentsBuffer; +use crate::decode::Decode; +use crate::encode::{Encode, IsNull}; +use crate::error::BoxDynError; +use crate::type_info::DataType; +use crate::types::Type; +use crate::{Sqlite, SqliteArgumentValue, SqliteTypeInfo, SqliteValueRef}; +use sqlx_core::database::Database; +use std::borrow::Cow; +use std::rc::Rc; +use std::sync::Arc; + +impl Type for str { + fn type_info() -> SqliteTypeInfo { + SqliteTypeInfo(DataType::Text) + } +} + +impl Encode<'_, Sqlite> for &'_ str { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Text(Arc::new(self.to_string()))); + + Ok(IsNull::No) + } +} + +impl<'r> Decode<'r, Sqlite> for &'r str { + fn decode(value: SqliteValueRef<'r>) -> Result { + Ok(value.text_borrowed()?) + } +} + +impl Encode<'_, Sqlite> for Box { + fn encode(self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::TextSlice(Arc::from(self))); + + Ok(IsNull::No) + } + + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Text(Arc::new(self.to_string()))); + + Ok(IsNull::No) + } +} + +impl Type for String { + fn type_info() -> SqliteTypeInfo { + <&str as Type>::type_info() + } +} + +impl Encode<'_, Sqlite> for String { + fn encode(self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Text(Arc::new(self))); + + Ok(IsNull::No) + } + + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Text(Arc::new(self.clone()))); + + Ok(IsNull::No) + } +} + +impl<'r> Decode<'r, Sqlite> for String { + fn decode(value: SqliteValueRef<'r>) -> Result { + Ok(value.text_owned()?) + } +} + +impl Encode<'_, Sqlite> for Cow<'_, str> { + fn encode(self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Text(Arc::new(self.into()))); + + Ok(IsNull::No) + } + + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Text(Arc::new(self.to_string()))); + + Ok(IsNull::No) + } +} + +impl Encode<'_, Sqlite> for Arc { + fn encode(self, args: &mut ::ArgumentBuffer) -> Result + where + Self: Sized, + { + args.push(SqliteArgumentValue::TextSlice(self)); + + Ok(IsNull::No) + } + + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + >::encode(self.to_string(), args) + } +} + +impl Encode<'_, Sqlite> for Rc { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + >::encode(self.to_string(), args) + } +} diff --git a/vendor/sqlx-sqlite/src/types/text.rs b/vendor/sqlx-sqlite/src/types/text.rs new file mode 100755 index 000000000000..ef03caf5a028 --- /dev/null +++ b/vendor/sqlx-sqlite/src/types/text.rs @@ -0,0 +1,37 @@ +use crate::arguments::SqliteArgumentsBuffer; +use crate::{Sqlite, SqliteTypeInfo, SqliteValueRef}; +use sqlx_core::decode::Decode; +use sqlx_core::encode::{Encode, IsNull}; +use sqlx_core::error::BoxDynError; +use sqlx_core::types::{Text, Type}; +use std::fmt::Display; +use std::str::FromStr; + +impl Type for Text { + fn type_info() -> SqliteTypeInfo { + >::type_info() + } + + fn compatible(ty: &SqliteTypeInfo) -> bool { + >::compatible(ty) + } +} + +impl Encode<'_, Sqlite> for Text +where + T: Display, +{ + fn encode_by_ref(&self, buf: &mut SqliteArgumentsBuffer) -> Result { + Encode::::encode(self.0.to_string(), buf) + } +} + +impl<'r, T> Decode<'r, Sqlite> for Text +where + T: FromStr, + BoxDynError: From<::Err>, +{ + fn decode(value: SqliteValueRef<'r>) -> Result { + Ok(Self(value.with_temp_text(|text| text.parse::())??)) + } +} diff --git a/vendor/sqlx-sqlite/src/types/time.rs b/vendor/sqlx-sqlite/src/types/time.rs new file mode 100755 index 000000000000..0e0027882d61 --- /dev/null +++ b/vendor/sqlx-sqlite/src/types/time.rs @@ -0,0 +1,319 @@ +use crate::arguments::SqliteArgumentsBuffer; +use crate::value::ValueRef; +use crate::{ + decode::Decode, + encode::{Encode, IsNull}, + error::BoxDynError, + type_info::DataType, + types::Type, + Sqlite, SqliteTypeInfo, SqliteValueRef, +}; +use time::format_description::{well_known::Rfc3339, BorrowedFormatItem}; +use time::macros::format_description as fd; +use time::{Date, OffsetDateTime, PrimitiveDateTime, Time}; + +impl Type for OffsetDateTime { + fn type_info() -> SqliteTypeInfo { + SqliteTypeInfo(DataType::Datetime) + } + + fn compatible(ty: &SqliteTypeInfo) -> bool { + >::compatible(ty) + } +} + +impl Type for PrimitiveDateTime { + fn type_info() -> SqliteTypeInfo { + SqliteTypeInfo(DataType::Datetime) + } + + fn compatible(ty: &SqliteTypeInfo) -> bool { + matches!( + ty.0, + DataType::Datetime | DataType::Text | DataType::Integer | DataType::Int4 + ) + } +} + +impl Type for Date { + fn type_info() -> SqliteTypeInfo { + SqliteTypeInfo(DataType::Date) + } + + fn compatible(ty: &SqliteTypeInfo) -> bool { + matches!(ty.0, DataType::Date | DataType::Text) + } +} + +impl Type for Time { + fn type_info() -> SqliteTypeInfo { + SqliteTypeInfo(DataType::Time) + } + + fn compatible(ty: &SqliteTypeInfo) -> bool { + matches!(ty.0, DataType::Time | DataType::Text) + } +} + +impl Encode<'_, Sqlite> for OffsetDateTime { + fn encode_by_ref(&self, buf: &mut SqliteArgumentsBuffer) -> Result { + Encode::::encode(self.format(&Rfc3339)?, buf) + } +} + +impl Encode<'_, Sqlite> for PrimitiveDateTime { + fn encode_by_ref(&self, buf: &mut SqliteArgumentsBuffer) -> Result { + let format = fd!("[year]-[month]-[day] [hour]:[minute]:[second].[subsecond]"); + Encode::::encode(self.format(&format)?, buf) + } +} + +impl Encode<'_, Sqlite> for Date { + fn encode_by_ref(&self, buf: &mut SqliteArgumentsBuffer) -> Result { + let format = fd!("[year]-[month]-[day]"); + Encode::::encode(self.format(&format)?, buf) + } +} + +impl Encode<'_, Sqlite> for Time { + fn encode_by_ref(&self, buf: &mut SqliteArgumentsBuffer) -> Result { + let format = fd!("[hour]:[minute]:[second].[subsecond]"); + Encode::::encode(self.format(&format)?, buf) + } +} + +impl<'r> Decode<'r, Sqlite> for OffsetDateTime { + fn decode(value: SqliteValueRef<'r>) -> Result { + decode_offset_datetime(value) + } +} + +impl<'r> Decode<'r, Sqlite> for PrimitiveDateTime { + fn decode(value: SqliteValueRef<'r>) -> Result { + decode_datetime(value) + } +} + +impl<'r> Decode<'r, Sqlite> for Date { + fn decode(value: SqliteValueRef<'r>) -> Result { + Ok(Date::parse( + value.text_borrowed()?, + &fd!("[year]-[month]-[day]"), + )?) + } +} + +impl<'r> Decode<'r, Sqlite> for Time { + fn decode(value: SqliteValueRef<'r>) -> Result { + let value = value.text_borrowed()?; + + let sqlite_time_formats = &[ + fd!("[hour]:[minute]:[second].[subsecond]"), + fd!("[hour]:[minute]:[second]"), + fd!("[hour]:[minute]"), + ]; + + for format in sqlite_time_formats { + if let Ok(dt) = Time::parse(value, &format) { + return Ok(dt); + } + } + + Err(format!("invalid time: {value}").into()) + } +} + +fn decode_offset_datetime(value: SqliteValueRef<'_>) -> Result { + let dt = match value.type_info().0 { + DataType::Text => decode_offset_datetime_from_text(value.text_borrowed()?), + DataType::Int4 | DataType::Integer => { + Some(OffsetDateTime::from_unix_timestamp(value.int64()?)?) + } + + _ => None, + }; + + if let Some(dt) = dt { + Ok(dt) + } else { + Err(format!("invalid offset datetime: {}", value.text_borrowed()?).into()) + } +} + +fn decode_offset_datetime_from_text(value: &str) -> Option { + if let Ok(dt) = OffsetDateTime::parse(value, &Rfc3339) { + return Some(dt); + } + + if let Ok(dt) = OffsetDateTime::parse(value, formats::OFFSET_DATE_TIME) { + return Some(dt); + } + + if let Some(dt) = decode_datetime_from_text(value) { + return Some(dt.assume_utc()); + } + + None +} + +fn decode_datetime(value: SqliteValueRef<'_>) -> Result { + let dt = match value.type_info().0 { + DataType::Text => decode_datetime_from_text(value.text_borrowed()?), + DataType::Int4 | DataType::Integer => { + let parsed = OffsetDateTime::from_unix_timestamp(value.int64()?).unwrap(); + Some(PrimitiveDateTime::new(parsed.date(), parsed.time())) + } + + _ => None, + }; + + if let Some(dt) = dt { + Ok(dt) + } else { + Err(format!("invalid datetime: {}", value.text_borrowed()?).into()) + } +} + +fn decode_datetime_from_text(value: &str) -> Option { + let default_format = fd!("[year]-[month]-[day] [hour]:[minute]:[second].[subsecond]"); + if let Ok(dt) = PrimitiveDateTime::parse(value, &default_format) { + return Some(dt); + } + + let formats = [ + BorrowedFormatItem::Compound(formats::PRIMITIVE_DATE_TIME_SPACE_SEPARATED), + BorrowedFormatItem::Compound(formats::PRIMITIVE_DATE_TIME_T_SEPARATED), + ]; + + if let Ok(dt) = PrimitiveDateTime::parse(value, &BorrowedFormatItem::First(&formats)) { + return Some(dt); + } + + None +} + +mod formats { + use time::format_description::BorrowedFormatItem::{Component, Literal, Optional}; + use time::format_description::{modifier, BorrowedFormatItem, Component::*}; + + const YEAR: BorrowedFormatItem<'_> = Component(Year({ + let mut value = modifier::Year::default(); + value.padding = modifier::Padding::Zero; + value.repr = modifier::YearRepr::Full; + value.iso_week_based = false; + value.sign_is_mandatory = false; + value + })); + + const MONTH: BorrowedFormatItem<'_> = Component(Month({ + let mut value = modifier::Month::default(); + value.padding = modifier::Padding::Zero; + value.repr = modifier::MonthRepr::Numerical; + value.case_sensitive = true; + value + })); + + const DAY: BorrowedFormatItem<'_> = Component(Day({ + let mut value = modifier::Day::default(); + value.padding = modifier::Padding::Zero; + value + })); + + const HOUR: BorrowedFormatItem<'_> = Component(Hour({ + let mut value = modifier::Hour::default(); + value.padding = modifier::Padding::Zero; + value.is_12_hour_clock = false; + value + })); + + const MINUTE: BorrowedFormatItem<'_> = Component(Minute({ + let mut value = modifier::Minute::default(); + value.padding = modifier::Padding::Zero; + value + })); + + const SECOND: BorrowedFormatItem<'_> = Component(Second({ + let mut value = modifier::Second::default(); + value.padding = modifier::Padding::Zero; + value + })); + + const SUBSECOND: BorrowedFormatItem<'_> = Component(Subsecond({ + let mut value = modifier::Subsecond::default(); + value.digits = modifier::SubsecondDigits::OneOrMore; + value + })); + + const OFFSET_HOUR: BorrowedFormatItem<'_> = Component(OffsetHour({ + let mut value = modifier::OffsetHour::default(); + value.sign_is_mandatory = true; + value.padding = modifier::Padding::Zero; + value + })); + + const OFFSET_MINUTE: BorrowedFormatItem<'_> = Component(OffsetMinute({ + let mut value = modifier::OffsetMinute::default(); + value.padding = modifier::Padding::Zero; + value + })); + + pub(super) const OFFSET_DATE_TIME: &[BorrowedFormatItem<'_>] = { + &[ + YEAR, + Literal(b"-"), + MONTH, + Literal(b"-"), + DAY, + Optional(&Literal(b" ")), + Optional(&Literal(b"T")), + HOUR, + Literal(b":"), + MINUTE, + Optional(&Literal(b":")), + Optional(&SECOND), + Optional(&Literal(b".")), + Optional(&SUBSECOND), + Optional(&OFFSET_HOUR), + Optional(&Literal(b":")), + Optional(&OFFSET_MINUTE), + ] + }; + + pub(super) const PRIMITIVE_DATE_TIME_SPACE_SEPARATED: &[BorrowedFormatItem<'_>] = { + &[ + YEAR, + Literal(b"-"), + MONTH, + Literal(b"-"), + DAY, + Literal(b" "), + HOUR, + Literal(b":"), + MINUTE, + Optional(&Literal(b":")), + Optional(&SECOND), + Optional(&Literal(b".")), + Optional(&SUBSECOND), + Optional(&Literal(b"Z")), + ] + }; + + pub(super) const PRIMITIVE_DATE_TIME_T_SEPARATED: &[BorrowedFormatItem<'_>] = { + &[ + YEAR, + Literal(b"-"), + MONTH, + Literal(b"-"), + DAY, + Literal(b"T"), + HOUR, + Literal(b":"), + MINUTE, + Optional(&Literal(b":")), + Optional(&SECOND), + Optional(&Literal(b".")), + Optional(&SUBSECOND), + Optional(&Literal(b"Z")), + ] + }; +} diff --git a/vendor/sqlx-sqlite/src/types/uint.rs b/vendor/sqlx-sqlite/src/types/uint.rs new file mode 100755 index 000000000000..1e8b1c539211 --- /dev/null +++ b/vendor/sqlx-sqlite/src/types/uint.rs @@ -0,0 +1,99 @@ +use crate::arguments::SqliteArgumentsBuffer; +use crate::decode::Decode; +use crate::encode::{Encode, IsNull}; +use crate::error::BoxDynError; +use crate::type_info::DataType; +use crate::types::Type; +use crate::{Sqlite, SqliteArgumentValue, SqliteTypeInfo, SqliteValueRef}; + +impl Type for u8 { + fn type_info() -> SqliteTypeInfo { + SqliteTypeInfo(DataType::Int4) + } + + fn compatible(ty: &SqliteTypeInfo) -> bool { + matches!(ty.0, DataType::Int4 | DataType::Integer) + } +} + +impl Encode<'_, Sqlite> for u8 { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Int(*self as i32)); + + Ok(IsNull::No) + } +} + +impl<'r> Decode<'r, Sqlite> for u8 { + fn decode(value: SqliteValueRef<'r>) -> Result { + // NOTE: using `sqlite3_value_int64()` here because `sqlite3_value_int()` silently truncates + // which leads to bugs, e.g.: + // https://github.com/launchbadge/sqlx/issues/3179 + // Similar bug in Postgres: https://github.com/launchbadge/sqlx/issues/3161 + Ok(value.int64()?.try_into()?) + } +} + +impl Type for u16 { + fn type_info() -> SqliteTypeInfo { + SqliteTypeInfo(DataType::Int4) + } + + fn compatible(ty: &SqliteTypeInfo) -> bool { + matches!(ty.0, DataType::Int4 | DataType::Integer) + } +} + +impl Encode<'_, Sqlite> for u16 { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Int(*self as i32)); + + Ok(IsNull::No) + } +} + +impl<'r> Decode<'r, Sqlite> for u16 { + fn decode(value: SqliteValueRef<'r>) -> Result { + Ok(value.int64()?.try_into()?) + } +} + +impl Type for u32 { + fn type_info() -> SqliteTypeInfo { + SqliteTypeInfo(DataType::Integer) + } + + fn compatible(ty: &SqliteTypeInfo) -> bool { + matches!(ty.0, DataType::Int4 | DataType::Integer) + } +} + +impl Encode<'_, Sqlite> for u32 { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Int64(*self as i64)); + + Ok(IsNull::No) + } +} + +impl<'r> Decode<'r, Sqlite> for u32 { + fn decode(value: SqliteValueRef<'r>) -> Result { + Ok(value.int64()?.try_into()?) + } +} + +impl Type for u64 { + fn type_info() -> SqliteTypeInfo { + SqliteTypeInfo(DataType::Integer) + } + + fn compatible(ty: &SqliteTypeInfo) -> bool { + matches!(ty.0, DataType::Int4 | DataType::Integer) + } +} + +impl<'r> Decode<'r, Sqlite> for u64 { + fn decode(value: SqliteValueRef<'r>) -> Result { + Ok(value.int64()?.try_into()?) + } +} diff --git a/vendor/sqlx-sqlite/src/types/uuid.rs b/vendor/sqlx-sqlite/src/types/uuid.rs new file mode 100755 index 000000000000..718ca5fb5d21 --- /dev/null +++ b/vendor/sqlx-sqlite/src/types/uuid.rs @@ -0,0 +1,85 @@ +use crate::arguments::SqliteArgumentsBuffer; +use crate::decode::Decode; +use crate::encode::{Encode, IsNull}; +use crate::error::BoxDynError; +use crate::type_info::DataType; +use crate::types::Type; +use crate::{Sqlite, SqliteArgumentValue, SqliteTypeInfo, SqliteValueRef}; +use std::sync::Arc; +use uuid::{ + fmt::{Hyphenated, Simple}, + Uuid, +}; + +impl Type for Uuid { + fn type_info() -> SqliteTypeInfo { + SqliteTypeInfo(DataType::Blob) + } + + fn compatible(ty: &SqliteTypeInfo) -> bool { + matches!(ty.0, DataType::Blob | DataType::Text) + } +} + +impl Encode<'_, Sqlite> for Uuid { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Blob(Arc::new( + self.as_bytes().to_vec(), + ))); + + Ok(IsNull::No) + } +} + +impl Decode<'_, Sqlite> for Uuid { + fn decode(value: SqliteValueRef<'_>) -> Result { + // construct a Uuid from the returned bytes + Uuid::from_slice(value.blob_borrowed()).map_err(Into::into) + } +} + +impl Type for Hyphenated { + fn type_info() -> SqliteTypeInfo { + SqliteTypeInfo(DataType::Text) + } +} + +impl Encode<'_, Sqlite> for Hyphenated { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Text(Arc::new(self.to_string()))); + + Ok(IsNull::No) + } +} + +impl Decode<'_, Sqlite> for Hyphenated { + fn decode(value: SqliteValueRef<'_>) -> Result { + let uuid: Result = + Uuid::parse_str(&value.text_borrowed().map(ToOwned::to_owned)?).map_err(Into::into); + + Ok(uuid?.hyphenated()) + } +} + +impl Type for Simple { + fn type_info() -> SqliteTypeInfo { + SqliteTypeInfo(DataType::Text) + } +} + +impl Encode<'_, Sqlite> for Simple { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Text(Arc::new(self.to_string()))); + + Ok(IsNull::No) + } +} + +impl Decode<'_, Sqlite> for Simple { + fn decode(value: SqliteValueRef<'_>) -> Result { + let uuid: Result = + Uuid::parse_str(&value.text_borrowed().map(ToOwned::to_owned)?).map_err(Into::into); + + Ok(uuid?.simple()) + } +} diff --git a/vendor/sqlx-sqlite/src/value.rs b/vendor/sqlx-sqlite/src/value.rs new file mode 100755 index 000000000000..bdf376c18794 --- /dev/null +++ b/vendor/sqlx-sqlite/src/value.rs @@ -0,0 +1,416 @@ +use std::borrow::Cow; +use std::cell::OnceCell; +use std::ptr::NonNull; +use std::slice; +use std::str; + +use libsqlite3_sys::{ + sqlite3_value, sqlite3_value_blob, sqlite3_value_bytes, sqlite3_value_double, + sqlite3_value_dup, sqlite3_value_free, sqlite3_value_int64, sqlite3_value_type, +}; +use sqlx_core::type_info::TypeInfo; +pub(crate) use sqlx_core::value::{Value, ValueRef}; + +use crate::type_info::DataType; +use crate::{Sqlite, SqliteError, SqliteTypeInfo}; + +/// An owned handle to a [`sqlite3_value`]. +/// +/// # Note: Decoding is Stateful +/// The [`sqlite3_value` interface][value-methods] reserves the right to be stateful: +/// +/// > Other interfaces might change the datatype for an sqlite3_value object. +/// > For example, if the datatype is initially SQLITE_INTEGER and sqlite3_value_text(V) is called +/// > to extract a text value for that integer, then subsequent calls to sqlite3_value_type(V) +/// > might return SQLITE_TEXT. Whether or not a persistent internal datatype conversion occurs is +/// > undefined and may change from one release of SQLite to the next. +/// +/// Thus, this type is `!Sync` and [`SqliteValueRef`] is `!Send` and `!Sync` to prevent data races. +/// +/// Additionally, this statefulness means that the return values of `sqlite3_value_bytes()` and +/// `sqlite3_value_blob()` could be invalidated by later calls to other `sqlite3_value*` methods. +/// +/// To prevent undefined behavior from accessing dangling pointers, this type (and any +/// [`SqliteValueRef`] instances created from it) remembers when it was used to decode a +/// borrowed `&[u8]` or `&str` and returns an error if it is used to decode any other type. +/// +/// To bypass this error, you must prove that no outstanding borrows exist. +/// +/// This may be done in one of a few ways: +/// * If you hold mutable access, call [`Self::reset_borrow()`] which resets the borrowed state. +/// * If you have an immutable reference, call [`Self::clone()`] to get a new instance +/// with no outstanding borrows. +/// * If you hold a [`SqliteValueRef`], call [`SqliteValueRef::to_owned()`] +/// to get a new `SqliteValue` with no outstanding borrows. +/// +/// This is *only* necessary if using the same `SqliteValue` or [`SqliteValueRef`] to decode +/// multiple different types. The vast majority of use-cases employing once-through decoding +/// should not have to worry about this. +/// +/// [`sqlite3_value`]: https://www.sqlite.org/c3ref/value.html +/// [value-methods]: https://www.sqlite.org/c3ref/value_blob.html +pub struct SqliteValue(ValueHandle); + +/// A borrowed reference to a [`sqlite3_value`]. +/// +/// Semantically, this behaves as a reference to [`SqliteValue`]. +/// +/// # Note: Decoding is Stateful +/// See [`SqliteValue`] for details. +pub struct SqliteValueRef<'r>(Cow<'r, ValueHandle>); + +impl SqliteValue { + // SAFETY: The sqlite3_value must be non-null and SQLite must not free it. It will be freed on drop. + pub(crate) unsafe fn dup( + value: *mut sqlite3_value, + column_type: Option, + ) -> Self { + debug_assert!(!value.is_null()); + let handle = ValueHandle::try_dup_of(value, column_type) + .expect("SQLite failed to allocate memory for duplicated value"); + Self(handle) + } + + /// Prove that there are no outstanding borrows of this instance. + /// + /// Call this after decoding a borrowed `&[u8]` or `&str` + /// to reset the internal borrowed state and allow decoding of other types. + pub fn reset_borrow(&mut self) { + self.0.reset_blob_borrow(); + } + + /// Call [`sqlite3_value_dup()`] to create a new instance of this type. + /// + /// Returns an error if the call returns a null pointer, indicating that + /// SQLite was unable to allocate the additional memory required. + /// + /// Non-panicking version of [`Self::clone()`]. + /// + /// [`sqlite3_value_dup()`]: https://www.sqlite.org/c3ref/value_dup.html + pub fn try_clone(&self) -> Result { + self.0.try_dup().map(Self) + } +} + +impl Clone for SqliteValue { + /// Call [`sqlite3_value_dup()`] to create a new instance of this type. + /// + /// # Panics + /// If [`sqlite3_value_dup()`] returns a null pointer, indicating an out-of-memory condition. + /// + /// See [`Self::try_clone()`] for a non-panicking version. + /// + /// [`sqlite3_value_dup()`]: https://www.sqlite.org/c3ref/value_dup.html + fn clone(&self) -> Self { + self.try_clone().expect("failed to clone `SqliteValue`") + } +} + +impl Value for SqliteValue { + type Database = Sqlite; + + fn as_ref(&self) -> SqliteValueRef<'_> { + SqliteValueRef::value(self) + } + + fn type_info(&self) -> Cow<'_, SqliteTypeInfo> { + Cow::Owned(self.0.type_info()) + } + + fn is_null(&self) -> bool { + self.0.is_null() + } +} + +impl<'r> SqliteValueRef<'r> { + /// Attempt to duplicate the internal `sqlite3_value` with [`sqlite3_value_dup()`]. + /// + /// Returns an error if the call returns a null pointer, indicating that + /// SQLite was unable to allocate the additional memory required. + /// + /// Non-panicking version of [`Self::try_to_owned()`]. + /// + /// [`sqlite3_value_dup()`]: https://www.sqlite.org/c3ref/value_dup.html + pub fn try_to_owned(&self) -> Result { + self.0.try_dup().map(SqliteValue) + } + + pub(crate) fn value(value: &'r SqliteValue) -> Self { + Self(Cow::Borrowed(&value.0)) + } + + /// # Safety + /// The supplied sqlite3_value must not be null and SQLite must free it. + /// It will not be freed on drop. + /// The lifetime on this struct should tie it to whatever scope it's valid for before SQLite frees it. + #[allow(unused)] + pub(crate) unsafe fn borrowed(value: *mut sqlite3_value) -> Self { + debug_assert!(!value.is_null()); + let handle = ValueHandle::temporary(NonNull::new_unchecked(value)); + Self(Cow::Owned(handle)) + } + + // NOTE: `int()` is deliberately omitted because it will silently truncate a wider value, + // which is likely to cause bugs: + // https://github.com/launchbadge/sqlx/issues/3179 + // (Similar bug in Postgres): https://github.com/launchbadge/sqlx/issues/3161 + pub(super) fn int64(&self) -> Result { + self.0.int64() + } + + pub(super) fn double(&self) -> Result { + self.0.double() + } + + pub(super) fn blob_borrowed(&self) -> &'r [u8] { + // SAFETY: lifetime is matched to `'r` + unsafe { self.0.blob_borrowed() } + } + + pub(super) fn with_temp_blob(&self, op: impl FnOnce(&[u8]) -> R) -> R { + self.0.with_blob(op) + } + + pub(super) fn blob_owned(&self) -> Vec { + self.with_temp_blob(|blob| blob.to_vec()) + } + + pub(super) fn text_borrowed(&self) -> Result<&'r str, str::Utf8Error> { + // SAFETY: lifetime is matched to `'r` + unsafe { self.0.text_borrowed() } + } + + pub(super) fn with_temp_text( + &self, + op: impl FnOnce(&str) -> R, + ) -> Result { + self.0.with_blob(|blob| str::from_utf8(blob).map(op)) + } + + pub(super) fn text_owned(&self) -> Result { + self.with_temp_text(|text| text.to_string()) + } +} + +impl<'r> ValueRef<'r> for SqliteValueRef<'r> { + type Database = Sqlite; + + /// Attempt to duplicate the internal `sqlite3_value` with [`sqlite3_value_dup()`]. + /// + /// # Panics + /// If [`sqlite3_value_dup()`] returns a null pointer, indicating an out-of-memory condition. + /// + /// See [`Self::try_to_owned()`] for a non-panicking version. + /// + /// [`sqlite3_value_dup()`]: https://www.sqlite.org/c3ref/value_dup.html + fn to_owned(&self) -> SqliteValue { + SqliteValue( + self.0 + .try_dup() + .expect("failed to convert SqliteValueRef to owned SqliteValue"), + ) + } + + fn type_info(&self) -> Cow<'_, SqliteTypeInfo> { + Cow::Owned(self.0.type_info()) + } + + fn is_null(&self) -> bool { + self.0.is_null() + } +} + +pub(crate) struct ValueHandle { + value: NonNull, + column_type: Option, + // Note: `std::cell` version + borrowed_blob: OnceCell, + free_on_drop: bool, +} + +struct Blob { + ptr: *const u8, + len: usize, +} + +#[derive(Debug, thiserror::Error)] +#[error("given `SqliteValue` was previously decoded as BLOB or TEXT; `SqliteValue::reset_borrow()` must be called first")] +pub(crate) struct BorrowedBlobError; + +// SAFE: only protected value objects are stored in SqliteValue +unsafe impl Send for ValueHandle {} + +// SAFETY: the `sqlite3_value_*()` methods reserve the right to be stateful, +// which means method calls aren't thread-safe without mutual exclusion. +// +// impl !Sync for ValueHandle {} + +impl ValueHandle { + /// # Safety + /// The `sqlite3_value` must be valid and SQLite must not free it. It will be freed on drop. + unsafe fn try_dup_of( + value: *mut sqlite3_value, + column_type: Option, + ) -> Result { + // SAFETY: caller must ensure `value` is valid. + let value = + unsafe { NonNull::new(sqlite3_value_dup(value)).ok_or_else(SqliteError::nomem)? }; + + Ok(Self { + value, + column_type, + borrowed_blob: OnceCell::new(), + free_on_drop: true, + }) + } + + fn temporary(value: NonNull) -> Self { + Self { + value, + column_type: None, + borrowed_blob: OnceCell::new(), + free_on_drop: false, + } + } + + fn try_dup(&self) -> Result { + // SAFETY: `value` is initialized + unsafe { Self::try_dup_of(self.value.as_ptr(), self.column_type.clone()) } + } + + fn value_type_info(&self) -> SqliteTypeInfo { + SqliteTypeInfo(DataType::from_code(unsafe { + sqlite3_value_type(self.value.as_ptr()) + })) + } + + fn type_info(&self) -> SqliteTypeInfo { + let value_type = self.value_type_info(); + + // Assume the actual value type is more accurate, if it's not NULL. + match &self.column_type { + Some(column_type) if value_type.is_null() => column_type.clone(), + _ => value_type, + } + } + + fn int64(&self) -> Result { + // SAFETY: we have to be certain the caller isn't still holding a borrow from `.blob_borrowed()` + self.assert_blob_not_borrowed()?; + + Ok(unsafe { sqlite3_value_int64(self.value.as_ptr()) }) + } + + fn double(&self) -> Result { + // SAFETY: we have to be certain the caller isn't still holding a borrow from `.blob_borrowed()` + self.assert_blob_not_borrowed()?; + + Ok(unsafe { sqlite3_value_double(self.value.as_ptr()) }) + } + + fn is_null(&self) -> bool { + self.value_type_info().is_null() + } +} + +impl Clone for ValueHandle { + fn clone(&self) -> Self { + self.try_dup().unwrap() + } +} + +impl Drop for ValueHandle { + fn drop(&mut self) { + if self.free_on_drop { + unsafe { + sqlite3_value_free(self.value.as_ptr()); + } + } + } +} + +impl ValueHandle { + fn assert_blob_not_borrowed(&self) -> Result<(), BorrowedBlobError> { + if self.borrowed_blob.get().is_none() { + Ok(()) + } else { + Err(BorrowedBlobError) + } + } + + fn reset_blob_borrow(&mut self) { + self.borrowed_blob.take(); + } + + fn get_blob(&self) -> Option { + if let Some(blob) = self.borrowed_blob.get() { + return Some(Blob { ..*blob }); + } + + // SAFETY: calling `sqlite3_value_bytes` from multiple threads at once is a data race. + let len = unsafe { sqlite3_value_bytes(self.value.as_ptr()) }; + + // This likely means UB in SQLite itself or our usage of it; + // signed integer overflow is UB in the C standard. + let len = usize::try_from(len).unwrap_or_else(|_| { + panic!("sqlite3_value_bytes() returned value out of range for usize: {len}") + }); + + if len == 0 { + // empty blobs are NULL + return None; + } + + let ptr = unsafe { sqlite3_value_blob(self.value.as_ptr()) } as *const u8; + debug_assert!(!ptr.is_null()); + + Some(Blob { ptr, len }) + } + + fn with_blob(&self, with_blob: impl FnOnce(&[u8]) -> R) -> R { + let Some(blob) = self.get_blob() else { + return with_blob(&[]); + }; + + // SAFETY: the slice cannot outlive the call + with_blob(unsafe { blob.as_slice() }) + } + + /// # Safety + /// Caller must ensure lifetime '`b` cannot outlive `self`. + unsafe fn blob_borrowed<'a>(&self) -> &'a [u8] { + let Some(blob) = self.get_blob() else { + return &[]; + }; + + // SAFETY: we need to store that the blob was borrowed + // to prevent + let blob = self.borrowed_blob.get_or_init(|| blob); + + unsafe { blob.as_slice() } + } + + /// # Safety + /// Caller must ensure lifetime '`b` cannot outlive `self`. + unsafe fn text_borrowed<'b>(&self) -> Result<&'b str, str::Utf8Error> { + let Some(blob) = self.get_blob() else { + return Ok(""); + }; + + // SAFETY: lifetime of `blob` will be tied to `'b`. + let s = str::from_utf8(unsafe { blob.as_slice() })?; + + // We only store the borrow after we ensure the string is valid. + self.borrowed_blob.set(blob).ok(); + + Ok(s) + } +} + +impl Blob { + /// # Safety + /// `'a` must not outlive the `sqlite3_value` this blob came from. + unsafe fn as_slice<'a>(&self) -> &'a [u8] { + slice::from_raw_parts(self.ptr, self.len) + } +}