From 2a44db8d52dd7eafd80f7d3102ed8f5a169252c2 Mon Sep 17 00:00:00 2001 From: robertlordhood <204023072+robertlordhood@users.noreply.github.com> Date: Sat, 5 Dec 2026 20:01:50 +0000 Subject: [PATCH 1/3] Speed up CI by building once and splitting the slowest test jobs Each pull request test job compiled Chaptarr itself, and the whole Core suite ran on a single Windows runner and a single PostgreSQL runner. Those two jobs took about 28 and 25 minutes on #371. Linux and Windows now compile once per platform and hand the binaries to their test jobs, and Linux SQLite and PostgreSQL share the Linux build. Windows and PostgreSQL split the suite across two runners each. Their required checks pass only when both halves ran the same test assembly and together ran every planned test exactly once without a failure. The browser checks moved into the frontend job, beside the .NET jobs. The five required check names are unchanged. For releases, the Docker images use the UI that the same release run already built and checked. Each architecture gets its own APT cache, so the three image builds no longer wait on one lock, and the build cache exports only the final image's layers. This also removes a pending author import retry test that never reached the retry. Its fake repository holds no pending row, so the retry returns on its first check, and the test's one-second limit failed Windows CI. --- .github/actions/compile-ci/action.yml | 105 +++ .github/actions/load-ci-runtime/action.yml | 14 + .github/workflows/build.yml | 599 +++++++++++------- .github/workflows/docker-publish.yml | 10 +- .github/workflows/release.yml | 2 + Dockerfile.cross | 48 +- build-tools/run-core-tests.py | 114 +++- build-tools/test_run_core_tests.py | 59 ++ frontend/build/check-author-search.cjs | 59 +- .../Books/PendingAuthorImportRetryFixture.cs | 25 - 10 files changed, 707 insertions(+), 328 deletions(-) create mode 100644 .github/actions/compile-ci/action.yml create mode 100644 .github/actions/load-ci-runtime/action.yml diff --git a/.github/actions/compile-ci/action.yml b/.github/actions/compile-ci/action.yml new file mode 100644 index 000000000..f51234dd0 --- /dev/null +++ b/.github/actions/compile-ci/action.yml @@ -0,0 +1,105 @@ +name: Compile Chaptarr for CI +description: Run the source guards and build the native package and Core test runtime. +runs: + using: composite + steps: + - name: Guard (repo) - no merge-conflict markers + shell: bash + run: | + if git grep -nE '^(<<<<<<<|=======|>>>>>>>)' -- .; then + echo "Merge-conflict markers found in tracked files." + exit 1 + fi + python -c "import json; json.load(open('package.json', encoding='utf-8'))" + + - name: Guard (version) - package.json and Directory.Build.props in sync + shell: bash + run: python3 build-tools/version_guard.py sync + + - name: Guard (version) - no decreases on develop + if: github.ref == 'refs/heads/develop' || github.base_ref == 'develop' + shell: bash + run: | + set -euo pipefail + + if [[ "${{ github.event_name }}" == "pull_request" ]]; then + git fetch --no-tags origin "refs/heads/develop:refs/remotes/origin/develop" + COMPARE_REF="origin/develop" + else + COMPARE_REF="$(git describe --tags --match 'v*' --abbrev=0 HEAD 2>/dev/null || true)" + + if [[ -z "$COMPARE_REF" ]]; then + echo "No reachable version tag is available for monotonic version comparison." + exit 1 + fi + fi + + python3 build-tools/version_guard.py monotonic \ + --compare-ref "$COMPARE_REF" \ + --event-path "$GITHUB_EVENT_PATH" + + - name: Guard (version) - version-only commits stay pure + shell: bash + run: | + set -euo pipefail + + if [[ "${{ github.event_name }}" == "pull_request" ]]; then + git fetch --no-tags origin "refs/heads/${{ github.base_ref }}:refs/remotes/origin/${{ github.base_ref }}" + COMPARE_REF="origin/${{ github.base_ref }}" + else + COMPARE_REF="$(git describe --tags --match 'v*' --abbrev=0 HEAD 2>/dev/null || true)" + + if [[ -z "$COMPARE_REF" ]]; then + echo "No reachable version tag is available for version-only commit hygiene." + exit 1 + fi + fi + + python3 build-tools/version_guard.py commit-hygiene --compare-ref "$COMPARE_REF" + + - name: Setup .NET + uses: actions/setup-dotnet@67a3573c9a986a3f9c594539f4ab511d57bb3ce9 + with: + dotnet-version: 10.0.x + + - name: Cache NuGet packages + if: runner.os == 'Windows' + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ~/.nuget/packages + key: ${{ runner.os }}-${{ runner.arch }}-nuget-${{ hashFiles('src/NuGet.config', 'src/Directory.Packages.props', 'src/Directory.Build.props', 'src/Directory.Build.targets', 'src/Targets/**/*.targets', 'src/Chaptarr.NoTests.sln', 'src/**/*.csproj') }} + restore-keys: | + ${{ runner.os }}-${{ runner.arch }}-nuget- + + # FFmpeg is intentionally not downloaded in this compile/test workflow. + # Source builds resolve bundled tools first and then the system PATH; explicit + # native packaging owns bundled-tool acquisition and validation. + + - name: Restore dependencies + shell: bash + run: | + dotnet restore src/Chaptarr.NoTests.sln + dotnet restore src/Chaptarr.Core.Test/Chaptarr.Core.Test.csproj + + - name: Build + shell: bash + run: dotnet build src/Chaptarr.NoTests.sln --configuration Release --no-restore + + - name: Build Windows tray host + if: runner.os == 'Windows' + shell: bash + run: dotnet build src/NzbDrone/Chaptarr.csproj --configuration Release + + - name: Check Core test runner + shell: bash + run: python3 -m unittest discover -s build-tools -p test_run_core_tests.py + + - name: Build Core tests + shell: bash + run: dotnet build src/Chaptarr.Core.Test/Chaptarr.Core.Test.csproj --configuration Release --no-restore + + - name: Publish + shell: bash + run: | + dotnet publish src/NzbDrone.Console/Chaptarr.Console.csproj -c Release -f net10.0 -o ./publish/Chaptarr + dotnet publish src/NzbDrone.Update/Chaptarr.Update.csproj -c Release -f net10.0 -o ./publish/Chaptarr/Chaptarr.Update diff --git a/.github/actions/load-ci-runtime/action.yml b/.github/actions/load-ci-runtime/action.yml new file mode 100644 index 000000000..b47b798a8 --- /dev/null +++ b/.github/actions/load-ci-runtime/action.yml @@ -0,0 +1,14 @@ +name: Load the compiled CI runtime +description: Restore the same-run test payload built on this operating system. +runs: + using: composite + steps: + - uses: actions/setup-dotnet@67a3573c9a986a3f9c594539f4ab511d57bb3ce9 + with: + dotnet-version: 10.0.x + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: ci-runtime-${{ runner.os }} + - name: Unpack test and app binaries + shell: bash + run: tar -xf ci-runtime.tar diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 8b63ab0a7..7352488b3 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -4,6 +4,10 @@ on: pull_request: branches: [ main, develop ] workflow_call: + inputs: + release-frontend: + type: boolean + default: false workflow_dispatch: # Tests only, never publishes. Runs on PRs, not again after merge. @@ -20,7 +24,9 @@ jobs: # the later Docker build. The same frontend is used on every runtime platform. frontend: runs-on: ubuntu-latest - timeout-minutes: 20 + timeout-minutes: 90 + outputs: + browser-result: ${{ steps.browser_checks.outcome }} steps: - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 @@ -33,280 +39,106 @@ jobs: run: npm install -g "yarn@$(node -p 'require("./package.json").volta.yarn')" --force - name: Install frontend dependencies + id: frontend_deps run: yarn install --frozen-lockfile - - name: Typecheck - run: yarn typecheck - - - name: Check translation keys - run: yarn check-translations - - - name: Check user-facing JSX text - run: yarn check-jsx-literals - - - name: Build frontend - run: yarn build - - build: - timeout-minutes: 90 - runs-on: ${{ matrix.os }} - strategy: - fail-fast: false - matrix: - os: [ubuntu-latest, windows-latest, macos-latest] - include: - - os: ubuntu-latest - platform: linux - - os: windows-latest - platform: win - - os: macos-latest - platform: osx - - steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 - with: - fetch-depth: 0 - - - name: Guard (repo) - no merge-conflict markers - shell: bash - run: | - if git grep -nE '^(<<<<<<<|=======|>>>>>>>)' -- .; then - echo "Merge-conflict markers found in tracked files." - exit 1 - fi - python -c "import json; json.load(open('package.json', encoding='utf-8'))" - - - name: Guard (version) - package.json and Directory.Build.props in sync - shell: bash - run: python3 build-tools/version_guard.py sync - - - name: Guard (version) - no decreases on develop - if: github.ref == 'refs/heads/develop' || github.base_ref == 'develop' - shell: bash - run: | - set -euo pipefail - - if [[ "${{ github.event_name }}" == "pull_request" ]]; then - git fetch --no-tags origin "refs/heads/develop:refs/remotes/origin/develop" - COMPARE_REF="origin/develop" - else - COMPARE_REF="$(git describe --tags --match 'v*' --abbrev=0 HEAD 2>/dev/null || true)" - - if [[ -z "$COMPARE_REF" ]]; then - echo "No reachable version tag is available for monotonic version comparison." - exit 1 - fi - fi - - python3 build-tools/version_guard.py monotonic \ - --compare-ref "$COMPARE_REF" \ - --event-path "$GITHUB_EVENT_PATH" - - - name: Guard (version) - version-only commits stay pure - shell: bash - run: | - set -euo pipefail - - if [[ "${{ github.event_name }}" == "pull_request" ]]; then - git fetch --no-tags origin "refs/heads/${{ github.base_ref }}:refs/remotes/origin/${{ github.base_ref }}" - COMPARE_REF="origin/${{ github.base_ref }}" - else - COMPARE_REF="$(git describe --tags --match 'v*' --abbrev=0 HEAD 2>/dev/null || true)" - - if [[ -z "$COMPARE_REF" ]]; then - echo "No reachable version tag is available for version-only commit hygiene." - exit 1 - fi - fi - - python3 build-tools/version_guard.py commit-hygiene --compare-ref "$COMPARE_REF" - - - name: Setup .NET - uses: actions/setup-dotnet@67a3573c9a986a3f9c594539f4ab511d57bb3ce9 - with: - dotnet-version: 10.0.x - - - name: Cache NuGet packages - if: runner.os == 'Windows' - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ~/.nuget/packages - key: ${{ runner.os }}-${{ runner.arch }}-nuget-${{ hashFiles('src/NuGet.config', 'src/Directory.Packages.props', 'src/Directory.Build.props', 'src/Directory.Build.targets', 'src/Targets/**/*.targets', 'src/Chaptarr.NoTests.sln', 'src/**/*.csproj') }} - restore-keys: | - ${{ runner.os }}-${{ runner.arch }}-nuget- - - # FFmpeg is intentionally not downloaded in this compile/test workflow. - # Source builds resolve bundled tools first and then the system PATH; explicit - # native packaging owns bundled-tool acquisition and validation. - - - name: Restore dependencies - run: | - dotnet restore src/Chaptarr.NoTests.sln - dotnet restore src/Chaptarr.Core.Test/Chaptarr.Core.Test.csproj - - - name: Build - run: dotnet build src/Chaptarr.NoTests.sln --configuration Release --no-restore - - - name: Build Windows tray host - if: runner.os == 'Windows' - run: dotnet build src/NzbDrone/Chaptarr.csproj --configuration Release - - - name: Check Core test runner - run: python3 -m unittest discover -s build-tools -p test_run_core_tests.py - - - name: Build Core tests - run: dotnet build src/Chaptarr.Core.Test/Chaptarr.Core.Test.csproj --configuration Release --no-restore - - - name: Test - timeout-minutes: 60 - env: - CHAPTARR_PHOTO_RESPONSE: ${{ runner.temp }}/author-photo-response.json - run: python3 build-tools/run-core-tests.py --results TestResults/core --workers 6 - - - name: Upload Core test results - if: always() - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - with: - name: core-tests-${{ matrix.os }} - path: TestResults/core - - # Reuse the response emitted by the Core suite above. A correct API response - # alone cannot catch a carousel selecting the wrong photo after a reorder. - - name: Setup Node for browser check - if: runner.os == 'Linux' - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 - with: - node-version-file: package.json - - - name: Install browser check dependencies + - name: Install Chromium id: browser_deps + if: ${{ !cancelled() && steps.frontend_deps.outcome == 'success' }} timeout-minutes: 10 - if: runner.os == 'Linux' - run: | - npm install -g "yarn@$(node -p 'require("./package.json").volta.yarn')" --force - yarn install --frozen-lockfile - yarn playwright install --with-deps chromium + run: yarn playwright install --with-deps chromium - # Directory-based `yarn lint` does not discover these .cjs runners. - # Include the shared browser helpers as well as their check runners and fixtures. + # Directory-based lint does not discover the .cjs checks or helpers. - name: Lint browser checks timeout-minutes: 5 - if: ${{ !cancelled() && runner.os == 'Linux' && steps.browser_deps.outcome == 'success' }} + if: ${{ !cancelled() && steps.browser_deps.outcome == 'success' }} run: yarn lint-browser-checks - name: Check retag preview - if: ${{ !cancelled() && runner.os == 'Linux' && steps.browser_deps.outcome == 'success' }} + if: ${{ !cancelled() && steps.browser_deps.outcome == 'success' }} timeout-minutes: 5 env: TMPDIR: ${{ runner.temp }} run: yarn check-retag-preview - name: Check browser route capture - if: ${{ !cancelled() && runner.os == 'Linux' && steps.browser_deps.outcome == 'success' }} + if: ${{ !cancelled() && steps.browser_deps.outcome == 'success' }} timeout-minutes: 1 run: node --test frontend/build/capture-browser-route.test.cjs - - name: Check author photos - if: ${{ !cancelled() && runner.os == 'Linux' && steps.browser_deps.outcome == 'success' }} - timeout-minutes: 5 - env: - CHAPTARR_PHOTO_RESPONSE: ${{ runner.temp }}/author-photo-response.json - TMPDIR: ${{ runner.temp }} - run: yarn check-author-photo - - - name: Upload author photo evidence - if: ${{ !cancelled() && runner.os == 'Linux' }} - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - with: - name: author-photo-evidence - path: | - ${{ runner.temp }}/author-photo-response.json - ${{ runner.temp }}/chaptarr-photo-*/*.png - retention-days: 7 - if-no-files-found: warn - - # Covers the delete checkbox, the outgoing request body and the mobile layout. - # It does NOT prove filesystem deletion is safe -- the Core deletion fixtures do. + # The browser checks the dialog and request body. Core checks filesystem deletion. - name: Check author delete UI - if: ${{ !cancelled() && runner.os == 'Linux' && steps.browser_deps.outcome == 'success' }} + if: ${{ !cancelled() && steps.browser_deps.outcome == 'success' }} timeout-minutes: 5 env: TMPDIR: ${{ runner.temp }} run: yarn check-author-delete - - name: Check author search confirmation - if: ${{ !cancelled() && runner.os == 'Linux' && steps.browser_deps.outcome == 'success' }} - timeout-minutes: 5 - env: - TMPDIR: ${{ runner.temp }} - run: yarn check-author-search - - - name: Check author sync controls - if: ${{ !cancelled() && runner.os == 'Linux' && steps.browser_deps.outcome == 'success' }} - timeout-minutes: 5 + - name: Check author search and sync controls + if: ${{ !cancelled() && steps.browser_deps.outcome == 'success' }} + timeout-minutes: 10 env: TMPDIR: ${{ runner.temp }} - CHAPTARR_SYNC_ONLY: '1' - run: yarn check-author-search + run: yarn check-author-search --with-sync - name: Check author-entry - if: ${{ !cancelled() && runner.os == 'Linux' && steps.browser_deps.outcome == 'success' }} + if: ${{ !cancelled() && steps.browser_deps.outcome == 'success' }} timeout-minutes: 5 env: TMPDIR: ${{ runner.temp }} run: yarn check-author-entry - name: Check book-route-guards - if: ${{ !cancelled() && runner.os == 'Linux' && steps.browser_deps.outcome == 'success' }} + if: ${{ !cancelled() && steps.browser_deps.outcome == 'success' }} timeout-minutes: 5 env: TMPDIR: ${{ runner.temp }} run: yarn check-book-route-guards - name: Check header-search - if: ${{ !cancelled() && runner.os == 'Linux' && steps.browser_deps.outcome == 'success' }} + if: ${{ !cancelled() && steps.browser_deps.outcome == 'success' }} timeout-minutes: 5 env: TMPDIR: ${{ runner.temp }} run: yarn check-header-search - name: Check indexer-nfo - if: ${{ !cancelled() && runner.os == 'Linux' && steps.browser_deps.outcome == 'success' }} + if: ${{ !cancelled() && steps.browser_deps.outcome == 'success' }} timeout-minutes: 5 env: TMPDIR: ${{ runner.temp }} run: yarn check-indexer-nfo - name: Check ConfirmModal Enter behavior - if: ${{ !cancelled() && runner.os == 'Linux' && steps.browser_deps.outcome == 'success' }} + if: ${{ !cancelled() && steps.browser_deps.outcome == 'success' }} timeout-minutes: 5 env: TMPDIR: ${{ runner.temp }} run: yarn check-confirm-modal - name: Check manual import replacement confirmation - if: ${{ !cancelled() && runner.os == 'Linux' && steps.browser_deps.outcome == 'success' }} + if: ${{ !cancelled() && steps.browser_deps.outcome == 'success' }} timeout-minutes: 5 env: TMPDIR: ${{ runner.temp }} run: yarn check-manual-import-confirmation - name: Check installed-release popup - if: ${{ !cancelled() && runner.os == 'Linux' && steps.browser_deps.outcome == 'success' }} + if: ${{ !cancelled() && steps.browser_deps.outcome == 'success' }} timeout-minutes: 5 env: TMPDIR: ${{ runner.temp }} run: yarn check-update-popup - name: Check book-file deletion preview - if: ${{ !cancelled() && runner.os == 'Linux' && steps.browser_deps.outcome == 'success' }} + if: ${{ !cancelled() && steps.browser_deps.outcome == 'success' }} timeout-minutes: 5 env: TMPDIR: ${{ runner.temp }} run: yarn check-book-file-delete - name: Check Wanted Authors table and actions - if: ${{ !cancelled() && runner.os == 'Linux' && steps.browser_deps.outcome == 'success' }} + if: ${{ !cancelled() && steps.browser_deps.outcome == 'success' }} timeout-minutes: 5 env: TMPDIR: ${{ runner.temp }} @@ -314,7 +146,7 @@ jobs: run: yarn check-wanted-authors - name: Upload Wanted Authors evidence - if: ${{ !cancelled() && runner.os == 'Linux' }} + if: ${{ !cancelled() }} uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: wanted-authors-evidence @@ -323,49 +155,49 @@ jobs: if-no-files-found: warn - name: Check book-cover-scope - if: ${{ !cancelled() && runner.os == 'Linux' && steps.browser_deps.outcome == 'success' }} + if: ${{ !cancelled() && steps.browser_deps.outcome == 'success' }} timeout-minutes: 5 env: TMPDIR: ${{ runner.temp }} run: yarn check-book-cover-scope - name: Check media-management-cover-scope - if: ${{ !cancelled() && runner.os == 'Linux' && steps.browser_deps.outcome == 'success' }} + if: ${{ !cancelled() && steps.browser_deps.outcome == 'success' }} timeout-minutes: 5 env: TMPDIR: ${{ runner.temp }} run: yarn check-media-management-cover-scope - name: Check import-lists - if: ${{ !cancelled() && runner.os == 'Linux' && steps.browser_deps.outcome == 'success' }} + if: ${{ !cancelled() && steps.browser_deps.outcome == 'success' }} timeout-minutes: 5 env: TMPDIR: ${{ runner.temp }} run: yarn check-import-lists - name: Check backups - if: ${{ !cancelled() && runner.os == 'Linux' && steps.browser_deps.outcome == 'success' }} + if: ${{ !cancelled() && steps.browser_deps.outcome == 'success' }} timeout-minutes: 5 env: TMPDIR: ${{ runner.temp }} run: yarn check-backups - name: Check notification-upgrade - if: ${{ !cancelled() && runner.os == 'Linux' && steps.browser_deps.outcome == 'success' }} + if: ${{ !cancelled() && steps.browser_deps.outcome == 'success' }} timeout-minutes: 5 env: TMPDIR: ${{ runner.temp }} run: yarn check-notification-upgrade - name: Check smart-narrator - if: ${{ !cancelled() && runner.os == 'Linux' && steps.browser_deps.outcome == 'success' }} + if: ${{ !cancelled() && steps.browser_deps.outcome == 'success' }} timeout-minutes: 5 env: TMPDIR: ${{ runner.temp }} run: yarn check-smart-narrator - name: Upload cover settings evidence - if: ${{ !cancelled() && runner.os == 'Linux' }} + if: ${{ !cancelled() }} uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: cover-settings-evidence @@ -374,7 +206,7 @@ jobs: if-no-files-found: warn - name: Upload author delete evidence - if: ${{ !cancelled() && runner.os == 'Linux' }} + if: ${{ !cancelled() }} uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: author-delete-evidence @@ -383,7 +215,7 @@ jobs: if-no-files-found: warn - name: Check mobile toolbar - if: ${{ !cancelled() && runner.os == 'Linux' && steps.browser_deps.outcome == 'success' }} + if: ${{ !cancelled() && steps.browser_deps.outcome == 'success' }} timeout-minutes: 5 env: TMPDIR: ${{ runner.temp }} @@ -391,7 +223,7 @@ jobs: run: yarn check-mobile-toolbar - name: Upload mobile toolbar evidence - if: ${{ !cancelled() && runner.os == 'Linux' }} + if: ${{ !cancelled() }} uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: mobile-toolbar-evidence @@ -399,20 +231,292 @@ jobs: retention-days: 7 if-no-files-found: warn - - name: Publish + - name: Record successful browser checks + id: browser_checks + run: echo "Browser UI checks passed." + + - name: Typecheck + id: typecheck + if: ${{ !cancelled() && steps.frontend_deps.outcome == 'success' }} + run: yarn typecheck + + - name: Check translation keys + id: translations + if: ${{ !cancelled() && steps.typecheck.outcome == 'success' }} + run: yarn check-translations + + - name: Check user-facing JSX text + id: jsx_text + if: ${{ !cancelled() && steps.translations.outcome == 'success' }} + run: yarn check-jsx-literals + + - name: Build frontend + id: frontend_build + if: ${{ !cancelled() && steps.jsx_text.outcome == 'success' }} + run: yarn build + + - name: Upload validated release frontend + if: ${{ !cancelled() && inputs.release-frontend && steps.frontend_build.outcome == 'success' }} + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: release-frontend-${{ github.sha }} + path: _output/UI/ + if-no-files-found: error + retention-days: 30 + + compile-linux: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + with: + fetch-depth: 0 + - uses: ./.github/actions/compile-ci + + - name: Pack the compiled runtime + shell: bash + run: tar -cf ci-runtime.tar _tests/net10.0 _output/net10.0 + + - name: Upload the compiled runtime + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: ci-runtime-${{ runner.os }} + path: ci-runtime.tar + if-no-files-found: error + retention-days: 30 + + - name: Stage the native package + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: ci-package-${{ runner.os }} + path: ./publish/ + retention-days: 30 + if-no-files-found: error + + linux-core: + needs: compile-linux + runs-on: ubuntu-latest + timeout-minutes: 90 + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + - uses: ./.github/actions/load-ci-runtime + + - name: Test + timeout-minutes: 60 + env: + CHAPTARR_PHOTO_RESPONSE: ${{ runner.temp }}/author-photo-response.json + run: python3 build-tools/run-core-tests.py --results TestResults/core --workers 6 + + - name: Upload Core test results + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: core-tests-ubuntu-latest + path: TestResults/core + + # Reuse the response emitted by the Core suite above. A correct API response + # alone cannot catch a carousel selecting the wrong photo after a reorder. + - name: Setup Node for browser check + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 + with: + node-version-file: package.json + + - name: Install browser check dependencies + id: browser_deps + timeout-minutes: 10 run: | - dotnet publish src/NzbDrone.Console/Chaptarr.Console.csproj -c Release -f net10.0 -o ./publish/Chaptarr - dotnet publish src/NzbDrone.Update/Chaptarr.Update.csproj -c Release -f net10.0 -o ./publish/Chaptarr/Chaptarr.Update - + npm install -g "yarn@$(node -p 'require("./package.json").volta.yarn')" --force + yarn install --frozen-lockfile + yarn playwright install --with-deps chromium + + - name: Check author photos + if: ${{ !cancelled() && steps.browser_deps.outcome == 'success' }} + timeout-minutes: 5 + env: + CHAPTARR_PHOTO_RESPONSE: ${{ runner.temp }}/author-photo-response.json + TMPDIR: ${{ runner.temp }} + run: yarn check-author-photo + + - name: Upload author photo evidence + if: ${{ !cancelled() }} + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: author-photo-evidence + path: | + ${{ runner.temp }}/author-photo-response.json + ${{ runner.temp }}/chaptarr-photo-*/*.png + retention-days: 7 + if-no-files-found: warn + + build-linux: + name: build (ubuntu-latest) + needs: [linux-core, frontend] + if: ${{ always() }} + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Require the Linux Core and browser checks + shell: bash + env: + CORE_RESULT: ${{ needs.linux-core.result }} + BROWSER_RESULT: ${{ needs.frontend.outputs.browser-result }} + run: | + if [[ "$CORE_RESULT" != success || "$BROWSER_RESULT" != success ]]; then + echo "Linux Core result: $CORE_RESULT, browser result: $BROWSER_RESULT" + exit 1 + fi + + - name: Download the staged native package + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: ci-package-${{ runner.os }} + path: ./publish/ + - name: Upload artifacts uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: - name: chaptarr-${{ matrix.platform }} + name: chaptarr-linux path: ./publish/ retention-days: 7 if-no-files-found: error - postgres-migrations: + build-macos: + name: build (macos-latest) + runs-on: macos-latest + timeout-minutes: 90 + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + with: + fetch-depth: 0 + - uses: ./.github/actions/compile-ci + + - name: Test + timeout-minutes: 60 + env: + CHAPTARR_PHOTO_RESPONSE: ${{ runner.temp }}/author-photo-response.json + run: python3 build-tools/run-core-tests.py --results TestResults/core --workers 6 + + - name: Upload Core test results + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: core-tests-macos-latest + path: TestResults/core + + - name: Upload artifacts + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: chaptarr-osx + path: ./publish/ + retention-days: 7 + if-no-files-found: error + + compile-windows: + runs-on: windows-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + with: + fetch-depth: 0 + - uses: ./.github/actions/compile-ci + + - name: Pack the compiled runtime + shell: bash + run: tar -cf ci-runtime.tar _tests/net10.0 + + - name: Upload the compiled runtime + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: ci-runtime-${{ runner.os }} + path: ci-runtime.tar + if-no-files-found: error + retention-days: 30 + + - name: Stage the native package + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: ci-package-${{ runner.os }} + path: ./publish/ + retention-days: 30 + if-no-files-found: error + + windows-core: + needs: compile-windows + runs-on: windows-latest + timeout-minutes: 90 + strategy: + fail-fast: false + matrix: + part: [0, 1] + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + - uses: ./.github/actions/load-ci-runtime + + - name: Test + timeout-minutes: 60 + env: + CHAPTARR_PHOTO_RESPONSE: ${{ runner.temp }}/author-photo-response.json + run: python3 build-tools/run-core-tests.py --results TestResults/core --workers 6 --partition ${{ matrix.part }}/2 + + - name: Upload Core test results + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: windows-core-part-${{ matrix.part }} + retention-days: 30 + path: TestResults/core + + build-windows: + name: build (windows-latest) + needs: windows-core + if: ${{ always() }} + runs-on: windows-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + - name: Download Core test partitions + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + pattern: windows-core-part-* + path: core-parts + + - name: Verify and combine Core test partitions + shell: bash + run: python3 build-tools/run-core-tests.py --results TestResults/core --collect-partitions core-parts/windows-core-part-0 core-parts/windows-core-part-1 + + - name: Upload combined test results + if: ${{ !cancelled() }} + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: core-tests-windows-latest + path: TestResults/core + + - name: Require successful test workers + shell: bash + env: + WORKER_RESULT: ${{ needs.windows-core.result }} + run: test "$WORKER_RESULT" = success + + - name: Download the staged native package + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: ci-package-${{ runner.os }} + path: ./publish/ + + - name: Upload artifacts + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: chaptarr-win + path: ./publish/ + retention-days: 7 + if-no-files-found: error + + postgres-core: + needs: compile-linux + strategy: + fail-fast: false + matrix: + part: [0, 1] runs-on: ubuntu-latest timeout-minutes: 90 env: @@ -434,10 +538,7 @@ jobs: steps: - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 - - name: Setup .NET - uses: actions/setup-dotnet@67a3573c9a986a3f9c594539f4ab511d57bb3ce9 - with: - dotnet-version: 10.0.x + - uses: ./.github/actions/load-ci-runtime - name: Install PostgreSQL client shell: bash @@ -446,6 +547,7 @@ jobs: sudo sh build-tools/install-postgres-clients.sh - name: Create databases + if: matrix.part == 0 shell: bash env: PGPASSWORD: chaptarr @@ -455,32 +557,22 @@ jobs: psql -h localhost -U chaptarr -d postgres -c 'CREATE DATABASE "chaptarr-log";' psql -h localhost -U chaptarr -d postgres -c 'CREATE DATABASE "chaptarr-cache";' - - name: Restore dependencies - run: dotnet restore src/Chaptarr.NoTests.sln - - - name: Build (migrations smoke) - run: dotnet build src/Chaptarr.NoTests.sln --configuration Release --no-restore - - - name: Check Core test runner - run: python3 -m unittest discover -s build-tools -p test_run_core_tests.py - - - name: Build Core tests - run: dotnet build src/Chaptarr.Core.Test/Chaptarr.Core.Test.csproj --configuration Release - - name: Test - Core suite with PostgreSQL required timeout-minutes: 60 env: CHAPTARR_TEST_POSTGRES_CONNECTION_STRING: "Host=localhost;Port=5432;Database=postgres;Username=chaptarr;Password=chaptarr;Pooling=false" - run: python3 build-tools/run-core-tests.py --results TestResults/postgres --workers 6 + run: python3 build-tools/run-core-tests.py --results TestResults/postgres --workers 6 --partition ${{ matrix.part }}/2 - name: Upload PostgreSQL test results if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: - name: core-tests-postgres + name: postgres-core-part-${{ matrix.part }} + retention-days: 30 path: TestResults/postgres - name: Smoke - migrate up on fresh PostgreSQL + if: matrix.part == 0 shell: bash env: Chaptarr__Postgres__Host: localhost @@ -498,9 +590,15 @@ jobs: DATA_DIR="$(mktemp -d)" echo "Using data dir: $DATA_DIR" - dotnet run --project src/NzbDrone.Console/Chaptarr.Console.csproj -c Release --no-build --framework net10.0 -- \ + dotnet _output/net10.0/Chaptarr.dll \ /nobrowser "/data=$DATA_DIR" > app.log 2>&1 & pid=$! + cleanup() { + kill "$pid" >/dev/null 2>&1 || true + wait "$pid" >/dev/null 2>&1 || true + rm -rf -- "$DATA_DIR" + } + trap cleanup EXIT ready="" for i in $(seq 1 90); do @@ -511,9 +609,6 @@ jobs: sleep 1 done - kill "$pid" >/dev/null 2>&1 || true - wait "$pid" >/dev/null 2>&1 || true - if [ "$ready" != "yes" ]; then echo "Chaptarr failed to start or /ping did not become ready." tail -n 400 app.log || true @@ -521,3 +616,33 @@ jobs: fi echo "PostgreSQL migrations smoke test passed." + + postgres-migrations: + needs: postgres-core + if: ${{ always() }} + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + - name: Download Core test partitions + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + pattern: postgres-core-part-* + path: core-parts + + - name: Verify and combine Core test partitions + shell: bash + run: python3 build-tools/run-core-tests.py --results TestResults/postgres --collect-partitions core-parts/postgres-core-part-0 core-parts/postgres-core-part-1 + + - name: Upload combined test results + if: ${{ !cancelled() }} + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: core-tests-postgres + path: TestResults/postgres + + - name: Require successful test workers + shell: bash + env: + WORKER_RESULT: ${{ needs.postgres-core.result }} + run: test "$WORKER_RESULT" = success diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml index 538f5ac3f..612bea22b 100644 --- a/.github/workflows/docker-publish.yml +++ b/.github/workflows/docker-publish.yml @@ -107,11 +107,19 @@ jobs: echo 'EOF' } >> "$GITHUB_OUTPUT" + - name: Download validated release frontend + if: steps.docker-tags.outputs.has_tags == 'true' + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: release-frontend-${{ inputs.sha }} + path: ${{ runner.temp }}/release-frontend + - name: Build and push Docker image if: steps.docker-tags.outputs.has_tags == 'true' uses: docker/build-push-action@ca052bb54ab0790a636c9b5f226502c73d547a25 with: context: . + build-contexts: release-frontend=${{ runner.temp }}/release-frontend file: ./Dockerfile.cross platforms: linux/amd64,linux/arm64,linux/arm/v7 push: true @@ -120,4 +128,4 @@ jobs: org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }} org.opencontainers.image.revision=${{ inputs.sha }} cache-from: type=gha - cache-to: type=gha,mode=max + cache-to: type=gha,mode=min diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index eb6aaae5c..cb7e49c9c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -40,6 +40,8 @@ jobs: validate: needs: preflight uses: ./.github/workflows/build.yml + with: + release-frontend: true permissions: contents: read diff --git a/Dockerfile.cross b/Dockerfile.cross index 8d9972ac5..b16918095 100644 --- a/Dockerfile.cross +++ b/Dockerfile.cross @@ -3,40 +3,33 @@ # This Dockerfile uses cross-compilation to build for multiple architectures # efficiently without QEMU emulation overhead -###### node stage ###### -# Use a pinned Node image instead of curl|bash installers. +# Standalone source builds use this stage. Release CI supplies its already +# validated files as a named context, so BuildKit skips the UI build stages. FROM --platform=$BUILDPLATFORM node:24.22.2-bookworm-slim AS node RUN npm install -g yarn@1.22.22 --force -###### mp4v2 stage ###### -FROM --platform=$TARGETPLATFORM sandreas/mp4v2:2.1.1@sha256:c186cccc63b69a428be6a60359c29aff84bfacbd8597a4237038c7ccd7628a2d AS mp4v2 - -###### deps stage ###### -# Always build on the native architecture for speed -FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:10.0 AS deps +FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:10.0 AS build-frontend WORKDIR /src - -# Copy Node + Yarn from the official Node image (avoids curl|bash installers). COPY --from=node /usr/local /usr/local - -# Copy only dependency manifests so cache is preserved when code changes COPY package.json yarn.lock ./ +RUN --mount=type=cache,target=/root/.cache/yarn yarn install --frozen-lockfile +COPY . . +RUN yarn typecheck +RUN yarn build + +FROM scratch AS release-frontend +COPY --from=build-frontend /src/_output/UI/ / -# Use BuildKit cache mount so tarballs stay on host between builds -RUN --mount=type=cache,target=/root/.cache/yarn \ - yarn install --frozen-lockfile +FROM release-frontend AS ui + +###### mp4v2 stage ###### +FROM --platform=$TARGETPLATFORM sandreas/mp4v2:2.1.1@sha256:c186cccc63b69a428be6a60359c29aff84bfacbd8597a4237038c7ccd7628a2d AS mp4v2 ###### build stage ###### -FROM --platform=$BUILDPLATFORM deps AS build +FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:10.0 AS build WORKDIR /src - -# Bring in the rest of the project *after* deps are installed COPY . . -# Front‑end build (architecture-independent) -RUN yarn typecheck -RUN yarn build - # Build for the target architecture only. When building multi-platform images with Buildx, # Docker runs this Dockerfile once per target platform, so producing *all* arch outputs here # just bloats every final image layer. @@ -52,17 +45,16 @@ RUN --mount=type=cache,target=/root/.nuget/packages,sharing=locked \ dotnet restore src/Chaptarr.NoTests.sln -r "$RUNTIME_ID"; \ dotnet publish src/NzbDrone.Console/Chaptarr.Console.csproj -c Release -f net10.0 -r "$RUNTIME_ID" --self-contained false -o /app --no-restore /p:EnableWindowsTargeting=true /p:RunAnalyzersDuringBuild=false /p:RunCodeAnalysis=false /p:PublishSingleFile=false -# Copy UI output to app directory -RUN mkdir -p /app/UI && cp -r _output/UI/* /app/UI/ - ###### runtime stage ###### # This stage runs on the target platform FROM --platform=$TARGETPLATFORM mcr.microsoft.com/dotnet/aspnet:10.0 COPY build-tools/install-postgres-clients.sh /tmp/install-postgres-clients.sh +ARG TARGETARCH +ARG TARGETVARIANT # Install runtime dependencies (these are architecture-specific) -RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \ - --mount=type=cache,target=/var/lib/apt,sharing=locked \ +RUN --mount=type=cache,id=apt-cache-${TARGETARCH}-${TARGETVARIANT},target=/var/cache/apt,sharing=locked \ + --mount=type=cache,id=apt-lists-${TARGETARCH}-${TARGETVARIANT},target=/var/lib/apt,sharing=locked \ set -eux; \ apt-get update; \ apt-get install -y --no-install-recommends \ @@ -113,6 +105,8 @@ RUN chmod +x /entrypoint.sh WORKDIR /app COPY --from=build /app /app +COPY --from=ui / /app/UI/ +RUN test -s /app/UI/index.html # Set app permissions at build time RUN chmod -R 755 /app diff --git a/build-tools/run-core-tests.py b/build-tools/run-core-tests.py index fc3478ba5..d5c001e63 100644 --- a/build-tools/run-core-tests.py +++ b/build-tools/run-core-tests.py @@ -240,6 +240,75 @@ def isolated_runtime(assembly, directory, workspace): return runtime / assembly.name, work, environment +def partition_arg(value): + try: + index, count = map(int, value.split("/")) + except ValueError: + raise argparse.ArgumentTypeError("Expected a zero-based INDEX/COUNT") from None + if not 0 <= index < count: + raise argparse.ArgumentTypeError("Partition index must be between zero and COUNT - 1") + return index, count + + +def write_report(output, fixtures, results, baseline, summary): + try: + summary["coverage"] = verify_coverage(fixtures, results, baseline) + if summary["postgresRequired"] and any(case["outcome"] == "NotExecuted" and "postgres" in case["reason"].lower() for case in results): + raise ValueError("Required PostgreSQL coverage was skipped") + except ValueError as error: + summary["coverageError"] = str(error) + write_json(output / "summary.json", summary) + write_json(output / "case-results.json", results) + measured = collections.defaultdict(float) + for case in results: + measured[fixture_name(case["fixture"])] += case["seconds"] + write_json(output / "fixture-times.json", {name: round(seconds, 6) for name, seconds in sorted(measured.items())}) + print(json.dumps(summary, indent=2)) + return int("coverageError" in summary or + any(result["exitCode"] or "coverageError" in result for result in summary["shards"]) or + any(case["outcome"] not in ("Passed", "NotExecuted") for case in results)) + + +def collect_partitions(paths, output, baseline=None): + def read(directory, name): + return json.loads((directory / name).read_text(encoding="utf-8")) + + plan = read(paths[0], "plan.json") + groups = plan["groups"] + fixtures = plan["fixtures"] + if collections.Counter(name for group in groups for name in group) != collections.Counter(fixtures.keys()): + raise ValueError("The shared plan does not assign every fixture exactly once") + + parts = [read(path, "summary.json") for path in paths] + first = parts[0] + keys = ("assemblySha256", "workers", "postgresRequired") + summary = {key: first[key] for key in keys} + combined = {} + results = [] + for index, (path, part) in enumerate(zip(paths, parts)): + if (part["partition"] != [index, len(paths)] or read(path, "plan.json") != plan or + any(part[key] != first[key] for key in keys) or "coverageError" in part): + raise ValueError(f"Partition {path} is missing, failed, or used a different test plan or environment") + assigned = range(index, len(groups), len(paths)) + if len(part["shards"]) != len(assigned): + raise ValueError(f"Partition {path} did not report every assigned shard") + for shard, result in zip(assigned, part["shards"]): + source = path / f"shard-{shard}" + cases = read_results(source / "results.trx") + verify_coverage({name: fixtures[name] for name in groups[shard]}, cases) + results.extend(cases) + combined[shard] = result + + for shard in range(len(groups)): + source = paths[shard % len(paths)] / f"shard-{shard}" + shutil.copytree(source, output / source.name) + for name in ("discovery.runsettings", "discovery.log", "discovery.xml", "plan.json"): + shutil.copyfile(paths[0] / name, output / name) + times = [part["seconds"] for part in parts] + summary.update(seconds=max(times), partitionSeconds=times, shards=[combined[i] for i in range(len(groups))]) + return write_report(output, fixtures, results, baseline, summary) + + def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--assembly", type=Path, default=Path("_tests/net10.0/Chaptarr.Core.Test.dll")) @@ -251,7 +320,22 @@ def main(): help="Measured fixture durations used to balance the processes") parser.add_argument("--fixture", action="append", help="Exact fixture name for a targeted check") parser.add_argument("--uses", help="Run fixtures using comma-separated symbols, including shared test-helper consumers") + distribution = parser.add_mutually_exclusive_group() + distribution.add_argument("--partition", type=partition_arg, help="Run one zero-based INDEX/COUNT share of the worker groups") + distribution.add_argument("--collect-partitions", type=Path, nargs="+", help="Verify and combine all partition reports in order") args = parser.parse_args() + if args.collect_partitions: + if args.fixture or args.uses is not None: + parser.error("Partition collection verifies the whole shared plan and does not accept fixture selectors") + args.results.mkdir(parents=True, exist_ok=True) + try: + baseline = read_results(args.baseline) if args.baseline else None + return collect_partitions(args.collect_partitions, args.results, baseline) + except (OSError, KeyError, ValueError, ET.ParseError) as error: + for index, path in enumerate(args.collect_partitions): + if path.is_dir(): + shutil.copytree(path, args.results / f"partition-{index}", dirs_exist_ok=True) + parser.exit(1, f"Unable to combine Core test partitions: {error}\n") repo = Path(__file__).resolve().parents[1] test_source = repo / "src/Chaptarr.Core.Test" symbols = None @@ -311,6 +395,15 @@ def main(): baseline = [case for case in baseline or [] if fixture_name(case["fixture"]) in fixtures] if baseline else None groups = partition(fixtures, args.workers, timings) write_json(output / "plan.json", {"fixtures": fixtures, "groups": groups}) + indexes = range(len(groups)) + if args.partition: + index, count = args.partition + if count > len(groups): + parser.error("Cannot assign a partition to an empty set of worker groups") + indexes = range(index, len(groups), count) + fixtures = {name: fixtures[name] for shard in indexes for name in groups[shard]} + baseline = [case for case in baseline if fixture_name(case["fixture"]) in fixtures] if baseline is not None else None + summary["partition"] = args.partition def execute(index, group): with tempfile.TemporaryDirectory(prefix=f"shard-{index}-", dir=scratch) as directory, tempfile.TemporaryDirectory(prefix="chaptarr-test-work-") as workspace: @@ -334,27 +427,12 @@ def execute(index, group): print(f"Shard {index}: {result['seconds']:.1f}s, {dict(collections.Counter(case['outcome'] for case in results))}, exit {result['exitCode']}", flush=True) return result, results - with concurrent.futures.ThreadPoolExecutor(max_workers=args.workers) as pool: - futures = [pool.submit(execute, i, group) for i, group in enumerate(groups)] + with concurrent.futures.ThreadPoolExecutor(max_workers=len(indexes)) as pool: + futures = [pool.submit(execute, i, groups[i]) for i in indexes] completed = [future.result() for future in futures] results = [case for _, cases in completed for case in cases] summary.update(seconds=time.monotonic() - started, shards=[result for result, _ in completed]) - try: - summary["coverage"] = verify_coverage(fixtures, results, baseline) - if postgres_required and any(case["outcome"] == "NotExecuted" and "postgres" in case["reason"].lower() for case in results): - raise ValueError("Required PostgreSQL coverage was skipped") - except ValueError as error: - summary["coverageError"] = str(error) - write_json(output / "summary.json", summary) - write_json(output / "case-results.json", results) - measured = collections.defaultdict(float) - for case in results: - measured[fixture_name(case["fixture"])] += case["seconds"] - write_json(output / "fixture-times.json", {name: round(seconds, 6) for name, seconds in sorted(measured.items())}) - print(json.dumps(summary, indent=2)) - if "coverageError" in summary or any(result["exitCode"] or "coverageError" in result for result, _ in completed) or any(case["outcome"] not in ("Passed", "NotExecuted") for case in results): - return 1 - return 0 + return write_report(output, fixtures, results, baseline, summary) if __name__ == "__main__": diff --git a/build-tools/test_run_core_tests.py b/build-tools/test_run_core_tests.py index d25098229..d102e7342 100644 --- a/build-tools/test_run_core_tests.py +++ b/build-tools/test_run_core_tests.py @@ -1,4 +1,7 @@ +import contextlib import importlib.util +import io +import json import os import subprocess import sys @@ -230,6 +233,62 @@ def test_new_skip_cannot_replace_a_previously_passing_test(self): with self.assertRaisesRegex(ValueError, "Previously passing"): runner.verify_coverage(fixtures, [dict(passed, outcome="NotExecuted")], [passed]) + @staticmethod + def partition_reports(root, second_outcome="Passed", second_count=1): + fixtures = {"N.A": fixture("N.A"), "N.B": fixture("N.B", second_count)} + plan = {"fixtures": fixtures, "groups": [["N.A"], ["N.B"]]} + paths = [root / f"part-{index}" for index in range(2)] + summaries = [] + for index, path in enumerate(paths): + runtime = path / f"shard-{index}" + runtime.mkdir(parents=True) + name = plan["groups"][index][0] + runner.write_json(path / "plan.json", plan) + summary = {"assemblySha256": "test-dll", "workers": 2, "partition": [index, 2], + "postgresRequired": True, "seconds": index + 1, "shards": [{"exitCode": 0}]} + summaries.append(summary) + runner.write_json(path / "summary.json", summary) + outcome = second_outcome if index == 1 else "Passed" + (runtime / "results.trx").write_text(f''' + + + ''', encoding="utf-8") + for filename in ("discovery.runsettings", "discovery.log", "discovery.xml"): + (path / filename).touch() + + output = root / "combined" + output.mkdir() + return paths, summaries, output + + def test_collect_partitions_requires_the_same_complete_suite(self): + with tempfile.TemporaryDirectory() as directory: + paths, summaries, output = self.partition_reports(Path(directory)) + with contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(runner.collect_partitions(paths, output), 0) + self.assertEqual(json.loads((output / "summary.json").read_text())["coverage"]["outcomes"], {"Passed": 2}) + + for incomplete in (paths[:1], paths[::-1]): + with self.subTest(incomplete=incomplete), self.assertRaisesRegex(ValueError, "different test plan or environment"): + runner.collect_partitions(incomplete, output) + runner.write_json(paths[1] / "summary.json", dict(summaries[1], postgresRequired=False)) + with self.assertRaisesRegex(ValueError, "different test plan or environment"): + runner.collect_partitions(paths, output) + + + def test_collect_partitions_rejects_a_missing_case_in_shard_trx(self): + with tempfile.TemporaryDirectory() as directory: + # Valid metadata reports both shards successful, but N.B's TRX omits test_1. + paths, _, output = self.partition_reports(Path(directory), second_count=2) + with contextlib.redirect_stdout(io.StringIO()), self.assertRaisesRegex(ValueError, "Test coverage changed: missing=.*N.B.*test_1"): + runner.collect_partitions(paths, output) + + def test_collect_partitions_rejects_a_failed_case_despite_successful_shards(self): + with tempfile.TemporaryDirectory() as directory: + paths, _, output = self.partition_reports(Path(directory), second_outcome="Failed") + with contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(runner.collect_partitions(paths, output), 1) + self.assertEqual(json.loads((output / "summary.json").read_text())["coverage"]["outcomes"], {"Passed": 1, "Failed": 1}) + if __name__ == "__main__": unittest.main() diff --git a/frontend/build/check-author-search.cjs b/frontend/build/check-author-search.cjs index b2e6dc3a6..0eda95cf2 100644 --- a/frontend/build/check-author-search.cjs +++ b/frontend/build/check-author-search.cjs @@ -616,20 +616,7 @@ async function checkModalReopenAndZeroFallback(page, seriesRequests, bookRequest assert.deepEqual(failures, [], 'New modal openings reuse root defaults; existing positive metadata fallback excludes zero'); } -(async() => { - const compiler = webpack(config); - await new Promise((resolve, reject) => compiler.run((error, stats) => { - compiler.close(() => {}); - if (error || stats.hasErrors()) { - reject(error || new Error(stats.toString({ all: false, errors: true }))); - } else { - console.log('Browser fixture webpack compilation completed.'); - resolve(); - } - })); - - console.log('Launching Chromium for the mocked browser lifecycle.'); - const browser = await chromium.launch(); +async function checkAuthorScenario(browser, syncOnly) { const unloadStops = []; const server = http.createServer((request, response) => { const url = new URL(request.url, 'http://localhost'); @@ -642,11 +629,11 @@ async function checkModalReopenAndZeroFallback(page, seriesRequests, bookRequest response.writeHead(404); response.end(); }); + const context = await browser.newContext(); try { await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); const css = fs.readdirSync(path.join(output, 'Content')).find((name) => name.endsWith('.css')); const strings = JSON.parse(fs.readFileSync(path.join(root, 'src/NzbDrone.Core/Localization/Core/en.json'))); - const context = await browser.newContext(); const page = await context.newPage(); const errors = []; const releaseRequests = []; @@ -856,7 +843,7 @@ async function checkModalReopenAndZeroFallback(page, seriesRequests, bookRequest return route.fulfill({ path: path.join(output, 'Content', css), contentType: 'text/css' }); } if (pathname !== '/') { - if (process.env.CHAPTARR_SYNC_ONLY) { + if (syncOnly) { console.error(`Unmatched sync fixture request: ${request.method()} ${url.pathname}${url.search}`); } return route.fulfill({ status: 404, body: '' }); @@ -896,7 +883,7 @@ async function checkModalReopenAndZeroFallback(page, seriesRequests, bookRequest assert.deepEqual(errors, []); return; } - if (process.env.CHAPTARR_SYNC_ONLY) { + if (syncOnly) { await checkAuthorSync(page, { importRequests, checkAddAuthorPayloads, selectAddAuthorMonitor, setAddAuthorCheckbox, strings, beforeInjectedFailure: () => assert.deepEqual(errors, [], 'Normal form interactions have zero browser console or page errors'), @@ -1629,13 +1616,45 @@ async function checkModalReopenAndZeroFallback(page, seriesRequests, bookRequest assert.deepEqual(errors, []); console.log('Author-search browser check passed: confirmation and media boundaries, scoped grabs, incremental/final merges, explicit Stop acceptance, retry, modal isolation, terminal cancellation, and unmount cleanup.'); + } finally { + try { + await context.close(); + } finally { + await new Promise((resolve) => server.close(resolve)); + } + } +} + +(async() => { + const compiler = webpack(config); + await new Promise((resolve, reject) => compiler.run((error, stats) => { + compiler.close(() => {}); + if (error || stats.hasErrors()) { + reject(error || new Error(stats.toString({ all: false, errors: true }))); + } else { + console.log('Browser fixture webpack compilation completed.'); + resolve(); + } + })); + + console.log('Launching Chromium for the mocked browser lifecycle.'); + const browser = await chromium.launch(); + try { + const modes = process.argv.includes('--with-sync') ? [false, true] : [Boolean(process.env.CHAPTARR_SYNC_ONLY)]; + for (const syncOnly of modes) { + try { + await checkAuthorScenario(browser, syncOnly); + } catch (error) { + console.error(`Author ${syncOnly ? 'sync' : 'search'} browser checks failed`, error); + process.exitCode = 1; + } + } } finally { await browser.close(); - await new Promise((resolve) => server.close(resolve)); - fs.rmSync(output, { recursive: true, force: true }); } })().catch((error) => { - fs.rmSync(output, { recursive: true, force: true }); console.error(error); process.exitCode = 1; +}).finally(() => { + fs.rmSync(output, { recursive: true, force: true }); }); diff --git a/src/Chaptarr.Core.Test/Books/PendingAuthorImportRetryFixture.cs b/src/Chaptarr.Core.Test/Books/PendingAuthorImportRetryFixture.cs index e720d4450..dc4fdfacd 100644 --- a/src/Chaptarr.Core.Test/Books/PendingAuthorImportRetryFixture.cs +++ b/src/Chaptarr.Core.Test/Books/PendingAuthorImportRetryFixture.cs @@ -1111,31 +1111,6 @@ public async Task concurrent_requests_should_retry_the_merge_without_losing_eith Assert.That(repositoryProxy.Active.Version, Is.EqualTo(6)); } - [Test] - [Timeout(1000)] - public void retry_should_stop_if_the_pending_row_became_inactive_during_the_update() - { - var repository = DispatchProxy.Create(); - var repositoryProxy = (RepositoryProxy)repository; - repositoryProxy.TryUpdate = (_, _) => false; - var subject = new PendingAuthorImportService( - repository, - DispatchProxy.Create(), - new RecordingEventAggregator(), - LogManager.GetCurrentClassLogger()); - var item = new PendingAuthorImport - { - Id = 42, - ProviderId = "gr:42", - AudiobookStatus = PendingImportStatus.Pending, - OverallStatus = PendingImportStatus.Pending - }; - - subject.ScheduleRetry(item, "not ready"); - - Assert.That(repositoryProxy.Updated, Is.Null); - } - [Test] public void cancel_should_survive_a_stale_processing_retry() { From a5399a1971ac23134958bab69b342c66392bd288 Mon Sep 17 00:00:00 2001 From: robertlordhood <204023072+robertlordhood@users.noreply.github.com> Date: Sat, 5 Dec 2026 20:01:50 +0000 Subject: [PATCH 2/3] Repair PostgreSQL ID counters before migrations Copying rows into PostgreSQL with their existing IDs, as when moving a SQLite database over, can leave a table's ID counter behind its highest row when the copy doesn't also move the counter. Every later insert into that table then fails with a duplicate key, as reported for Editions and ScheduledTasks. Before migrations run on a PostgreSQL database, including a staged restore, Chaptarr now checks the counter behind each table's Id primary key and moves a counter that has fallen behind forward to the next free ID. Rows are never renumbered and a counter is never moved back. One query reads every counter, with a fallback to one table at a time if that query fails. A repair locks the table and its counter, reads them again under the lock and commits table by table. Lock waits are limited to two seconds and the whole pass to thirty, and a repair whose client stops responding releases its locks after twenty seconds. Counters that can't safely be changed, such as cached or cycling ones, are skipped with a warning. Failures are logged and retried at the next start, and startup continues either way. The pending author import retry now treats a PostgreSQL unique violation as a race with another request only when it hits its own active-row constraint, so a duplicate key from a stale counter is reported instead of retried. --- .../BackupServiceCoverageFixture.Postgres.cs | 17 + ...PendingAuthorImportRetryConflictFixture.cs | 63 ++ .../PostgresSequenceRepairFixture.cs | 814 ++++++++++++++++++ .../Services/PendingAuthorImportService.cs | 3 +- .../Framework/MigrationController.cs | 5 + .../Datastore/PostgresSequenceRepair.cs | 273 ++++++ 6 files changed, 1173 insertions(+), 2 deletions(-) create mode 100644 src/Chaptarr.Core.Test/Datastore/PostgresSequenceRepairFixture.cs create mode 100644 src/NzbDrone.Core/Datastore/PostgresSequenceRepair.cs diff --git a/src/Chaptarr.Core.Test/Backup/BackupServiceCoverageFixture.Postgres.cs b/src/Chaptarr.Core.Test/Backup/BackupServiceCoverageFixture.Postgres.cs index 052626f8a..985064288 100644 --- a/src/Chaptarr.Core.Test/Backup/BackupServiceCoverageFixture.Postgres.cs +++ b/src/Chaptarr.Core.Test/Backup/BackupServiceCoverageFixture.Postgres.cs @@ -319,6 +319,12 @@ public void postgres_full_restore_should_preserve_every_store_and_recover_the_or using var target = new PostgresStores("target"); var sourceFolders = new AppFolders(Path.Combine(_root, "pg-source")); var targetFolders = new AppFolders(Path.Combine(_root, "pg-target")); + if (outcome == "commit") + { + using var connection = PostgresBackup.Open(source.Connections["chaptarr.dump"]); + connection.Execute(@"SELECT setval(pg_get_serial_sequence('""BackupProbe""', 'Id'), 1, false)"); + } + var archive = PostgresArchive(source, sourceFolders); var artifactFolder = Environment.GetEnvironmentVariable("CHAPTARR_BACKUP_TEST_ARTIFACTS"); if (outcome == "commit" && !string.IsNullOrWhiteSpace(artifactFolder)) @@ -327,6 +333,12 @@ public void postgres_full_restore_should_preserve_every_store_and_recover_the_or File.Copy(archive, Path.Combine(artifactFolder, "postgres-round-trip.zip"), true); } var expected = source.Snapshot(); + if (outcome == "commit") + { + Assert.That(expected["chaptarr.dump"]["sequence:BackupProbe_Id_seq"], Is.EqualTo(new[] { "1:false" })); + expected["chaptarr.dump"]["sequence:BackupProbe_Id_seq"] = new[] { "3:false" }; + } + var original = target.Snapshot(); SeedConfig(targetFolders); File.WriteAllText(targetFolders.GetConfigPath(), "target-value"); @@ -349,6 +361,11 @@ public void postgres_full_restore_should_preserve_every_store_and_recover_the_or Assert.That(config.Root.Element("BackupCoverageFutureKey").Value, Is.EqualTo("unknown value & Unicode Å")); if (outcome == "commit") { + using (var connection = PostgresBackup.Open(target.Connections["chaptarr.dump"])) + { + Assert.That(connection.ExecuteScalar(@"INSERT INTO ""BackupProbe"" DEFAULT VALUES RETURNING ""Id"""), Is.EqualTo(3)); + } + restoration.Commit(); Assert.That(Directory.Exists(targetFolders.GetDatabaseRestoreBundle()), Is.False); } diff --git a/src/Chaptarr.Core.Test/Books/PendingAuthorImportRetryConflictFixture.cs b/src/Chaptarr.Core.Test/Books/PendingAuthorImportRetryConflictFixture.cs index c619d6db4..29d1d2c8e 100644 --- a/src/Chaptarr.Core.Test/Books/PendingAuthorImportRetryConflictFixture.cs +++ b/src/Chaptarr.Core.Test/Books/PendingAuthorImportRetryConflictFixture.cs @@ -3,9 +3,11 @@ using Chaptarr.Api.V1.PendingImport; using Chaptarr.Core.Test.Common; using Chaptarr.Http.ErrorManagement; +using Dapper; using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Http; using NLog; +using Npgsql; using NUnit.Framework; using NzbDrone.Core.Books; using NzbDrone.Core.Books.Services; @@ -73,6 +75,67 @@ public void unrelated_repository_failure_should_not_be_mapped_to_active_provider Assert.That(Assert.Throws(() => service.RetryNow(1)), Is.SameAs(failure)); } + [Test] + public void enqueue_primary_key_collision_propagates_without_retrying_an_unrelated_race() + { + DualDatabaseFixture.Run(true, database => + { + var events = InterfaceProxy.Proxy((_, _) => null); + var repository = new PendingAuthorImportRepository(database, events); + var stored = repository.Insert(Row(PendingImportStatus.Failed)); + using var connection = database.OpenConnection(); + connection.Execute("SELECT setval(pg_get_serial_sequence('\"PendingAuthorImport\"', 'Id'), @id, false)", new { id = stored.Id }); + var service = new PendingAuthorImportService(repository, NoLocalAuthors(), events, LogManager.GetCurrentClassLogger()); + + var error = Assert.Throws(() => service.EnqueueAsync("gr:9002", new MonitoringConfig { CreateAudiobook = true }, "UserInterface").GetAwaiter().GetResult()); + + Assert.That(error.SqlState, Is.EqualTo(PostgresErrorCodes.UniqueViolation)); + Assert.That(error.ConstraintName, Is.Not.EqualTo("UX_PendingAuthorImport_Active")); + Assert.That(repository.GetActiveByProviderId("gr:9002"), Is.Null); + Assert.That(repository.Find(stored.Id).ProviderId, Is.EqualTo(stored.ProviderId)); + Assert.That(connection.ExecuteScalar("SELECT COUNT(*) FROM \"PendingAuthorImport\""), Is.EqualTo(1)); + }); + } + + [TestCase(false)] + [TestCase(true)] + public void enqueue_active_provider_insert_race_still_merges_both_media_requests(bool postgres) + { + DualDatabaseFixture.Run(postgres, database => + { + var events = InterfaceProxy.Proxy((_, _) => null); + var repository = new PendingAuthorImportRepository(database, events); + var existing = repository.Insert(Row(PendingImportStatus.Pending)); + var firstLookup = true; + var insertAttempts = 0; + var racing = InterfaceProxy.Proxy((method, args) => + { + if (method.Name == nameof(IPendingAuthorImportRepository.GetActiveByProviderId)) + { + if (firstLookup) { firstLookup = false; return null; } + return repository.GetActiveByProviderId((string)args[0]); + } + if (method.Name == nameof(IPendingAuthorImportRepository.Insert)) + { + insertAttempts++; + return repository.Insert((PendingAuthorImport)args[0]); + } + return method.Invoke(repository, args); + }); + var service = new PendingAuthorImportService(racing, NoLocalAuthors(), events, LogManager.GetCurrentClassLogger()); + + var id = service.EnqueueAsync(existing.ProviderId, new MonitoringConfig { CreateEbook = true }, "UserInterface").GetAwaiter().GetResult(); + + Assert.That(insertAttempts, Is.EqualTo(1), "The first lookup must miss the competing active row, producing a real unique-index error."); + Assert.That(id, Is.EqualTo(existing.Id)); + var saved = repository.Find(id); + Assert.That(saved.AudiobookStatus, Is.EqualTo(PendingImportStatus.Pending)); + Assert.That(saved.EbookStatus, Is.EqualTo(PendingImportStatus.Pending)); + using var connection = database.OpenConnection(); + Assert.That(connection.ExecuteScalar("SELECT COUNT(*) FROM \"PendingAuthorImport\""), Is.EqualTo(1)); + }); + } + private static IAuthorService NoLocalAuthors() => InterfaceProxy.Proxy((method, _) => method.Name == nameof(IAuthorService.FindByProviderId) ? null : throw new NotSupportedException(method.Name)); diff --git a/src/Chaptarr.Core.Test/Datastore/PostgresSequenceRepairFixture.cs b/src/Chaptarr.Core.Test/Datastore/PostgresSequenceRepairFixture.cs new file mode 100644 index 000000000..1b2a89cdc --- /dev/null +++ b/src/Chaptarr.Core.Test/Datastore/PostgresSequenceRepairFixture.cs @@ -0,0 +1,814 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Diagnostics; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Chaptarr.Core.Test.Common; +using Dapper; +using NLog; +using NLog.Config; +using NLog.Targets; +using Npgsql; +using NUnit.Framework; +using NzbDrone.Core.Datastore; +using NzbDrone.Core.Datastore.Migration.Framework; + +namespace Chaptarr.Core.Test.Datastore +{ + [TestFixture] + [NonParallelizable] + public class PostgresSequenceRepairFixture + { + private static readonly Logger Logger = LogManager.GetLogger(nameof(PostgresSequenceRepairFixture)); + + private static void Repair(IDbConnection connection) => PostgresSequenceRepair.Run(connection.ConnectionString, Logger); + + private static string[] RepairWarnings(IDbConnection connection) + { + var target = new MemoryTarget { Layout = "${message}" }; + using var factory = new LogFactory(); + var config = new LoggingConfiguration(factory); + config.AddRule(LogLevel.Warn, LogLevel.Fatal, target); + factory.Configuration = config; + PostgresSequenceRepair.Run(connection.ConnectionString, factory.GetLogger("CounterFixture")); + return target.Logs.ToArray(); + } + + private sealed class CaptureTarget : Target + { + public List Events { get; } = new(); + public Action OnWrite { get; init; } + + protected override void Write(LogEventInfo logEvent) + { + Events.Add(logEvent); + OnWrite?.Invoke(logEvent); + } + } + + private static LogEventInfo[] Capture(Action action, Action onWrite = null) + { + using var target = new CaptureTarget { OnWrite = onWrite }; + var previous = LogManager.Configuration; + var config = previous ?? new LoggingConfiguration(); + var rule = new LoggingRule("*", LogLevel.Debug, target); + config.LoggingRules.Insert(0, rule); + LogManager.Configuration = config; + try + { + action(); + return target.Events.ToArray(); + } + finally + { + config.LoggingRules.Remove(rule); + LogManager.Configuration = previous; + LogManager.ReconfigExistingLoggers(); + } + } + + private static void Startup(string connectionString, MigrationType type = MigrationType.Main, bool postgres = true, long? version = null) + { + var info = new DatabaseConnectionInfo(postgres ? DatabaseType.PostgreSQL : DatabaseType.SQLite, connectionString); + var factory = new DbFactory(new MigrationController(Logger, null), + InterfaceProxy.Proxy((_, _) => info), null); + Assert.That(factory.Create(new MigrationContext(type, version)), Is.Not.Null); + } + + private static void InsertRepairPeers(IDbConnection connection) + { + connection.Execute(@"INSERT INTO ""Config"" (""Id"", ""Key"", ""Value"") OVERRIDING SYSTEM VALUE VALUES (10000, 'counterfixture', 'retained'); + INSERT INTO ""Tags"" (""Id"", ""Label"") OVERRIDING SYSTEM VALUE VALUES (10000, 'counterfixture')"); + SetCounter(connection, "Config", 1, false); + SetCounter(connection, "Tags", 1, false); + } + + private static void AssertError(LogEventInfo[] logs, string table, string state) + { + var errors = logs.Where(e => e.Level == LogLevel.Error).ToArray(); + Assert.That(errors, Has.Length.EqualTo(1)); + Assert.That(errors[0].FormattedMessage, Is.EqualTo( + $"PostgreSQL ID counter repair failed for public.\"{table}\" (SQLSTATE {state}); left unchanged; retried at next start. Startup will continue.")); + } + + private static void AssertPeersRepaired(IDbConnection connection) + { + Assert.That(State(connection, "Config"), Is.EqualTo("10001:false")); + Assert.That(State(connection, "Tags"), Is.EqualTo("10001:false")); + } + + private static string Sequence(IDbConnection connection, string table) => + connection.ExecuteScalar("SELECT pg_get_serial_sequence(@table, 'Id')", new { table = $"\"{table}\"" }); + + private static string State(IDbConnection connection, string table) => + connection.ExecuteScalar($"SELECT last_value::text || ':' || is_called::text FROM {Sequence(connection, table)}"); + + private static void SetCounter(IDbConnection connection, string table, long value, bool called) => + connection.Execute("SELECT setval(@sequence::regclass, @value, @called)", new { sequence = Sequence(connection, table), value, called }); + + private static void InsertTask(IDbConnection connection, int id) => connection.Execute(@" + INSERT INTO ""ScheduledTasks"" (""Id"", ""TypeName"", ""Interval"", ""LastExecution"", ""LastStartTime"") + OVERRIDING SYSTEM VALUE VALUES (@id, 'Counter fixture', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)", new { id }); + + private static int InsertTask(IDbConnection connection) => connection.ExecuteScalar(@" + INSERT INTO ""ScheduledTasks"" (""TypeName"", ""Interval"", ""LastExecution"", ""LastStartTime"") + VALUES ('New counter fixture', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) RETURNING ""Id"""); + + [TestCase(1, false)] + [TestCase(100, false)] + [TestCase(99, true)] + public void startup_repairs_behind_or_uncalled_equal_counter_without_changing_rows(long last, bool called) + { + DualDatabaseFixture.Run(true, database => + { + using var connection = database.OpenConnection(); + InsertTask(connection, 1); + InsertTask(connection, 100); + SetCounter(connection, "ScheduledTasks", last, called); + var before = connection.Query("SELECT row_to_json(t)::text FROM \"ScheduledTasks\" t ORDER BY \"Id\"").ToArray(); + Startup(connection.ConnectionString); + Assert.That(connection.Query("SELECT row_to_json(t)::text FROM \"ScheduledTasks\" t ORDER BY \"Id\""), Is.EqualTo(before)); + Assert.That(InsertTask(connection), Is.EqualTo(101)); + }); + } + + [Test] + public void released_postgres_schema_with_a_behind_alias_counter_upgrades_through_migration_111() + { + DualDatabaseFixture.Run(true, database => + { + using var connection = database.OpenConnection(); + connection.Execute(@"INSERT INTO ""Authors"" (""Id"", ""Name"", ""CleanName"", ""Path"", ""Monitored"", ""Added"") + OVERRIDING SYSTEM VALUE VALUES (100, 'Counter Author', 'counter author', '/fixture', true, CURRENT_TIMESTAMP); + INSERT INTO ""Books"" (""Id"", ""AuthorId"", ""Title"", ""CleanTitle"", ""MediaType"", ""AnyEditionOk"", ""Added"") + OVERRIDING SYSTEM VALUE VALUES (200, 100, 'Counter Book', 'counter book', 0, true, CURRENT_TIMESTAMP); + INSERT INTO ""Editions"" (""Id"", ""BookId"", ""Title"", ""Monitored"", ""Asin"") + OVERRIDING SYSTEM VALUE VALUES (300, 200, 'Counter Edition', true, 'B000000002'); + INSERT INTO ""ProviderAliasIndex"" (""Id"", ""EntityType"", ""EntityId"", ""Scope"", ""Provider"", ""NormalizedProviderId"", ""CreatedAt"", ""UpdatedAt"") + OVERRIDING SYSTEM VALUE VALUES (1, 'Edition', 300, 'edition', 'az', 'B000000001', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP);"); + SetCounter(connection, "ProviderAliasIndex", 1, false); + // With this planner setting the old literal 'Id' inventory fails on VersionInfo. + var config = new NpgsqlConnectionStringBuilder(connection.ConnectionString) { Options = "-c enable_nestloop=off" }; + + Startup(config.ConnectionString, version: 111); + + Assert.That(connection.ExecuteScalar("SELECT MAX(\"Version\") FROM \"VersionInfo\""), Is.EqualTo(111)); + Assert.That(connection.ExecuteScalar(@"SELECT ""Id"" FROM ""ProviderAliasIndex"" WHERE ""NormalizedProviderId"" = 'B000000001'"), Is.EqualTo(1)); + Assert.That(connection.ExecuteScalar(@"SELECT ""Id"" FROM ""ProviderAliasIndex"" WHERE ""NormalizedProviderId"" = 'B000000002'"), Is.GreaterThan(1)); + }, desiredVersion: 107); + } + + [TestCase(false, MigrationType.Log)] + [TestCase(true, MigrationType.Log)] + [TestCase(false, MigrationType.Cache)] + [TestCase(true, MigrationType.Cache)] + public void log_and_cache_startup_preserve_rows_and_allow_the_next_insert(bool postgres, MigrationType type) + { + DualDatabaseFixture.Run(postgres, database => + { + using var connection = database.OpenConnection(); + var table = type == MigrationType.Log ? "Logs" : "HttpResponse"; + var columns = type == MigrationType.Log ? "\"Message\",\"Time\",\"Logger\",\"Level\"" + : "\"Url\",\"LastRefresh\",\"Expiry\",\"Value\",\"StatusCode\""; + var values = type == MigrationType.Log ? "'retained',CURRENT_TIMESTAMP,'CounterFixture','Warn'" + : "'https://counter.invalid/',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,'retained',200"; + var identity = postgres ? "OVERRIDING SYSTEM VALUE" : string.Empty; + connection.Execute($"INSERT INTO \"{table}\" (\"Id\",{columns}) {identity} VALUES (100,{values})"); + if (postgres) SetCounter(connection, table, 1, false); + Startup(connection.ConnectionString, type, postgres); + Assert.That(connection.ExecuteScalar($"SELECT COUNT(*) FROM \"{table}\""), Is.EqualTo(1)); + var valueColumn = type == MigrationType.Log ? "Message" : "Value"; + Assert.That(connection.ExecuteScalar($"SELECT \"{valueColumn}\" FROM \"{table}\" WHERE \"Id\"=100"), Is.EqualTo("retained")); + if (postgres) Assert.That(State(connection, table), Is.EqualTo("101:false")); + Assert.That(connection.ExecuteScalar($"INSERT INTO \"{table}\" ({columns}) VALUES ({values}) RETURNING \"Id\""), Is.EqualTo(101)); + }, migrationType: type); + } + + [TestCase(100, true)] + [TestCase(200, false)] + [TestCase(200, true)] + public void healthy_or_ahead_counters_and_repeated_startup_are_exact_no_ops(long last, bool called) + { + DualDatabaseFixture.Run(true, database => + { + using var connection = database.OpenConnection(); + InsertTask(connection, 100); + SetCounter(connection, "ScheduledTasks", last, called); + var state = State(connection, "ScheduledTasks"); + var filenode = connection.ExecuteScalar("SELECT pg_relation_filenode(@sequence::regclass)::bigint", new { sequence = Sequence(connection, "ScheduledTasks") }); + Repair(connection); + Repair(connection); + Assert.That(State(connection, "ScheduledTasks"), Is.EqualTo(state)); + Assert.That(connection.ExecuteScalar("SELECT pg_relation_filenode(@sequence::regclass)::bigint", new { sequence = Sequence(connection, "ScheduledTasks") }), Is.EqualTo(filenode)); + }); + } + + [Test] + public void healthy_startup_succeeds_with_writes_forbidden_and_preserves_every_sequence() + { + DualDatabaseFixture.Run(true, database => + { + using var connection = database.OpenConnection(); + InsertTask(connection); + var sequences = connection.Query("SELECT format('%I.%I', schemaname, sequencename) FROM pg_sequences WHERE schemaname = current_schema() ORDER BY sequencename").ToArray(); + string[] ReadStates() => sequences.Select(sequence => connection.ExecuteScalar( + $"SELECT last_value::text || ':' || is_called::text FROM {sequence}")).ToArray(); + var before = ReadStates(); + var config = new NpgsqlConnectionStringBuilder(connection.ConnectionString) { Options = "-c default_transaction_read_only=on" }; + using var readOnly = new NpgsqlConnection(config.ConnectionString); + readOnly.Open(); + Assert.That(readOnly.ExecuteScalar("SHOW transaction_read_only"), Is.EqualTo("on")); + + var logs = Capture(() => Startup(config.ConnectionString)); + + Assert.That(logs.Where(e => e.Level >= LogLevel.Warn), Is.Empty); + Assert.That(logs.Any(e => e.FormattedMessage.StartsWith("PostgreSQL ID counter public.\"ScheduledTasks\":", StringComparison.Ordinal)), Is.True); + Assert.That(ReadStates(), Is.EqualTo(before)); + + SetCounter(connection, "ScheduledTasks", 1, false); + before = ReadStates(); + logs = Capture(() => Startup(config.ConnectionString)); + AssertError(logs, "ScheduledTasks", PostgresErrorCodes.ReadOnlySqlTransaction); + Assert.That(ReadStates(), Is.EqualTo(before)); + }); + } + + [TestCase(false)] + [TestCase(true)] + public void whole_pass_budget_cancels_active_sql_and_reports_remaining_tables(bool duringRepair) + { + DualDatabaseFixture.Run(true, database => + { + using var connection = database.OpenConnection(); + if (duringRepair) + { + InsertTask(connection, 100); + SetCounter(connection, "ScheduledTasks", 1, false); + } + + // The table read or sequence repair could otherwise wait two seconds. + using (var locker = connection.BeginTransaction()) + { + if (duringRepair) + { + connection.ExecuteScalar("SELECT nextval(@sequence::regclass)", + new { sequence = Sequence(connection, "ScheduledTasks") }, locker); + } + else + { + connection.Execute("LOCK TABLE \"ScheduledTasks\" IN ACCESS EXCLUSIVE MODE", transaction: locker); + } + + var logs = Capture(() => PostgresSequenceRepair.Run(connection.ConnectionString, Logger, TimeSpan.FromMilliseconds(750))); + var error = logs.Single(e => e.Level == LogLevel.Error); + Assert.That(error.FormattedMessage, Does.Contain("ScheduledTasks")); + Assert.That(error.Exception, Is.InstanceOf()); + if (!duringRepair) + { + var processed = logs.Count(e => e.FormattedMessage.StartsWith("PostgreSQL ID counter public.", StringComparison.Ordinal)); + var summary = logs.Single(e => e.FormattedMessage.StartsWith("PostgreSQL ID counter check finished:", StringComparison.Ordinal)); + Assert.That(summary.Parameters[1], Is.EqualTo(processed), "The interrupted individual read must not count as checked."); + } + + Assert.That(logs.Any(e => e.Level == LogLevel.Warn && + e.FormattedMessage.Contains("Unchecked counters will be checked at next start.", StringComparison.Ordinal)), Is.True); + Assert.That(logs.Count(e => e.Level == LogLevel.Info && + e.FormattedMessage.StartsWith("PostgreSQL ID counter check finished:", StringComparison.Ordinal)), Is.EqualTo(1)); + if (duringRepair) + { + using var writable = database.OpenConnection(); + using var writer = writable.BeginTransaction(); + writable.Execute("LOCK TABLE \"ScheduledTasks\" IN ROW EXCLUSIVE MODE NOWAIT", transaction: writer); + Assert.That(State(connection, "ScheduledTasks"), Is.EqualTo("1:true")); + } + } + + if (duringRepair) + { + Startup(connection.ConnectionString); + Assert.That(InsertTask(connection), Is.EqualTo(101)); + } + }); + } + + [TestCase(false)] + [TestCase(true)] + public void broken_connection_warns_how_many_tables_were_not_checked(bool duringPrefetch) + { + DualDatabaseFixture.Run(true, database => + { + using var connection = database.OpenConnection(); + connection.Execute(@"CREATE SCHEMA counter_disconnect; + CREATE TABLE counter_disconnect.""A"" (""Id"" int GENERATED ALWAYS AS IDENTITY PRIMARY KEY); + CREATE TABLE counter_disconnect.""B"" (""Id"" int GENERATED ALWAYS AS IDENTITY PRIMARY KEY); + CREATE TABLE counter_disconnect.""C"" (""Id"" int GENERATED ALWAYS AS IDENTITY PRIMARY KEY);"); + var name = "counter_disconnect_" + Guid.NewGuid().ToString("N"); + var config = new NpgsqlConnectionStringBuilder(connection.ConnectionString) + { + ApplicationName = name, + SearchPath = "counter_disconnect" + }; + var terminated = false; + var logs = Capture(() => PostgresSequenceRepair.Run(config.ConnectionString, Logger), log => + { + var inventoried = log.FormattedMessage.StartsWith("PostgreSQL ID counter inventory:", StringComparison.Ordinal); + if (!duringPrefetch && inventoried) + { + // Make the combined read fail promptly so the next check uses fallback. + connection.Execute(@"DROP TABLE counter_disconnect.""C"""); + } + + var checkedFirst = log.FormattedMessage.StartsWith("PostgreSQL ID counter counter_disconnect.\"A\":", StringComparison.Ordinal); + if (!terminated && (duringPrefetch ? inventoried : checkedFirst)) + { + terminated = connection.ExecuteScalar("SELECT pg_terminate_backend(pid, 5000) FROM pg_stat_activity WHERE application_name = @Name", new { Name = name }); + } + }); + + Assert.That(terminated, Is.True); + var error = logs.Single(e => e.Level == LogLevel.Error); + Assert.That(error.FormattedMessage, Does.StartWith(duringPrefetch + ? "PostgreSQL ID counter prefetch stopped" + : "PostgreSQL ID counter repair failed for counter_disconnect.\"B\"")); + var processed = duringPrefetch ? 0 : 1; + Assert.That(logs.Single(e => e.Level == LogLevel.Warn).FormattedMessage, Is.EqualTo( + $"PostgreSQL ID counter pass stopped: {processed} of 3 tables processed; {3 - processed} not checked. Unchecked counters will be checked at next start.")); + var summary = logs.Single(e => e.FormattedMessage.StartsWith("PostgreSQL ID counter check finished:", StringComparison.Ordinal)); + Assert.That(summary.Parameters.Take(5), Is.EqualTo(new[] { 3, processed, 0, 0, 1 })); + }); + } + + [Test] + public void empty_unused_counters_are_not_advanced() + { + DualDatabaseFixture.Run(true, database => + { + using var connection = database.OpenConnection(); + var state = State(connection, "ScheduledTasks"); + Repair(connection); + Assert.That(State(connection, "ScheduledTasks"), Is.EqualTo(state)); + Assert.That(InsertTask(connection), Is.EqualTo(1)); + }); + } + + [Test] + public void custom_cached_allocation_is_not_misidentified_as_safe_from_its_high_water_mark() + { + DualDatabaseFixture.Run(true, database => + { + using var connection = database.OpenConnection(); + var sequence = Sequence(connection, "ScheduledTasks"); + connection.Execute($"ALTER SEQUENCE {sequence} CACHE 20"); + using var cached = database.OpenConnection(); + Assert.That(InsertTask(cached), Is.EqualTo(1)); + InsertTask(connection, 2); + InsertTask(connection, 15); + var state = State(connection, "ScheduledTasks"); + Assert.That(state, Is.EqualTo("20:true"), "Reserved high-water mark is above every stored Id, but this session still holds Id 2."); + Assert.That(RepairWarnings(connection), Has.Some.Contains("Skipped automatic PostgreSQL ID counter check for public.\"ScheduledTasks\"")); + Assert.That(State(connection, "ScheduledTasks"), Is.EqualTo(state)); + Assert.That(connection.ExecuteScalar("SELECT seqcache FROM pg_sequence WHERE seqrelid=@sequence::regclass", new { sequence }), Is.EqualTo(20)); + Assert.That(Assert.Throws(() => InsertTask(cached)).SqlState, Is.EqualTo(PostgresErrorCodes.UniqueViolation), "Skipping is explicitly not a claim that custom cached allocations were repaired."); + }); + } + + [TestCase(false)] + [TestCase(true)] + public void repair_session_keeps_its_timeouts_after_prefetch(bool blockRead) + { + DualDatabaseFixture.Run(true, database => + { + using var connection = database.OpenConnection(); + if (!connection.ExecuteScalar("SELECT rolsuper FROM pg_roles WHERE rolname = current_user")) + { + Assert.Ignore("Recording the repair session settings requires a PostgreSQL test superuser."); + } + + connection.Execute(@"CREATE SCHEMA counter_limits; + CREATE TABLE counter_limits.""Repair"" (""Id"" int GENERATED ALWAYS AS IDENTITY PRIMARY KEY); + INSERT INTO counter_limits.""Repair"" OVERRIDING SYSTEM VALUE VALUES (100); + CREATE TABLE counter_limits.observed_settings (lock_wait text, idle_limit text); + CREATE FUNCTION counter_limits.record_settings() RETURNS event_trigger LANGUAGE plpgsql AS $$ + BEGIN + INSERT INTO counter_limits.observed_settings VALUES + (current_setting('lock_timeout'), current_setting('idle_in_transaction_session_timeout')); + END; + $$; + CREATE EVENT TRIGGER counter_repair_settings ON ddl_command_start + WHEN TAG IN ('ALTER SEQUENCE') EXECUTE FUNCTION counter_limits.record_settings()"); + + var config = new NpgsqlConnectionStringBuilder(connection.ConnectionString) + { + SearchPath = "counter_limits", + Options = "-c lock_timeout=1s -c idle_in_transaction_session_timeout=45s" + }; + using (var locker = blockRead ? connection.BeginTransaction() : null) + { + if (blockRead) + { + connection.Execute(@"LOCK TABLE counter_limits.""Repair"" IN ACCESS EXCLUSIVE MODE", transaction: locker); + } + + var released = false; + var logs = Capture(() => PostgresSequenceRepair.Run(config.ConnectionString, Logger), log => + { + if (blockRead && log.FormattedMessage.StartsWith("PostgreSQL ID counter prefetch failed;", StringComparison.Ordinal)) + { + locker.Rollback(); // The prefetch hit its limit; let fallback repair the row. + released = true; + } + }); + + Assert.That(released, Is.EqualTo(blockRead)); + Assert.That(logs.Where(e => e.Level == LogLevel.Error), Is.Empty); + if (!blockRead) + { + Assert.That(logs.Any(e => e.FormattedMessage.StartsWith("PostgreSQL ID counter prefetch:", StringComparison.Ordinal)), Is.True); + } + } + + var settings = connection.Query("SELECT DISTINCT lock_wait || '|' || idle_limit FROM counter_limits.observed_settings"); + Assert.That(settings, Is.EqualTo(new[] { "2s|20s" })); + Assert.That(connection.ExecuteScalar(@"INSERT INTO counter_limits.""Repair"" DEFAULT VALUES RETURNING ""Id"""), Is.EqualTo(101)); + }); + } + + [Test] + public void combined_read_falls_back_after_one_table_lock() + { + VerifyCombinedRead(blockRead: true, unsupported: false); + } + + [TestCase(false)] + [TestCase(true)] + public void combined_read_repairs_supported_peers_without_modifying_unused_or_unsupported_counters(bool unsupported) + { + VerifyCombinedRead(blockRead: false, unsupported); + } + + private static void VerifyCombinedRead(bool blockRead, bool unsupported) + { + DualDatabaseFixture.Run(true, database => + { + using var connection = database.OpenConnection(); + connection.Execute(@"CREATE SCHEMA counter_prefetch; + CREATE TABLE counter_prefetch.""ARead"" (""Id"" bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY); + CREATE TABLE counter_prefetch.""BBlocked"" (""Id"" integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY); + CREATE TABLE counter_prefetch.""CRepair"" (""Id"" smallint GENERATED ALWAYS AS IDENTITY PRIMARY KEY); + CREATE TABLE counter_prefetch.""DEmpty"" (""Id"" integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY); + INSERT INTO counter_prefetch.""ARead"" OVERRIDING SYSTEM VALUE VALUES (4000000000); + INSERT INTO counter_prefetch.""BBlocked"" OVERRIDING SYSTEM VALUE VALUES (100); + INSERT INTO counter_prefetch.""CRepair"" OVERRIDING SYSTEM VALUE VALUES (100)"); + if (unsupported) + { + connection.Execute(@"ALTER SEQUENCE counter_prefetch.""BBlocked_Id_seq"" CACHE 20"); + } + + var config = new NpgsqlConnectionStringBuilder(connection.ConnectionString) { SearchPath = "counter_prefetch" }; + using (var locker = connection.BeginTransaction()) + { + if (blockRead) + { + connection.Execute(@"LOCK TABLE counter_prefetch.""BBlocked"" IN ACCESS EXCLUSIVE MODE", transaction: locker); + } + + var lockedAfterPrefetch = false; + var logs = Capture(() => PostgresSequenceRepair.Run(config.ConnectionString, Logger), log => + { + if (!blockRead && log.FormattedMessage.StartsWith("PostgreSQL ID counter prefetch:", StringComparison.Ordinal)) + { + // A second read of this healthy table would now fail. + connection.Execute(@"LOCK TABLE counter_prefetch.""DEmpty"" IN ACCESS EXCLUSIVE MODE NOWAIT", transaction: locker); + lockedAfterPrefetch = true; + } + }); + var errors = logs.Where(e => e.Level == LogLevel.Error).ToArray(); + if (blockRead) + { + Assert.That(errors, Has.Length.EqualTo(1)); + Assert.That(errors[0].FormattedMessage, Does.Contain("counter_prefetch.\"BBlocked\"")); + Assert.That(((PostgresException)errors[0].Exception).SqlState, Is.EqualTo(PostgresErrorCodes.LockNotAvailable)); + Assert.That(logs.Single(e => e.FormattedMessage.StartsWith("PostgreSQL ID counter prefetch failed", StringComparison.Ordinal)).Exception, + Is.TypeOf().With.Property(nameof(PostgresException.SqlState)).EqualTo(PostgresErrorCodes.LockNotAvailable)); + } + else + { + Assert.That(lockedAfterPrefetch, Is.True); + Assert.That(errors, Is.Empty); + var read = logs.Single(e => e.FormattedMessage.StartsWith("PostgreSQL ID counter prefetch:", StringComparison.Ordinal)); + Assert.That(read.Parameters[0], Is.EqualTo(unsupported ? 3 : 4)); + } + + if (unsupported) + { + Assert.That(logs.Any(e => e.Level == LogLevel.Warn && + e.FormattedMessage.StartsWith("Skipped automatic PostgreSQL ID counter check for counter_prefetch.\"BBlocked\"", StringComparison.Ordinal)), Is.True); + } + } + + Assert.That(connection.ExecuteScalar(@"INSERT INTO counter_prefetch.""ARead"" DEFAULT VALUES RETURNING ""Id"""), Is.EqualTo(4_000_000_001L)); + Assert.That(connection.ExecuteScalar(@"SELECT is_called FROM counter_prefetch.""DEmpty_Id_seq"""), Is.False); + Assert.That(connection.ExecuteScalar(@"INSERT INTO counter_prefetch.""CRepair"" DEFAULT VALUES RETURNING ""Id"""), Is.EqualTo(101)); + Assert.That(connection.ExecuteScalar(@"SELECT last_value FROM counter_prefetch.""BBlocked_Id_seq"""), Is.EqualTo(blockRead || unsupported ? 1 : 101)); + }); + } + + [Test] + public void table_lock_timeout_is_nonfatal_and_other_tables_still_repair() + { + DualDatabaseFixture.Run(true, database => + { + using var connection = database.OpenConnection(); + InsertRepairPeers(connection); + InsertTask(connection, 100); + var before = State(connection, "ScheduledTasks"); + using (var writer = connection.BeginTransaction()) + { + connection.Execute("UPDATE \"ScheduledTasks\" SET \"Interval\" = 2", transaction: writer); + var timer = Stopwatch.StartNew(); + var logs = Capture(() => Startup(connection.ConnectionString)); + AssertError(logs, "ScheduledTasks", PostgresErrorCodes.LockNotAvailable); + Assert.That(timer.Elapsed, Is.LessThan(TimeSpan.FromSeconds(15))); + Assert.That(State(connection, "ScheduledTasks"), Is.EqualTo(before)); + AssertPeersRepaired(connection); + writer.Rollback(); + } + + Startup(connection.ConnectionString); + Assert.That(InsertTask(connection), Is.EqualTo(101)); + }); + } + + [Test] + public void direct_sequence_allocation_blocks_only_its_table_repair() + { + DualDatabaseFixture.Run(true, database => + { + using var connection = database.OpenConnection(); + InsertRepairPeers(connection); + InsertTask(connection, 100); + using var allocator = connection.BeginTransaction(); + connection.ExecuteScalar("SELECT nextval(@sequence::regclass)", new { sequence = Sequence(connection, "ScheduledTasks") }, allocator); + var before = State(connection, "ScheduledTasks"); + var logs = Capture(() => Startup(connection.ConnectionString)); + AssertError(logs, "ScheduledTasks", PostgresErrorCodes.LockNotAvailable); + Assert.That(State(connection, "ScheduledTasks"), Is.EqualTo(before)); + AssertPeersRepaired(connection); + allocator.Rollback(); + Startup(connection.ConnectionString); + Assert.That(InsertTask(connection), Is.EqualTo(101)); + }); + } + + [Test] + public void writer_advancing_counter_after_initial_read_is_not_rewound() + { + DualDatabaseFixture.Run(true, database => + { + using var connection = database.OpenConnection(); + InsertTask(connection, 100); + using var read = new ManualResetEventSlim(); + using var resume = new ManualResetEventSlim(); + var repair = Task.Run(() => Capture(() => Startup(connection.ConnectionString), log => + { + if (log.FormattedMessage.StartsWith("PostgreSQL ID counter public.\"ScheduledTasks\":", StringComparison.Ordinal)) + { + read.Set(); + Assert.That(resume.Wait(TimeSpan.FromSeconds(30)), Is.True); + } + })); + try + { + Assert.That(read.Wait(TimeSpan.FromSeconds(30)), Is.True, "Wait for the actual initial read, independently of connection/catalog latency."); + SetCounter(connection, "ScheduledTasks", 200, true); + } + finally + { + resume.Set(); + repair.GetAwaiter().GetResult(); + } + + Assert.That(State(connection, "ScheduledTasks"), Is.EqualTo("200:true")); + Assert.That(InsertTask(connection), Is.EqualTo(201)); + }); + } + + [TestCase("INCREMENT BY -1")] + [TestCase("CYCLE")] + public void unusual_sequences_are_reported_and_left_unchanged(string alteration) + { + DualDatabaseFixture.Run(true, database => + { + using var connection = database.OpenConnection(); + var sequence = Sequence(connection, "ScheduledTasks"); + connection.Execute($"ALTER SEQUENCE {sequence} {alteration}"); + var state = State(connection, "ScheduledTasks"); + Assert.That(RepairWarnings(connection), Has.Some.Contains("Skipped automatic PostgreSQL ID counter check for public.\"ScheduledTasks\"")); + Assert.That(State(connection, "ScheduledTasks"), Is.EqualTo(state)); + }); + } + + [Test] + public void exhausted_id_range_is_nonfatal_and_other_tables_still_repair() + { + DualDatabaseFixture.Run(true, database => + { + using var connection = database.OpenConnection(); + InsertRepairPeers(connection); + InsertTask(connection, int.MaxValue); + var before = State(connection, "ScheduledTasks"); + var logs = Capture(() => Startup(connection.ConnectionString)); + AssertError(logs, "ScheduledTasks", "n/a"); + Assert.That(logs.Single(e => e.Level == LogLevel.Error).Exception.Message, Is.EqualTo("The Id range is exhausted.")); + Assert.That(State(connection, "ScheduledTasks"), Is.EqualTo(before)); + AssertPeersRepaired(connection); + }); + } + + [Test] + public void every_visible_owned_id_counter_is_checked_without_a_model_mapping() + { + DualDatabaseFixture.Run(true, database => + { + using var connection = database.OpenConnection(); + connection.Execute("CREATE TABLE extra_counter (\"Id\" serial PRIMARY KEY); INSERT INTO extra_counter VALUES (100)"); + var logs = Capture(() => Startup(connection.ConnectionString)); + Assert.That(connection.ExecuteScalar("INSERT INTO extra_counter DEFAULT VALUES RETURNING \"Id\""), Is.EqualTo(101)); + Assert.That(logs.Any(e => e.Level >= LogLevel.Warn && e.FormattedMessage.Contains("VersionInfo")), Is.False); + }); + } + + [Test] + public void migration_created_unmapped_import_claim_counter_is_repaired() + { + DualDatabaseFixture.Run(true, database => + { + using var connection = database.OpenConnection(); + connection.Execute(@"INSERT INTO ""AuthorImportClaims"" (""Id"", ""ProviderId"", ""ClaimedAt"", ""LeaseSec"") + OVERRIDING SYSTEM VALUE VALUES (1, 'stored', 0, 300), (100, 'stored-high', 0, 300)"); + SetCounter(connection, "AuthorImportClaims", 1, false); + Startup(connection.ConnectionString); + var events = InterfaceProxy.Proxy((_, _) => null); + var repository = new NzbDrone.Core.Books.AuthorRepository(database, events, Logger); + Assert.That(repository.TryClaimAuthorImport("new-claim"), Is.True); + Assert.That(connection.ExecuteScalar("SELECT \"Id\" FROM \"AuthorImportClaims\" WHERE \"ProviderId\"='new-claim'"), Is.EqualTo(101)); + }); + } + + [Test] + public void connection_open_failure_is_left_to_the_callers_startup_error_handling() + { + DualDatabaseFixture.Run(true, database => + { + using var connection = database.OpenConnection(); + var config = new NpgsqlConnectionStringBuilder(connection.ConnectionString) { Database = "counter_missing_" + Guid.NewGuid().ToString("N") }; + var logs = Capture(() => + { + var error = Assert.Throws(() => new MigrationController(Logger, null) + .Migrate(config.ConnectionString, new MigrationContext(MigrationType.Main), DatabaseType.PostgreSQL)); + Assert.That(error.SqlState, Is.EqualTo(PostgresErrorCodes.InvalidCatalogName)); + }); + Assert.That(logs.Where(e => e.Level == LogLevel.Error), Is.Empty); + }); + } + + [Test] + public void serial_sequences_are_discovered_by_ownership_not_by_name() + { + DualDatabaseFixture.Run(true, database => + { + using var connection = database.OpenConnection(); + connection.Execute(@"ALTER TABLE ""ScheduledTasks"" ALTER COLUMN ""Id"" DROP IDENTITY; + CREATE SEQUENCE ""odd counter name"" OWNED BY ""ScheduledTasks"".""Id""; + ALTER TABLE ""ScheduledTasks"" ALTER COLUMN ""Id"" SET DEFAULT nextval('""odd counter name""'::regclass)"); + InsertTask(connection, 100); + Repair(connection); + Assert.That(InsertTask(connection), Is.EqualTo(101)); + }); + } + + [Test] + public void repair_follows_search_path_and_does_not_touch_a_shadowed_table() + { + DualDatabaseFixture.Run(true, database => + { + using var connection = database.OpenConnection(); + connection.Execute(@"CREATE SCHEMA ""counter schema""; + CREATE TABLE ""counter schema"".""ScheduledTasks"" (""Id"" int GENERATED ALWAYS AS IDENTITY PRIMARY KEY); + INSERT INTO ""counter schema"".""ScheduledTasks"" OVERRIDING SYSTEM VALUE VALUES (200)"); + InsertTask(connection, 100); + var state = State(connection, "ScheduledTasks"); + var config = new NpgsqlConnectionStringBuilder(connection.ConnectionString) { SearchPath = "\"counter schema\", public" }; + PostgresSequenceRepair.Run(config.ConnectionString, Logger); + Assert.That(State(connection, "ScheduledTasks"), Is.EqualTo(state), "The application resolves the other schema, so public's same-named table is not ours to change."); + Assert.That(connection.ExecuteScalar("INSERT INTO \"counter schema\".\"ScheduledTasks\" DEFAULT VALUES RETURNING \"Id\""), Is.EqualTo(201)); + }); + } + + [TestCase(false)] + [TestCase(true)] + public void missing_repair_permission_is_nonfatal_and_other_tables_still_repair(bool canWriteRows) + { + DualDatabaseFixture.Run(true, database => + { + using var connection = database.OpenConnection(); + var role = "counter_" + Guid.NewGuid().ToString("N"); + var password = Guid.NewGuid().ToString("N"); + connection.Execute($"CREATE ROLE {role} LOGIN PASSWORD '{password}'; GRANT USAGE ON SCHEMA public TO {role}; GRANT SELECT ON ALL TABLES IN SCHEMA public TO {role}; GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO {role}"); + try + { + var config = new NpgsqlConnectionStringBuilder(connection.ConnectionString) { Username = role, Password = password }; + Startup(config.ConnectionString); // Healthy counters need no ALTER privilege. + InsertRepairPeers(connection); + connection.Execute($"ALTER TABLE \"Config\" OWNER TO {role}"); + if (canWriteRows) + { + connection.Execute($"GRANT INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO {role}"); + using var writer = new NpgsqlConnection(config.ConnectionString); + writer.Open(); + using var transaction = writer.BeginTransaction(); + writer.Execute("LOCK TABLE \"ScheduledTasks\", \"Tags\" IN SHARE ROW EXCLUSIVE MODE", transaction: transaction); + transaction.Commit(); // Prove that this role passes LOCK, before testing ALTER ownership. + } + else + { + connection.Execute($"ALTER TABLE \"Tags\" OWNER TO {role}"); + } + InsertTask(connection, 100); + var before = State(connection, "ScheduledTasks"); + var logs = Capture(() => Startup(config.ConnectionString)); + Assert.That(State(connection, "ScheduledTasks"), Is.EqualTo(before)); + if (canWriteRows) + { + var errors = logs.Where(e => e.Level == LogLevel.Error).ToArray(); + Assert.That(errors, Has.Length.EqualTo(2)); + foreach (var error in errors) + { + var failure = (PostgresException)error.Exception; + Assert.That(failure.SqlState, Is.EqualTo(PostgresErrorCodes.InsufficientPrivilege)); + Assert.That(failure.MessageText, Does.StartWith("must be owner of sequence")); + } + Assert.That(State(connection, "Tags"), Is.EqualTo("1:false")); + Assert.That(State(connection, "Config"), Is.EqualTo("10001:false")); + } + else + { + AssertError(logs, "ScheduledTasks", PostgresErrorCodes.InsufficientPrivilege); + AssertPeersRepaired(connection); + } + } + finally + { + connection.Execute($"DROP OWNED BY {role}; DROP ROLE {role}"); + } + }); + } + + [Test] + public void repair_preserves_book_edition_file_relationships_and_allows_a_real_repository_insert() + { + DualDatabaseFixture.Run(true, database => + { + using var connection = database.OpenConnection(); + connection.Execute(@"INSERT INTO ""Authors"" (""Id"", ""Name"", ""CleanName"", ""Path"", ""Monitored"", ""Added"") + OVERRIDING SYSTEM VALUE VALUES (100, 'Counter Author', 'counter author', '/fixture', true, CURRENT_TIMESTAMP); + INSERT INTO ""Books"" (""Id"", ""AuthorId"", ""Title"", ""CleanTitle"", ""MediaType"", ""AnyEditionOk"", ""Added"") + OVERRIDING SYSTEM VALUE VALUES (200, 100, 'Counter Book', 'counter book', 0, true, CURRENT_TIMESTAMP); + INSERT INTO ""Editions"" (""Id"", ""BookId"", ""Title"", ""Monitored"") + OVERRIDING SYSTEM VALUE VALUES (300, 200, 'Stored Edition', true); + INSERT INTO ""BookFiles"" (""Id"", ""EditionId"", ""Path"", ""Size"", ""Modified"", ""DateAdded"", ""Quality"", ""MediaInfo"", ""CalibreId"", ""Part"") + OVERRIDING SYSTEM VALUE VALUES (400, 300, '/fixture/book.m4b', 1234, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, '{}', '{}', 0, 1)"); + var names = new[] { "Authors", "Books", "Editions", "BookFiles" }; + var before = names.Select(table => connection.Query($"SELECT row_to_json(t)::text FROM \"{table}\" t ORDER BY \"Id\"").ToArray()).ToArray(); + Repair(connection); + for (var i = 0; i < names.Length; i++) + { + Assert.That(connection.Query($"SELECT row_to_json(t)::text FROM \"{names[i]}\" t ORDER BY \"Id\""), Is.EqualTo(before[i]), names[i]); + } + + var events = InterfaceProxy.Proxy((_, _) => null); + var repository = new BasicRepository(database, events); + var edition = repository.Insert(new NzbDrone.Core.Books.Edition { BookId = 200, Title = "New Edition", Monitored = false }); + Assert.That(edition.Id, Is.EqualTo(301)); + Assert.That(edition.BookId, Is.EqualTo(200)); + Assert.That(connection.ExecuteScalar("SELECT \"EditionId\" FROM \"BookFiles\" WHERE \"Id\" = 400"), Is.EqualTo(300)); + }); + } + + [Test] + public void sqlite_startup_does_not_run_postgres_repair() + { + DualDatabaseFixture.Run(false, database => + { + using var connection = database.OpenConnection(); + var before = connection.Query("SELECT name || ':' || seq FROM sqlite_sequence ORDER BY name").ToArray(); + var logs = Capture(() => Startup(connection.ConnectionString, postgres: false)); + Assert.That(logs.Where(e => e.Level >= LogLevel.Error || + e.FormattedMessage.StartsWith("PostgreSQL ID counter", StringComparison.Ordinal)), Is.Empty); + Assert.That(connection.Query("SELECT name || ':' || seq FROM sqlite_sequence ORDER BY name"), Is.EqualTo(before)); + }); + } + } +} diff --git a/src/NzbDrone.Core/Books/Services/PendingAuthorImportService.cs b/src/NzbDrone.Core/Books/Services/PendingAuthorImportService.cs index 35a21b9ca..3b6e4e886 100644 --- a/src/NzbDrone.Core/Books/Services/PendingAuthorImportService.cs +++ b/src/NzbDrone.Core/Books/Services/PendingAuthorImportService.cs @@ -755,8 +755,7 @@ private static bool IsActiveProviderUniqueViolation(SqliteException ex) private static bool IsActiveProviderUniqueViolation(PostgresException ex) { return string.Equals(ex?.SqlState, "23505", StringComparison.Ordinal) && - (string.Equals(ex.ConstraintName, "UX_PendingAuthorImport_Active", StringComparison.OrdinalIgnoreCase) || - ex.MessageText?.Contains("PendingAuthorImport", StringComparison.OrdinalIgnoreCase) == true); + string.Equals(ex.ConstraintName, "UX_PendingAuthorImport_Active", StringComparison.OrdinalIgnoreCase); } private bool TryMergeProviderIds( diff --git a/src/NzbDrone.Core/Datastore/Migration/Framework/MigrationController.cs b/src/NzbDrone.Core/Datastore/Migration/Framework/MigrationController.cs index fe8a600c6..a3c0e3851 100644 --- a/src/NzbDrone.Core/Datastore/Migration/Framework/MigrationController.cs +++ b/src/NzbDrone.Core/Datastore/Migration/Framework/MigrationController.cs @@ -35,6 +35,11 @@ public void Migrate(string connectionString, MigrationContext migrationContext, { var sw = Stopwatch.StartNew(); + if (databaseType == DatabaseType.PostgreSQL) + { + PostgresSequenceRepair.Run(connectionString, _logger); + } + _logger.Info("*** Migrating {0} database ***", databaseType); ServiceProvider serviceProvider; diff --git a/src/NzbDrone.Core/Datastore/PostgresSequenceRepair.cs b/src/NzbDrone.Core/Datastore/PostgresSequenceRepair.cs new file mode 100644 index 000000000..b08834757 --- /dev/null +++ b/src/NzbDrone.Core/Datastore/PostgresSequenceRepair.cs @@ -0,0 +1,273 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Diagnostics; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Dapper; +using NLog; +using Npgsql; + +namespace NzbDrone.Core.Datastore +{ + internal static class PostgresSequenceRepair + { + // One read round trip on a healthy pass; never wait 30 seconds for every table. + private static readonly TimeSpan PassBudget = TimeSpan.FromSeconds(30); + private const int CommandTimeoutSeconds = 30; + // The optimistic read mustn't repeat the full lock wait before per-table fallback. + private const int PrefetchLockTimeoutMilliseconds = 250; + // Ordinary autovacuum can yield after deadlock_timeout (normally 1 s). + // Allow that handoff, but bound startup waiting; wraparound vacuum may not yield. + private const int LockTimeoutMilliseconds = 2000; + + private sealed class Counter + { + public long TableId { get; set; } + public string Table { get; set; } + public string Sequence { get; set; } + public bool Supported { get; set; } + public long MaximumValue { get; set; } + } + + private sealed class State + { + public long TableId { get; set; } + public long? MaximumId { get; set; } + public long LastValue { get; set; } + public bool IsCalled { get; set; } + + public bool NeedsRepair => MaximumId.HasValue && + (LastValue < MaximumId.Value || (!IsCalled && LastValue == MaximumId.Value)); + } + + public static void Run(string connectionString, Logger logger, TimeSpan? passBudget = null) + { + // Keep session settings out of the application pool. Let Open failures reach + // DbFactory's existing connection retry instead of diagnosing them as drift. + using var connection = new NpgsqlConnection(new NpgsqlConnectionStringBuilder(connectionString) + { + Pooling = false, + Enlist = false, + CancellationTimeout = 2000 + }.ConnectionString); + connection.Open(); + CheckCounters(connection, logger, passBudget ?? PassBudget).GetAwaiter().GetResult(); + } + + private static async Task CheckCounters(NpgsqlConnection connection, Logger logger, TimeSpan passBudget) + { + var timer = Stopwatch.StartNew(); + using var deadline = new CancellationTokenSource(passBudget); + CommandDefinition Command(string sql, NpgsqlTransaction transaction = null) => + new(sql, transaction: transaction, commandTimeout: CommandTimeoutSeconds, cancellationToken: deadline.Token); + + List counters; + try + { + await connection.ExecuteAsync(Command($"SET lock_timeout = '{LockTimeoutMilliseconds}ms'; SET statement_timeout = '{CommandTimeoutSeconds}s'; SET idle_in_transaction_session_timeout = '20s'")) + .ConfigureAwait(false); + + // Include migration-created counters that have no mapped model. Follow the + // application's search path and owned serial/identity dependencies, not names. + counters = (await connection.QueryAsync(Command(@" + SELECT t.oid::bigint AS ""TableId"", + format('%I.%I', n.nspname, t.relname) AS ""Table"", + CASE WHEN s.oid IS NOT NULL THEN format('%I.%I', sn.nspname, s.relname) END AS ""Sequence"", + COALESCE(t.relkind = 'r' AND s.relpersistence = 'p' + AND q.seqincrement = 1 AND q.seqcache = 1 AND NOT q.seqcycle + AND has_sequence_privilege(s.oid, 'SELECT') AND has_table_privilege(t.oid, 'SELECT') + AND a.atttypid IN ('int2'::regtype, 'int4'::regtype, 'int8'::regtype) + AND (a.attidentity IN ('a', 'd') OR pg_get_expr(d.adbin, d.adrelid) = + format('nextval(%L::regclass)', s.oid::regclass::text)), false) AS ""Supported"", + LEAST(q.seqmax, CASE a.atttypid WHEN 'int2'::regtype THEN 32767::bigint + WHEN 'int4'::regtype THEN 2147483647::bigint ELSE 9223372036854775807::bigint END) AS ""MaximumValue"" + FROM pg_class t + JOIN pg_namespace n ON n.oid = t.relnamespace + JOIN pg_attribute a ON a.attrelid = t.oid AND a.attname = 'Id' AND NOT a.attisdropped + LEFT JOIN pg_attrdef d ON d.adrelid = t.oid AND d.adnum = a.attnum + LEFT JOIN pg_class s ON s.oid = pg_get_serial_sequence(format('%I.%I', n.nspname, t.relname), a.attname)::regclass + LEFT JOIN pg_namespace sn ON sn.oid = s.relnamespace + LEFT JOIN pg_sequence q ON q.seqrelid = s.oid + WHERE pg_table_is_visible(t.oid) AND n.nspname = ANY(current_schemas(false)) + AND t.relkind = 'r' AND s.oid IS NOT NULL + AND EXISTS (SELECT 1 FROM pg_index i WHERE i.indrelid = t.oid + AND i.indisprimary AND i.indisvalid AND i.indnkeyatts = 1 AND i.indkey[0] = a.attnum) + ORDER BY t.relname")).ConfigureAwait(false)).ToList(); + } + catch (Exception ex) + { + if (deadline.IsCancellationRequested) + { + logger.Warn(ex, "PostgreSQL ID counter pass stopped before inventory finished; no counters checked. Unchecked counters will be checked at next start."); + } + else + { + logger.Error(ex, "PostgreSQL ID counter inventory failed (SQLSTATE {0}); remaining counters were not checked; retried at next start. Startup will continue.", + SqlState(ex)); + } + + logger.Info("PostgreSQL ID counter check finished: inventory unavailable, 0 repaired, 0 skipped, 1 failed in {0} ms", timer.ElapsedMilliseconds); + return; + } + + logger.Debug("PostgreSQL ID counter inventory: {0} tables in {1} ms", counters.Count, timer.ElapsedMilliseconds); + + var repaired = 0; + var skipped = 0; + var failed = 0; + var processed = 0; + bool CanContinue() => !deadline.IsCancellationRequested && connection.State == ConnectionState.Open; + + Dictionary prefetched = null; + var reads = counters.Where(counter => counter.Supported).Select(ReadSql).ToArray(); + if (reads.Length > 0 && CanContinue()) + { + var check = Stopwatch.StartNew(); + try + { + // Npgsql sends this as one implicit transaction. On failure PostgreSQL + // rolls back the shorter SET; on success the final SET restores the limit. + // The two-second wait remains available for individual checks and repairs. + var sql = $"SET lock_timeout = '{PrefetchLockTimeoutMilliseconds}ms'; " + + string.Join(" UNION ALL ", reads) + $"; SET lock_timeout = '{LockTimeoutMilliseconds}ms'"; + prefetched = (await connection.QueryAsync(Command(sql)).ConfigureAwait(false)) + .ToDictionary(state => state.TableId); + logger.Debug("PostgreSQL ID counter prefetch: {0} tables in {1} ms", prefetched.Count, check.ElapsedMilliseconds); + } + catch (Exception ex) + { + if (CanContinue()) + { + logger.Debug(ex, "PostgreSQL ID counter prefetch failed; checking counters individually."); + } + else + { + failed++; + logger.Error(ex, "PostgreSQL ID counter prefetch stopped (SQLSTATE {0}); no counters checked. Startup will continue.", + SqlState(ex)); + } + } + } + + foreach (var counter in counters) + { + if (!CanContinue()) + { + break; + } + + processed++; + if (!counter.Supported) + { + skipped++; + logger.Warn("Skipped automatic PostgreSQL ID counter check for {0}: requires an owned, logged sequence with increment 1, cache 1, no cycling, an integer Id and read permission. This table was left unchanged.", counter.Table); + continue; + } + + var commitPending = false; + State state = null; + try + { + if (prefetched?.TryGetValue(counter.TableId, out state) != true) + { + state = await connection.QuerySingleAsync(Command(ReadSql(counter))).ConfigureAwait(false); + } + + logger.Debug("PostgreSQL ID counter {0}: highest Id {1}, last value {2}, called {3}", + counter.Table, state.MaximumId, state.LastValue, state.IsCalled); + if (!state.NeedsRepair) + { + continue; + } + + // Each repair is independent. Match INSERT's lock order, also exclude + // direct nextval callers, then re-read so another writer is never rewound. + using var transaction = await connection.BeginTransactionAsync(deadline.Token).ConfigureAwait(false); + var committed = false; + try + { + await connection.ExecuteAsync(Command($"LOCK TABLE {counter.Table} IN SHARE ROW EXCLUSIVE MODE; ALTER SEQUENCE {counter.Sequence} NO CYCLE", transaction)) + .ConfigureAwait(false); + state = await connection.QuerySingleAsync(Command(ReadSql(counter), transaction)).ConfigureAwait(false); + if (!state.NeedsRepair) + { + continue; + } + + if (state.MaximumId.Value >= counter.MaximumValue) + { + throw new InvalidOperationException("The Id range is exhausted."); + } + + var next = state.MaximumId.Value + 1; + // RESTART rolls back with this table's transaction; setval does not. + await connection.ExecuteAsync(Command($"ALTER SEQUENCE {counter.Sequence} RESTART WITH {next}", transaction)).ConfigureAwait(false); + commitPending = true; + await transaction.CommitAsync(deadline.Token).ConfigureAwait(false); + commitPending = false; + committed = true; + repaired++; + logger.Warn("Repaired PostgreSQL ID counter for {0}: last value {1} (called {2}), highest Id {3}, next Id {4}. Existing row IDs were not changed.", + counter.Table, state.LastValue, state.IsCalled, state.MaximumId, next); + } + finally + { + if (!committed && connection.State == ConnectionState.Open) + { + try + { + await transaction.RollbackAsync(deadline.Token).ConfigureAwait(false); + } + catch (Exception ex) + { + // Do not let disposal send an unbounded ROLLBACK after + // the deadline. Closing this unpooled session releases its locks. + logger.Debug(ex, "Closing the PostgreSQL ID counter connection after an incomplete rollback."); + await connection.CloseAsync().ConfigureAwait(false); + } + } + } + } + catch (Exception ex) + { + failed++; + // A lost COMMIT acknowledgement cannot honestly be called unchanged. + var outcome = commitPending && ex is not PostgresException ? "commit outcome unknown" : "left unchanged"; + LogFailure(logger, counter, ex, outcome); + if (!CanContinue()) + { + // If the initial read was interrupted, this table was never checked. + if (state == null) + { + processed--; + } + + break; + } + } + } + + if (processed < counters.Count) + { + logger.Warn("PostgreSQL ID counter pass stopped: {0} of {1} tables processed; {2} not checked. Unchecked counters will be checked at next start.", + processed, counters.Count, counters.Count - processed); + } + + logger.Info("PostgreSQL ID counter check finished: {0} inventoried, {1} processed, {2} repaired, {3} skipped, {4} failed in {5} ms", + counters.Count, processed, repaired, skipped, failed, timer.ElapsedMilliseconds); + } + + private static string ReadSql(Counter counter) => FormattableString.Invariant($@" + SELECT {counter.TableId}::bigint AS ""TableId"", + (SELECT MAX(""Id"")::bigint FROM {counter.Table}) AS ""MaximumId"", + last_value AS ""LastValue"", is_called AS ""IsCalled"" FROM {counter.Sequence}"); + + private static void LogFailure(Logger logger, Counter counter, Exception exception, string outcome) => + logger.Error(exception, "PostgreSQL ID counter repair failed for {0} (SQLSTATE {1}); {2}; retried at next start. Startup will continue.", + counter.Table, SqlState(exception), outcome); + + private static string SqlState(Exception exception) => exception is PostgresException postgres ? postgres.SqlState : "n/a"; + } +} From 01c13624d20e6f8c6ffe04c251166341088c75d3 Mon Sep 17 00:00:00 2001 From: robertlordhood <204023072+robertlordhood@users.noreply.github.com> Date: Sat, 5 Dec 2026 20:01:51 +0000 Subject: [PATCH 3/3] Replace the in-app release notes for this release The notes cover what was merged since 0.9.1000, with the widely used changes first and the tag-writing changes last. --- .../Update/UpdatePackageProvider.cs | 52 ++++++------------- 1 file changed, 16 insertions(+), 36 deletions(-) diff --git a/src/NzbDrone.Core/Update/UpdatePackageProvider.cs b/src/NzbDrone.Core/Update/UpdatePackageProvider.cs index 7c70696df..80fb5bff8 100644 --- a/src/NzbDrone.Core/Update/UpdatePackageProvider.cs +++ b/src/NzbDrone.Core/Update/UpdatePackageProvider.cs @@ -186,45 +186,25 @@ private List GetChaptarrEnhancements(Version currentVersion) { New = new List { - "Quality profiles can replace upgrades automatically or wait for you to confirm.", - "Author page Search groups results by book, best pick first. It has a Stop button, keeps running if you leave the page, holds results for 30 minutes and shows clickable progress in the sidebar. Search Monitored works through books one at a time.", - "Keep seeding permanently is now Preserve torrents (indexer setting). Chaptarr also turns off seeding limits in Transmission and in qBittorrent 4.1 to 4.5 and 4.6.3 or later, and ratio stop and remove in Deluge and rTorrent. Your Post-Import Category still applies. In Deluge, Chaptarr re-applies unlimited seeding after the label change, which can pause the torrent for a moment; System > Status warns if one doesn't resume, and torrents you paused yourself stay paused. Thanks @jberlyn and @EasyAsABC123.", - "Improved library search results, and adding an author follows your root folder settings more consistently.", - "Chaptarr and LazyLibrarian import lists now have separate audiobook and ebook settings, like Goodreads and Hardcover lists, and every list has new options to add missing authors or formats and to monitor paused authors with books on the list. List searches follow delay profiles, \"Keep listed books monitored\" explains that each sync turns monitoring back on, and a list warns when no format is enabled or a Goodreads fetch fails. Thanks @jordanfelle and @Josh-Archer.", - "New naming tokens: {Smart Narrator}, {First Narrator} and {FullCast}. {Smart Narrator} uses the first value that applies, in your chosen order; by default the production label (GraphicAudio or Dramatized), then Full Cast for three or more narrators, then the narrator names. Formats with stray braces, or multi-part formats that would give every part the same name, can't be saved, and ebook naming previews show ebook details.", - "\"Library covers only\" (Settings > Media Management) keeps covers just for monitored books and books with files, and removes the rest when you save and during regular housekeeping. Use Calculate savings to see how much space you'll save first.", - "PostgreSQL backups (work in progress) include the database; restores apply at the next start and roll back if startup fails, and failed scheduled backups show in System > Status. They need matching pg_dump and pg_restore versions; back up before the first start. Settings Backup now covers delay and release profiles, quality sizes, and indexer, client and interface options; Overwrite lists everything it will delete first, and Merge only adds and fills blanks. Restoring a backup warns that it replaces your settings, including the API key, and that it clears pending import work. Thanks @Josh-Archer.", - "Multiple improvements for mobile users: the format switch has its own row, tap targets are larger, the author's book table now shows Narrator, Position and Rating on phones, and toolbar buttons that don't fit go under More. Mobile support is still a work in progress. Thanks @jberlyn and @bhoffman20, and @nmbrg and @plz12345 for bringing awareness.", - "Changed the messy narrator icon to the simple microphone.", - "Indexer Test checks NFO support and greys out Fetch Narrator Metadata when the indexer lacks it. Searches for books with a pinned narrator put the narrator first.", - "Wanted > Author Requests shows queued author adds and marks any that couldn't be added. Books has an In Library filter.", - "When a download also contains the other format of the book you grabbed, Chaptarr also tries to import it, as long as that format is monitored for the author and the book, the book has no files or other download in progress, and it passes your quality profile and custom formats, all checked before anything is converted. If it can't, the book you grabbed still completes and History says why; if it imports, History shows it under the original grab.", - "Searching more than five books at once from Wanted, Calendar, Books or an author asks first and says how many will run. Retry Match on more than five books asks too." + "Apps connected through Chaptarr's audiobook or ebook address, like Seerr, now see books you already have as complete (100%).", + "For anyone who has turned on Tag Audio Files with Metadata (Settings > Metadata, off by default): audio tags now include the series and its number, and with \"keep in sync\" they update when a book's series changes.", + "Also Embed/Replace Cover Art, for the same users: when Chaptarr writes a file's tags, it also puts in the matched edition's cover, replacing different embedded art (on by default).", + "Also for tag writing: tags aren't written when your files' length differs from the matched edition's by more than 5%, so the wrong book's details don't end up in your files (on by default). With Clean matched tags, M4B conversion keeps the source tags in that case.", + "Retag on the author list follows the Audiobooks or Ebooks tab, and the Retag preview explains which files will be skipped and why." }, Fixed = new List { - "Better protection for your recordings (#286). A hand-picked grab keeps both files when upgrades are off and never replaces a file with a worse one. An automatic import that would replace your file with a different recording type keeps your files and waits for you to confirm in Manual Import. Manual Import shows and sets the recording type, and choosing an audio edition in Edit Book with Automatically Switch Edition off sets it from that edition (three or more narrators count as Full Cast); multi-part replacements keep the old recording until every part arrives, and Replace lists what it will delete. Thanks @SaxxyToo, @jordanfelle and @sebclark.", - "Author delete can remove audiobooks, ebooks or both, and first shows each folder it will delete with its book files, size and other files. Root folders, unavailable roots and folders outside your roots are refused, a folder holding another author's files needs an extra confirmation, and deleting one format keeps the other format's files. Bulk delete can add a list exclusion. Removing a root folder leaves your files on disk, and deleting one Calibre format removes only that format. Configure Chaptarr's Recycling Bin (Settings > Media Management) if you'd like, but always keep backups of data you can't afford to lose. Thanks @benjitobz (PR #134), @jordanfelle and @digitalgp.", - "Downloads still arriving are rechecked until they finish instead of going to Manual Import after a few tries (#319), and a download counts as imported only when every file in the grabbed format is in (#254); ._ files, Thumbs.db and .DS_Store no longer hold it up. A download that doesn't contain what was grabbed stops with a message saying what arrived and isn't failed, blocklisted, re-searched or deleted, and one identical to files you already have stops with \"Already in your library\". Removing a pending release blocklists it only if you choose; pending releases keep their books across restarts, and ones Chaptarr can't place show in the Queue, which also loads faster (#165). Thanks @Randrage, @BassMatt and @jordanfelle.", - "Manual Import skips a file that vanished instead of aborting (#225). Thanks @jordanfelle.", - "Manual Import now imports the files you pick as they are. To convert a blocked download to M4B, select it in Activity > Queue and use Retry Imports.", - "Release matching: a better-fitting book by the same author wins, narrator and series names no longer stand in for the author, and a release isn't mistaken for a pack when its series positions match the book. A track number in a quoted audio file name no longer blocks a match when the title also appears outside the quotes, while a number that points to another book in the series still does. Numbers match whether written as 2 or II, ½ is understood, and number words and a leading The, A or An are recognized for English editions. Emoji no longer break release processing (#116), accented and non-Latin names match better, and file size is the last tie-breaker, with small differences ignored. File import handles split \"Title: Subtitle\" tags, [Kindle Edition] and {Unabridged}, and prefers the monitored edition when an ebook matches two equally. Thanks @jonnotk, @jbob06 (PR #117) and tabby.", - "Place eBooks with Audiobooks no longer moves or renames an ebook when there's no shared destination (#126). Thanks @jbob06 (PR #127).", - "Sync Monitored also applies after a first scan and to single-book requests, and retries within minutes if it fails. Refresh is faster, failed author refreshes retry within minutes (an hour after a rate limit, a not-found or a local error; an author the metadata server refuses outright waits for the next scheduled refresh), and a metadata server outage no longer counts against the author. Thanks @jordanfelle (PR #174) and @JordanFromIT.", - "Series labels, folder tokens and Calibre tags use Goodreads series in a consistent order, {Book SeriesPosition:00} zero-pads series numbers (#72), refreshing one author no longer strips another author's shared-series books, and the Series tab's position sort follows the direction you choose; books without a number come after numbered ones in ascending order. Series changes on the metadata server are still being rolled out and propagated, so series will keep improving as your authors refresh. Thanks @tillkruss, @davidgibbons, @Yoldark34 and @the-wondersmith.", - "A notification set only for On Upgrade now sends (#150), a blank Discord username uses the webhook's name, and Kavita and Synology get the right folder. Thanks @jordanfelle (PR #151) and @rukuh.", - "M4B conversion keeps provider chapters on shares without symlinks, a multi-file conversion checks where the merged file will go before converting (#284), quality and custom formats are checked against the download before converting so a book is never refused because conversion made it smaller, and the conversion queue no longer crashes (#139). Further tweaks to the conversion process. Thanks @tillkruss (PR #316), @bhoffman20 (PR #287), @ArtyParty0848 and @the-wondersmith.", - "Root folder profiles save (#279), new or cloned profiles appear without reloading (#329), Add Series no longer crashes (#317), and Edit Author's audiobook and ebook folder fields show and save the stored folders and ask whether to move the files (#28, #332). Thanks @beardedslav (PR #280), @texas1880, @zenermerps, @elric667, @waden34, @paulrouleau and @sebclark.", - "Generic Books indexers are searched for audiobooks too, searching an author searches each monitored book in its own format's categories (#325), indexer Test refreshes categories, the log explains why a search was skipped, MyAnonaMouse search behavior is improved and its errors show as failures, and when Interactive Search finds nothing, it says whether indexers failed. Thanks @jschuttler-zylio and @zenermerps.", - "Narrator lookups run only for releases that match the book and author, and preferred narrators come from audio editions only. GraphicAudio is shown only for GraphicAudio productions, other dramatized recordings are labeled Full Cast or Dramatized, \"Full Cast\" credits aren't treated as people, and Audible search keeps the real narrator names; production labels are recognized in English for now. File import picks the right recording when a book has solo and full-cast editions: one matching narrator plus a matching length is enough, and the edition that accounts for the file's narrators wins. Thanks @JordanFromIT.", - "Interactive Search titles no longer get squeezed (#69, #297), Enter confirms a dialog once, Space toggles checkboxes, a book's links open the right format, and author photos show once downloaded, your picks stick and failures show the placeholder. Thanks @brt0wn, @jpdexter101-lang and @jordanfelle.", - "System > Updates says when it can't reach the update server instead of reporting you're up to date, and a manual update check installs updates.", - "Adding an author through the API without a format now uses the root folder's or quality profile's format instead of setting up both, and asks when neither says. Deleting an author that has both formats through the API asks which one, or both.", - "Book lookups from apps connected to Chaptarr's ebook address return ebook results. Thanks @kukitch (#67) and @snapetech (PR #114).", - "Security: a new Allowed Hosts setting (Settings > General > Host) is required when login is disabled for local addresses, and that option now also checks every client address your proxy reports. Login redirects stay on the address you used. Setting up a login for the first time creates a new API key; update it in connected apps. The API can no longer switch login to None or External. Thanks to Nurjaman Shaikh for reporting it.", - "Import lists: list searches and queued author requests respect a format you've paused for an author (Monitor Author's Audiobooks or Monitor Author's eBooks off) unless the list is set to monitor its authors, a specific-book list with search on no longer monitors the new author's whole catalog after the first scan (#159), and a list can add the missing format to an author you already have (#186). Adding one format clears only that format's list exclusion, authors with exclusions in both formats no longer fail to add, and queued list requests respect exclusions. A search you start yourself still runs. Thanks @jbob06, @foinse, @PACE-1 and @iain247.", - "Saving an indexer, download client, import list or notification without changes no longer re-tests it or starts a list sync. Releases Chaptarr can't classify show as Unknown instead of Unknown Text and are no longer assumed to be ebooks. Wanted > Cutoff Unmet counts and lists each book once instead of once per file.", - "When the metadata server merges two authors or splits one, your library follows it and History notes the change, and merging two copies of an author no longer fails on a shared Audible ID (#49). Thanks @digitalgp and @sebclark." + "Worked to improve the speed of the book list, its A-Z bar, the author list and Wanted on large libraries. The first start after updating builds new database indexes, which can take a little while on very large libraries. Thanks @elric667 (PR #169).", + "On very large libraries, author and book pages load much faster when many books have no cover yet. Thanks @jordanfelle (PR #237).", + "MyAnonaMouse: Chaptarr picks up MAM's renewed login cookie during its account check (#257), searches send apostrophes as written (#379), unsatisfied-slot protection counts per MAM account, saving the indexer keeps your VIP status and member class, and System > Status says when MAM's account reply can't be read. Thanks @director-mouse (PR #308), @nmbrg and @brandon-billings.", + "Authors waiting on the metadata server are retried less often over time, up to every six hours, instead of every five minutes forever (#359), and cancelling an author's setup now sticks. Thanks @elric667 (PR #368).", + "Author and book photos are kept when a provider fails, a refresh no longer undoes your photo choice, covers follow automatic edition changes, damaged images are refused, and an image host that can't be found is paused instead of being tried for every cover.", + "If you use Calibre, a library that can't be reached is paused, waiting longer each time up to fifteen minutes, and an unusable reply from Calibre is no longer counted as saved.", + "Single sign-on (OIDC) no longer loops back to the login page when Chaptarr's email rules turn an account away (missing, unverified or not allowed); the login page now says why (#340). Thanks @benane and @jtruland (PR #283).", + "PostgreSQL: if your database's ID counters fell behind its records (for example after moving your data over from SQLite), Chaptarr now repairs them at startup instead of failing with duplicate-ID errors. Existing records keep their IDs. Thanks compgeek500.", + "Discord and Slack book-deleted and file-deleted notifications no longer show a stray $ in the title. Thanks Freeman.", + "Hardlinked imports stay shared with your download client. Chaptarr copies a file apart only when it rewrites its tags, which uses extra space for seeded files, and file dates and permissions apply to the shared file. Tags are never written through a symbolic link.", + "Audio tag writes change only what differs and keep your files' own track and disc numbers, also with Scrub. The album comes from the matched edition, and so does the title for single-file books; multi-part books keep their part titles." } } }