diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..3454d63 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,10 @@ +# Everything the build does not need: the image is measured, and a build +# context that carries the test suite and a virtualenv is how it stops being. +* +!pyproject.toml +!uv.lock +!README.md +!LICENSE +!CHANGELOG.md +!pg_partsmith/** +pg_partsmith/**/__pycache__/ diff --git a/.github/dependabot.yml b/.github/dependabot.yml index cb1b013..c46acff 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,18 +1,29 @@ +# What moves under this project without a commit of its own: the base images, +# the actions the workflows run, and the lock file. Each gets one pull request +# a week, so a security rebuild of the image is a merge and a release rather +# than a hunt for which digest to bump. version: 2 updates: - - package-ecosystem: "pip" - directory: "/" + - package-ecosystem: docker + directory: / schedule: - interval: "weekly" - day: "monday" + interval: weekly + labels: [dependencies, image] + + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + labels: [dependencies, ci] groups: - dev-dependencies: - dependency-type: "development" - open-pull-requests-limit: 5 + actions: + patterns: ["*"] - - package-ecosystem: "github-actions" - directory: "/" + - package-ecosystem: uv + directory: / schedule: - interval: "weekly" - day: "monday" - open-pull-requests-limit: 5 + interval: weekly + labels: [dependencies] + groups: + dev: + dependency-type: development diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7af02c8..bf7a52a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,6 +6,16 @@ on: pull_request: branches: [master] +permissions: + contents: read + +# A push to a pull request while the previous run is still going restarts it; +# the old one is answering a question nobody is asking any more. A run on +# master is left to finish: every commit there should end with a verdict. +concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + jobs: lint: name: Lint & type check @@ -13,61 +23,292 @@ jobs: steps: - uses: actions/checkout@v7 - uses: astral-sh/setup-uv@v7 - - run: uv sync --group dev + with: + enable-cache: true + cache-dependency-glob: uv.lock + # A lock file out of step with pyproject.toml fails here, in one line, + # rather than in an image build three jobs away. + - run: uv lock --check + - run: uv sync --frozen --group dev - run: uv run ruff check - run: uv run ruff format --check - run: uv run mypy pg_partsmith + - name: The workflows parse, and their shell steps pass shellcheck + run: docker run --rm -v "$PWD:/repo" -w /repo rhysd/actionlint:1.7.12 -color + - name: Dockerfile lint + run: docker run --rm -v "$PWD:/repo" -w /repo hadolint/hadolint:v2.15.1 hadolint Dockerfile + # The Job and CronJob the running guide shows are what a team pastes into + # a cluster: kubeconform checks them against the API schema, strictly, so + # a misspelt field fails here and not at kubectl apply. + - name: The Kubernetes manifests in the guide validate + run: | + uv run python scripts/k8s_manifests.py docs/guide/running.md manifests + docker run --rm -v "$PWD/manifests:/manifests:ro" ghcr.io/yannh/kubeconform:v0.8.0 -strict -summary /manifests - test-unit: - name: Unit tests (Python ${{ matrix.python-version }}) + # Every direct dependency at the lowest version pyproject.toml admits, on + # the oldest Python. The bounds a library declares are a promise, and this + # is the only job that tests it; everything else runs on the lock file. + test-lowest: + name: Lowest declared dependencies (Python 3.11) needs: lint runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: astral-sh/setup-uv@v7 + with: + python-version: "3.11" + enable-cache: true + cache-dependency-glob: uv.lock + cache-suffix: lowest + - run: uv sync --resolution lowest-direct --no-default-groups --group test --extra cli --extra pydantic-settings + # An old floor on a new transitive dependency deprecates things between + # the two; that is theirs to fail on, not this library's. + - run: uv run --no-sync pytest -W default::DeprecationWarning + + test-unit: + name: Unit tests (${{ matrix.os }}, Python ${{ matrix.python-version }}) + needs: lint + runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: - python-version: ["3.11", "3.12", "3.13"] + os: [ubuntu-latest] + python-version: ["3.11", "3.12", "3.13", "3.14"] + # The other platforms at both ends of the range: the CLI runs + # subprocesses and handles signals differently on each of them. + include: + - { os: windows-latest, python-version: "3.11" } + - { os: windows-latest, python-version: "3.14" } + - { os: macos-latest, python-version: "3.11" } + - { os: macos-latest, python-version: "3.14" } + - { os: ubuntu-24.04-arm, python-version: "3.14" } steps: - uses: actions/checkout@v7 - uses: astral-sh/setup-uv@v7 with: python-version: ${{ matrix.python-version }} - - run: uv sync --group dev --extra pydantic-settings + enable-cache: true + cache-dependency-glob: uv.lock + - run: uv sync --frozen --group dev --extra pydantic-settings - run: uv run pytest -m unit --cov=pg_partsmith --cov-report=xml - uses: codecov/codecov-action@v7 - if: matrix.python-version == '3.11' + if: matrix.os == 'ubuntu-latest' && matrix.python-version == '3.11' with: token: ${{ secrets.CODECOV_TOKEN }} files: coverage.xml continue-on-error: true - test-integration: - name: Integration tests (PostgreSQL ${{ matrix.postgres }}) & coverage gate + # A partition boundary is a moment. The suite runs where the clock is + # furthest from UTC in either direction, so a naive datetime has nowhere + # to hide. + test-unit-far-from-utc: + name: Unit tests (TZ=${{ matrix.tz }}) needs: lint runs-on: ubuntu-latest strategy: fail-fast: false matrix: - postgres: ["15-alpine", "16-alpine", "17-alpine"] + tz: [Pacific/Kiritimati, Etc/GMT+12] + env: + TZ: ${{ matrix.tz }} + steps: + - uses: actions/checkout@v7 + - uses: astral-sh/setup-uv@v7 + with: + python-version: "3.14" + enable-cache: true + cache-dependency-glob: uv.lock + - run: uv sync --frozen --group dev --extra pydantic-settings + - run: uv run pytest -m unit + + test-integration: + name: Integration tests (${{ matrix.name }}) + needs: lint + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + include: + - { name: PostgreSQL 15, os: ubuntu-latest, image: postgres:15-alpine } + - { name: PostgreSQL 16, os: ubuntu-latest, image: postgres:16-alpine } + - { name: PostgreSQL 17, os: ubuntu-latest, image: postgres:17-alpine } + - { name: PostgreSQL 18, os: ubuntu-latest, image: postgres:18-alpine } + - { name: PostgreSQL 17 on arm64, os: ubuntu-24.04-arm, image: postgres:17-alpine } + # The server's clock at UTC+14 and the client's at UTC-12: a bound + # written as a date must mean the same day on both sides. + - name: PostgreSQL 17, server at UTC+14, client at UTC-12 + os: ubuntu-latest + image: postgres:17-alpine + server-tz: Pacific/Kiritimati + client-tz: Etc/GMT+12 + # No Docker on these runners; the action brings a server of its own, + # and the tests that reach into the container skip. + - { name: PostgreSQL 17 on Windows, os: windows-latest, server: "17" } + - { name: PostgreSQL 17 on macOS, os: macos-latest, server: "17" } env: - PG_PARTSMITH_TEST_PG_IMAGE: postgres:${{ matrix.postgres }} + PG_PARTSMITH_TEST_PG_IMAGE: ${{ matrix.image }} + PG_PARTSMITH_TEST_PG_TZ: ${{ matrix.server-tz }} + # An unset matrix value is an empty string here, and an empty TZ is not + # "unset" to everything that reads it; the default is spelled out. + TZ: ${{ matrix.client-tz || 'UTC' }} steps: - uses: actions/checkout@v7 - uses: astral-sh/setup-uv@v7 - - run: uv sync --group dev --extra pydantic-settings + with: + enable-cache: true + cache-dependency-glob: uv.lock + - run: uv sync --frozen --group dev --extra pydantic-settings + - name: A PostgreSQL server of the runner's own + if: matrix.server + id: postgres + uses: ikalnytskyi/action-setup-postgres@v8 + with: + postgres-version: ${{ matrix.server }} + username: partsmith + password: partsmith + database: partsmith # Both suites together: the gate is on the whole library, not on one half of it. - - run: uv run pytest --cov=pg_partsmith --cov-report=xml --cov-fail-under=90 + - name: Both suites, and the coverage gate + if: ${{ !matrix.server }} + run: uv run pytest --cov=pg_partsmith --cov-report=xml --cov-fail-under=90 + - name: The integration suite against the runner's server + if: matrix.server + run: uv run pytest -m integration + env: + PG_PARTSMITH_TEST_DSN: ${{ steps.postgres.outputs.connection-uri }} - uses: codecov/codecov-action@v7 - if: matrix.postgres == '17-alpine' + if: matrix.name == 'PostgreSQL 17' with: token: ${{ secrets.CODECOV_TOKEN }} files: coverage.xml continue-on-error: true + # What PyPI will get, installed from the wheel alone on each platform: the + # entry point, the package data, the extra's dependencies, and the whole + # stack up to the socket. + package: + name: Package (${{ matrix.os }}) + needs: lint + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest, macos-latest] + steps: + - uses: actions/checkout@v7 + - uses: astral-sh/setup-uv@v7 + with: + python-version: "3.14" + - run: uv build + - name: The wheel and the sdist pass the checks PyPI and a reader would make + shell: bash + run: | + uvx twine check --strict dist/* + uvx check-wheel-contents dist/*.whl + - name: Installed from the wheel alone, the command runs here + shell: bash + run: | + uv venv --python 3.14 smoke + if [ "$RUNNER_OS" = Windows ]; then BIN=smoke/Scripts; else BIN=smoke/bin; fi + WHEEL=$("$BIN/python" -c 'import pathlib, sys; print(pathlib.Path(sys.argv[1]).resolve().as_uri())' dist/*.whl) + # The environment directory, not its interpreter: uv resolves that the + # same way on every platform, and Windows spells the interpreter differently. + uv pip install --python smoke "pg-partsmith[cli] @ $WHEEL" + "$BIN/pg-partsmith" --version + "$BIN/pg-partsmith" schema | "$BIN/python" -c 'import json, sys; json.load(sys.stdin)' + # Everything short of a server: the document parses, the driver loads, + # the connection is refused, and that is exit 5 -- not a traceback. + set +e + PYTHONIOENCODING=ascii "$BIN/pg-partsmith" plan -c examples/partitions.minimal.yaml --dsn postgresql://nobody:nobody@127.0.0.1:1/none + rc=$? + set -e + test "$rc" -eq 5 + - name: Without the extra, the command on PATH says what to install + shell: bash + run: | + uv venv --python 3.14 bare + if [ "$RUNNER_OS" = Windows ]; then BIN=bare/Scripts; else BIN=bare/bin; fi + WHEEL=$("$BIN/python" -c 'import pathlib, sys; print(pathlib.Path(sys.argv[1]).resolve().as_uri())' dist/*.whl) + uv pip install --python bare "pg-partsmith @ $WHEEL" + set +e + "$BIN/pg-partsmith" --version 2> bare.err + rc=$? + set -e + test "$rc" -eq 64 + grep -q 'pip install "pg-partsmith\[cli\]"' bare.err + + image: + name: Container image (${{ matrix.os }}) + needs: lint + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + # The release builds both architectures; both are built and run here. + os: [ubuntu-latest, ubuntu-24.04-arm] + steps: + - uses: actions/checkout@v7 + - uses: docker/setup-buildx-action@v3 + - name: Build + uses: docker/build-push-action@v6 + with: + context: . + load: true + tags: pg-partsmith:ci + build-args: VERSION=ci + cache-from: type=gha,scope=${{ runner.arch }} + cache-to: type=gha,mode=max,scope=${{ runner.arch }} + # Size is the first thing a team evaluating this reads, so a regression in + # it is a build failure and not a note in a release. + - name: Size budget + run: | + BYTES=$(docker image inspect pg-partsmith:ci -f '{{.Size}}') + MB=$((BYTES / 1024 / 1024)) + echo "image is ${MB} MB (budget ${IMAGE_SIZE_BUDGET_MB} MB)" + test "$MB" -le "$IMAGE_SIZE_BUDGET_MB" + env: + IMAGE_SIZE_BUDGET_MB: 160 + - uses: astral-sh/setup-uv@v7 + with: + enable-cache: true + cache-dependency-glob: uv.lock + - run: uv sync --frozen --no-default-groups --group test --extra pydantic-settings + # The image as a container, against a database on a network of its own, + # run the way the guides say to: read-only, no capabilities, the + # document mounted, the commands the guides show, the codes they promise. + - name: End to end + run: uv run --no-sync pytest -m e2e + env: + PG_PARTSMITH_E2E_IMAGE: pg-partsmith:ci + # One test builds an image FROM pg-partsmith:ci, which was loaded into + # the daemon; the container builder set up above keeps a store of its + # own and would go to the registry for it. The daemon's builder sees it. + BUILDX_BUILDER: default + - name: Scan + uses: aquasecurity/trivy-action@v0.36.0 + with: + image-ref: pg-partsmith:ci + severity: CRITICAL,HIGH + ignore-unfixed: true + exit-code: "1" + + # A dependency a pull request adds or bumps is looked up before it is + # merged: a known vulnerability or an incompatible license fails the check. + dependency-review: + name: New dependencies carry no known vulnerability + if: github.event_name == 'pull_request' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/dependency-review-action@v5 + with: + fail-on-severity: high + # Sentinel job — use this as the single required status check in branch protection. all-checks-passed: name: All checks passed if: always() - needs: [lint, test-unit, test-integration] + needs: [lint, test-lowest, test-unit, test-unit-far-from-utc, test-integration, package, image, dependency-review] runs-on: ubuntu-latest steps: - name: Check all jobs succeeded diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 0000000..4136d6c --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,36 @@ +name: CodeQL + +# Static analysis of the library and of the workflows themselves, on every +# change and once a week for the queries that were added since. +on: + push: + branches: [master] + pull_request: + branches: [master] + schedule: + - cron: "17 4 * * 1" + +permissions: + contents: read + +jobs: + analyze: + name: Analyze (${{ matrix.language }}) + runs-on: ubuntu-latest + permissions: + security-events: write + actions: read + contents: read + packages: read + strategy: + fail-fast: false + matrix: + language: [python, actions] + steps: + - uses: actions/checkout@v7 + - uses: github/codeql-action/init@v4 + with: + languages: ${{ matrix.language }} + - uses: github/codeql-action/analyze@v4 + with: + category: /language:${{ matrix.language }} diff --git a/.github/workflows/links.yml b/.github/workflows/links.yml new file mode 100644 index 0000000..228cbe2 --- /dev/null +++ b/.github/workflows/links.yml @@ -0,0 +1,29 @@ +name: Links + +# The operator pages point at other projects' documentation, and those move. +# Once a week, every link is asked whether it still answers; a pull request +# is not held up on somebody else's outage. +on: + schedule: + - cron: "23 5 * * 1" + workflow_dispatch: + +permissions: + contents: read + +jobs: + check: + name: Every link in the docs answers + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: lycheeverse/lychee-action@v2 + with: + args: >- + --no-progress + --exclude-all-private + --exclude-path site + README.md CHANGELOG.md CONTRIBUTING.md 'docs/**/*.md' + fail: true + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 813c606..5e5221b 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -10,9 +10,12 @@ on: description: "Release tag to publish (e.g. pg-partsmith-v0.1.0)" required: true +# Each job asks for exactly what it needs; the workflow itself only reads. permissions: contents: read - id-token: write # Trusted Publisher (PyPI OIDC) + +env: + IMAGE: ghcr.io/bedrock-python/pg-partsmith jobs: check: @@ -45,17 +48,224 @@ jobs: fi fi - publish: - name: Build and publish to PyPI + # The image first, on each architecture natively: built, made to say the + # version it is about to be tagged with, scanned, and pushed by digest -- + # untagged, so nothing is visible yet. If any of that fails, PyPI has not + # been touched and there is no half of a release to explain. + image: + name: Build, scan and push the image (${{ matrix.arch }}) needs: check if: needs.check.outputs.tag != '' + runs-on: ${{ matrix.os }} + permissions: + contents: read + packages: write + strategy: + matrix: + include: + - { os: ubuntu-latest, arch: amd64 } + - { os: ubuntu-24.04-arm, arch: arm64 } + outputs: + version: ${{ steps.version.outputs.version }} + minor: ${{ steps.version.outputs.minor }} + steps: + - uses: actions/checkout@v7 + with: + ref: ${{ needs.check.outputs.tag }} + + # The library, the CLI and the image carry the same number, always. It + # comes off the tag here so the label, the tags and `--version` inside the + # container cannot disagree. + - name: Resolve version + id: version + run: | + VERSION="${TAG#pg-partsmith-v}" + echo "version=$VERSION" >> "$GITHUB_OUTPUT" + echo "minor=${VERSION%.*}" >> "$GITHUB_OUTPUT" + env: + TAG: ${{ needs.check.outputs.tag }} + + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Build + uses: docker/build-push-action@v6 + with: + context: . + load: true + tags: pg-partsmith:release + build-args: VERSION=${{ steps.version.outputs.version }} + cache-from: type=gha,scope=${{ runner.arch }} + cache-to: type=gha,mode=max,scope=${{ runner.arch }} + + - name: The image reports the version it is tagged with + run: | + test "$(docker run --rm pg-partsmith:release --version)" = "pg-partsmith ${VERSION}" + env: + VERSION: ${{ steps.version.outputs.version }} + + - name: Scan + uses: aquasecurity/trivy-action@v0.36.0 + with: + image-ref: pg-partsmith:release + severity: CRITICAL,HIGH + ignore-unfixed: true + exit-code: "1" + + # The same build again, from the cache, pushed under its digest alone. An + # SBOM and a build provenance attestation travel with it, so "what is in + # it" and "what built it" are answers in the registry. + - name: Push by digest + id: push + uses: docker/build-push-action@v6 + with: + context: . + build-args: VERSION=${{ steps.version.outputs.version }} + cache-from: type=gha,scope=${{ runner.arch }} + sbom: true + provenance: mode=max + tags: ${{ env.IMAGE }} + outputs: type=image,push-by-digest=true,name-canonical=true,push=true + + - name: Hand the digest on + run: | + mkdir -p "${RUNNER_TEMP}/digests" + touch "${RUNNER_TEMP}/digests/${DIGEST#sha256:}" + env: + DIGEST: ${{ steps.push.outputs.digest }} + - uses: actions/upload-artifact@v7 + with: + name: digest-${{ matrix.arch }} + path: ${{ runner.temp }}/digests/* + if-no-files-found: error + retention-days: 1 + + publish: + name: Publish to PyPI + needs: [check, image] + if: needs.check.outputs.tag != '' runs-on: ubuntu-latest environment: pypi + permissions: + contents: read + id-token: write # Trusted Publisher (PyPI OIDC) steps: - uses: actions/checkout@v7 with: ref: ${{ needs.check.outputs.tag }} - uses: astral-sh/setup-uv@v7 + with: + enable-cache: true + cache-dependency-glob: uv.lock - run: uv build - - run: uv publish + # --check-url: a run repeated after a failure further down skips what is + # already on the index instead of failing on it, and carries on to the tags. + - run: uv publish --check-url https://pypi.org/simple/pg-partsmith/ + + # One index over both architectures' images, under the exact tag and the + # minor one, signed. Never `latest`: a CronJob following it would cross a + # major on its own. + tags: + name: Tag and sign the image + needs: [check, image, publish] + if: needs.check.outputs.tag != '' + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + id-token: write # keyless signing + env: + VERSION: ${{ needs.image.outputs.version }} + MINOR: ${{ needs.image.outputs.minor }} + steps: + - uses: actions/download-artifact@v8 + with: + path: ${{ runner.temp }}/digests + pattern: digest-* + merge-multiple: true + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: The two tags + run: | + cd "${RUNNER_TEMP}/digests" + refs=() + for digest in *; do refs+=("${IMAGE}@sha256:${digest}"); done + docker buildx imagetools create -t "${IMAGE}:${VERSION}" -t "${IMAGE}:${MINOR}" "${refs[@]}" + docker buildx imagetools inspect "${IMAGE}:${VERSION}" + + # Signed keylessly with the workflow's own identity: `cosign verify` can + # then prove the index was built by this repository's release workflow + # on master, and not by anyone holding a leaked token. + - uses: sigstore/cosign-installer@v3 + - name: Sign + run: | + DIGEST="sha256:$(docker buildx imagetools inspect "${IMAGE}:${VERSION}" --raw | sha256sum | cut -d' ' -f1)" + cosign sign --yes "${IMAGE}@${DIGEST}" + + # What a team pulls is checked the way the container guide tells them to check + # it, on both architectures: the signature, the SBOM and the provenance, the + # version inside against the tag, the minor tag against the exact one -- and + # then the end-to-end suite runs against the published image itself. A + # failure here is a red release run to read, not an unpublished image. + verify: + name: The published image, verified (${{ matrix.os }}) + needs: [check, image, tags] + if: needs.check.outputs.tag != '' + runs-on: ${{ matrix.os }} + permissions: + contents: read + packages: read + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, ubuntu-24.04-arm] + env: + VERSION: ${{ needs.image.outputs.version }} + MINOR: ${{ needs.image.outputs.minor }} + steps: + - uses: actions/checkout@v7 + with: + ref: ${{ needs.check.outputs.tag }} + - uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + - name: Pull what was pushed + run: docker pull "${IMAGE}:${VERSION}" + + - uses: sigstore/cosign-installer@v3 + - name: Signed by this repository's release workflow, on master + run: | + cosign verify "${IMAGE}:${VERSION}" \ + --certificate-identity "https://github.com/bedrock-python/pg-partsmith/.github/workflows/publish.yml@refs/heads/master" \ + --certificate-oidc-issuer https://token.actions.githubusercontent.com + + - name: The version inside, the label, the minor tag, the SBOM and the provenance + run: | + test "$(docker run --rm "${IMAGE}:${VERSION}" --version)" = "pg-partsmith ${VERSION}" + test "$(docker image inspect "${IMAGE}:${VERSION}" -f '{{index .Config.Labels "org.opencontainers.image.version"}}')" = "${VERSION}" + test "$(docker buildx imagetools inspect "${IMAGE}:${VERSION}" --raw | sha256sum)" \ + = "$(docker buildx imagetools inspect "${IMAGE}:${MINOR}" --raw | sha256sum)" + docker buildx imagetools inspect "${IMAGE}:${VERSION}" --format '{{json .SBOM}}' | grep -q '"SPDX"' + docker buildx imagetools inspect "${IMAGE}:${VERSION}" --format '{{json .Provenance}}' | grep -q '"SLSA"' + + - uses: astral-sh/setup-uv@v7 + with: + enable-cache: true + cache-dependency-glob: uv.lock + - run: uv sync --frozen --no-default-groups --group test --extra pydantic-settings + - name: End to end, against the published image + run: uv run --no-sync pytest -m e2e + env: + PG_PARTSMITH_E2E_IMAGE: ghcr.io/bedrock-python/pg-partsmith:${{ needs.image.outputs.version }} diff --git a/.hadolint.yaml b/.hadolint.yaml new file mode 100644 index 0000000..26bf03e --- /dev/null +++ b/.hadolint.yaml @@ -0,0 +1,8 @@ +# DL3008: apt versions are not pinned. binutils lives in the build stage, +# which does not ship, and pinning Debian package versions across two +# architectures is upkeep with no image to show for it. +# DL3003: the prune step changes directory inside one RUN on purpose, so the +# paths it deletes read as what they are. +ignored: + - DL3008 + - DL3003 diff --git a/CHANGELOG.md b/CHANGELOG.md index bbe9417..98b9ca8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,312 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## 1.2.0 — a command line, an image, and hooks from a config file + +Everything here is reachable without writing Python: `pg-partsmith` on the command line +or in a container, a document that describes every table a deployment maintains, and +hooks that run a command. Underneath, the library gains what those needed — the +collaborators built once and handed back by name, the document as a model, and a plan +that refuses to be applied under a configuration it was not made from. + +### The plan as an artifact + +`plan()` and `apply()` were always separable and the plan was always a pydantic model, but +nothing checked that the plan handed to `apply()` was the one this configuration produced. +In one process the pair cannot disagree; written to a file by one run and read by another +— which is the whole point of the split — it can. + +- `MaintenancePlan.config_fingerprint` records `TablePartitionConfig.fingerprint`, a digest + of the configuration the plan was made from. `apply()` now refuses a plan made for + another table, and one made under a configuration that has since been edited, with + `PlanConfigMismatchError` and before any DDL runs; `allow_config_drift=True` applies it + as it stands. The identity revalidation each destructive operation already did answers + whether this is still the same *relation*, not whether it is still the same *intent* — a + plan made under `retention_count=12` names exactly the right partitions to expire for a + reason that stopped being true the moment someone wrote `120`. +- `MaintenancePlan.cursors` is typed `dict[str, int]`. Only an integer axis records a + cursor — a time axis is cursored by `generated_at` — and leaving it `Any` meant a plan + written to JSON did not always read back as the plan that was written. +- `validate_plan_for_config(config, plan, *, allow_config_drift=False)` is exported for + anything that pairs a plan with a configuration itself. + +### `PartitionToolkit` + +`PartitionToolkit.from_engine(engine, ...)` in both mirrors builds the repository, the +metadata provider, the lock manager, the service and the maintainer around one engine, and +returns them by name. Three settings live on two objects and have to agree — `marker_prefix` +(one writes the orphan marker, the other looks for it), `ddl_timezone` (one writes naive +boundary literals, the other reads them back, and the two constructors do not even default +to the same value) and `boundary_codec` — and each is now given once. Parts rather than +just a maintainer, so code calling `metadata.is_partition_closed` or `locks.acquire_lock` +directly does not build a second set to keep in step. Construct `PartitionToolkit(...)` +directly to hold parts of your own. + +### A configuration written down + +`PartitionsDocument` describes every table a deployment maintains, and the wiring it +maintains them through, as one validated model — what a ConfigMap, a mounted YAML or a +JSON blob parses into. `document.configs()` yields the `TablePartitionConfig` of each, +`config_for(name)` one by name, and `PartitionToolkit.from_options(engine, document.runtime)` +builds the collaborators the file describes. The library still reads no files and opens no +connections: parsing belongs to whoever owns the format. + +`PartitionTableSpec` is one table's entry, and `PartitionTableSettings` is now that same +model read from the environment rather than a second field list beside it — so a field +added once is available in both. `ToolkitOptions` is the `runtime` section, one field per +keyword of `PartitionToolkit.from_engine`. + +Unknown keys are refused wherever they appear, including in `defaults`, where a typo would +otherwise reach every table at once. A document with no tables, and one relation described +twice, are refused for the same reason: both are silent at 03:00 otherwise. + +### A command line + +`pip install "pg-partsmith[cli]"` installs `pg-partsmith`, which runs the library's +read-only half over a document and a DSN — no Python in the calling application at all. +Three of the four commands issue no DDL, take no lock and fire no hook: + +- `inspect` — the tree that actually exists. +- `plan` — what maintenance would do and why, straight from `MaintenancePlan`. +- `validate` — the document against the catalog. The one that belongs in CI. + +Exit codes are the point of a CLI a CronJob runs, so they are distinguishable: `2` for +drift under `plan --check` (what "maintenance has stopped running" looks like), `3` for +findings that need a person, which outranks drift, `4` configuration, `5` the database, and +`6` for a lock another maintainer holds — ordinary operation, and the first false page +every deployment gets if it is reported as a failure. + +The arguments are typer declarations — every flag typed, the help generated from the same +declarations that parse it, shell completion via `--install-completion`. A usage error exits +`64` (`EX_USAGE`), never the `2` argument parsers default to: `2` is what this tool means +"drift" by, and a CronJob alerting on drift must not page over a typo. + +A stop signal cancels the run rather than killing the process. `SIGTERM` — what a pod is +sent at its deadline — used to end it on the spot, with no `finally`, no line in the log +and, under a command hook, an archiver left running unwatched. Both it and Ctrl+C now take +the path a raised exception takes: the statement is cancelled and rolled back, the lock +released, the engine disposed, a hook's child terminated, and the exit code is `130` or +`143` with a line on stderr saying which. + +`--output json` is the models' own dump under a versioned envelope, `by_alias=True`, so +what comes out of `plan` and what goes into a document are one vocabulary; logs go to +stderr. The connection comes from `--dsn`, then `$PG_PARTSMITH_DSN`, then the document. +`--version` reads `pg_partsmith.__version__`: one number for the library and the CLI. + +`apply` carries maintenance out, and withholds every destructive operation unless +`--allow-destructive` is given — the safe behaviour is the default one rather than a second +mode to remember, and it is what an init container wants. With no `--plan` it plans and +applies under one lock, which is also what finalizes an interrupted `DETACH CONCURRENTLY`. + +`plan --save FILE` writes the artifact between the two halves, and `apply --plan FILE` +reads it back. Both guards from earlier in this release apply to it: a plan made for +another table, or under a configuration that has since been edited, is refused with exit +`4` unless `--allow-config-drift` is passed. + +### Commands around the lifecycle + +`CommandHooks` runs a configured command at each lifecycle phase, handing it the +`PartitionEvent` as JSON on stdin and treating a non-zero exit exactly as a raised +exception. It needed no new context: the event has been one pydantic model for every phase +since 1.1.0, so the payload is a dump of the object a Python hook already +receives. In a document it is a `hooks` section, and it is what makes the destructive half +usable by a team that does not write Python — they own the archiver already, they only +need it invoked at the right moment. + +The commands run only when the run is told to run them (`apply --allow-hooks`), and a +document declaring hooks is refused rather than quietly stripped when it is not: silently +skipping a configured `before_drop` would let an operator read the file, believe their +archiver ran, and be wrong. No sandbox is provided and none is claimed; the container +boundary is the answer if isolation is wanted. + +Both mirrors run the command through one implementation, so it does not depend on the +event loop being able to spawn processes — a hook that works in production works on a +developer's machine too. + +### A block of Python instead of a command + +A hook phase in a document can take a block of Python — inline as `python`, or from a +file as `python_file` relative to the document — evaluated with `event` and `log` in +scope, raising to refuse. `PythonHooks` is the same from code, in both mirrors. + +Every block is compiled when the document is read, and a file-backed one by `validate`: a +`SyntaxError` is a validation error with a line number in it, not something a CronJob +finds at 03:00 after some of the run's DDL has committed. Tracebacks name the phase, or +the file, rather than ``. + +It is behind the same `--allow-hooks` as a command, for the same reason, and no sandbox is +claimed: `exec` with a filtered `__builtins__` is not a security boundary, and the +documentation says so rather than pretending otherwise. + +### What a plan will lock + +Every operation now serializes its `capabilities` — the heaviest lock it takes and on +what, and whether it can run inside a transaction block — and `is_destructive` beside its +fields. They were on the object before and not in the dump, which meant a plan written to +a file lost the one thing a DBA reads before agreeing to a window. Both are computed on +the way out and ignored on the way in, so the round trip holds. `plan --locks` prints the +same for a person. + +There is deliberately no `--sql`. The DDL is built at execution time from decisions only +made then — a concurrent detach falling back to the blocking form, rows moved out of a +DEFAULT partition, an orphan marker cleared — and a rendering without them would be +read as a transcript in exactly the cases a review exists to catch. + +### Monitoring, for free + +`--output metrics` renders any command as Prometheus text exposition for a node_exporter +textfile collector. Most systems that partition PostgreSQL have no monitoring of it at all +— they find out at 03:00, from an insert PostgreSQL rejected — and a CronJob already runs +this on a schedule, so the cheapest monitoring available is for that run to leave a file +behind. + +`plan` emits pending operations by kind and findings by severity, `inspect` the size of the +tree and the age of the oldest orphan, `validate` whether each table still matches its +configuration, and `apply` what it did and what it could not. Every run also stamps +`pg_partsmith_run_timestamp_seconds`, so a textfile nothing refreshed reads as stale rather +than as good news, and a converged table reports zeroes rather than nothing — a missing +series and a zero are different alerts. + +The numbers come off the same envelope the JSON does, so a metric cannot disagree with what +the same run printed. + +### Examples that are tested, and a schema for the editor + +`examples/` holds a minimal document, one with everything in it, an id-partitioned queue, +cold tiering, and three hook scripts — a `pg_dump` before a drop in bash, a webhook after +a create, a `COPY` out before a detach as a Python file. The test suite validates every +document, compiles every hook and syntax-checks every script, so an example that stops +being right fails a build rather than teaching the wrong vocabulary. + +`pg-partsmith schema` prints the document's JSON Schema; with one comment line at the top +of the file, an editor validates keys and completes them. The committed copy is checked +against the generated one. + +### Every way to run it + +A deployment page with a copy-pasteable shape for each harness: plain Docker with host +cron or a systemd timer; Compose as a service you run, as the equivalent of an init +container (`service_completed_successfully`), and on a schedule with a cron sidecar; Swarm +with swarm-cronjob; Kubernetes as a Pod, a Job, a CronJob and an init container, plus the +plan-on-one-day-apply-on-another pair of Jobs and the node_exporter textfile; GitHub +Actions and GitLab CI; and the note that anything which runs a container and reads an +exit code runs this. + +`PG_PARTSMITH_DSN_FILE` reads the connection string from a file — the Docker and Swarm +secrets convention — after `PG_PARTSMITH_DSN` and before the document, so a Compose +stack hands a secret over without a shell wrapper and without it showing in +`docker inspect`. + +### What is inside the image + +The runtime is [distroless](https://github.com/GoogleContainerTools/distroless): glibc, +OpenSSL, CA certificates, a timezone database, and nothing else — no shell, no package +manager, no pip. Python 3.14 and a pruned standard library are copied in from the build +stage, the virtualenv is installed from `uv.lock` with `uv sync --locked` so the image holds +the versions the tests ran against and a stale lock fails the build, compiled extensions +are stripped, bytecode is precompiled, typer's `rich` is left out, and exactly the five +shared libraries the kept extension modules link against come along. There is no Debian +userland to carry: the budget is 160 MB, the image sits well under it, and a start is an +interpreter with nothing to byte-compile. + +Two flags replace the two things a shell wrapper in the image used to do: `--write FILE` +writes any command's output to a file atomically (a node_exporter textfile), and +`apply --ok-if-locked` makes a held lock exit `0` (an init container, which restarts on +anything else). A command hook inside the image is therefore a binary or a Python file +run through `/opt/venv/bin/python`, not a bash script; the docs say so, and say how to +build an image with bash in it in one line. + +Published images carry an SBOM and a SLSA provenance attestation and are signed keylessly +with the release workflow's identity; `cosign verify` is in the docs. Dependabot watches +the base images, the actions and the lock file. + +### Pipelines + +CI caches the uv environment keyed on `uv.lock` and installs with `--frozen`, so a stale +lock fails rather than resolving something else, and `uv lock --check` says so in one +line; a push cancels the run it supersedes; the image build reuses layers across runs. + +The matrix grew in every direction that has produced a bug before. Unit tests run on +Python 3.11 through 3.14 on Linux, at both ends of that range on Windows and macOS, on +arm64, and with the clock at UTC+14 and at UTC-12. The integration suite runs on +PostgreSQL 15 through 18, on arm64, on Windows and macOS against a server the runner +installs itself, and once with the server at UTC+14 and the client at UTC-12. One job +installs every direct dependency at the lowest version `pyproject.toml` admits and runs +both suites on it; it found the declared floors for pydantic and typer below what the code +needs, and they now say what is true. The wheel is built, checked and installed on its own +on all three platforms, and the command is run through to a refused connection. The image +is built and run on both architectures the release publishes. Warnings are errors under +pytest; the workflows go through actionlint and the Dockerfile through hadolint; CodeQL +reads the library and the workflows; a pull request that adds a dependency with a known +vulnerability is refused; and once a week every link in the docs is asked whether it still +answers. + +The image is run end to end, on both architectures: as a container with a read-only root +filesystem, every capability dropped and the document mounted, against a PostgreSQL +container on a network of its own — the commands the guides show, with the codes they +promise. A fresh table drifts and `apply` converges it; `--output json` is the envelope +alone on stdout; `--write` lands a textfile in a volume; the DSN arrives from a mounted +secret; a secret only root can read, a rejected password and a document with hooks but no +`--allow-hooks` each answer with their code and a sentence; `SIGTERM` during a command +hook is exit `143` inside the grace period with the lock released; an overlapping run +stands aside with `6`; `plan --save` in one container is applied by another and refused +once the document changed; an image derived with one `COPY` runs a Python file hook from +inside; and the Compose shape that holds an application until its partitions exist runs +as written. After a release, the same suite runs against the image that was actually +pushed, pulled back on both architectures, once the signature, the SBOM, the provenance, +the version inside and the minor tag have been checked. And the Job and CronJob manifests +the running guide shows go through kubeconform on every pull request, while a unit test +reads every YAML block in the guides and refuses a flag the command does not take. + +The checks paid for themselves before they were merged. The command line no longer dies +on a console that cannot show an em dash: a Windows pipe or a bare POSIX locale gets the +character escaped rather than a traceback. A password the server rejects is exit `5` like +any other database failure, where it used to be a traceback: the driver raises its own +error before SQLAlchemy has one to wrap. A hook command that was stopped mid-run had its +pipes left open, which a long-lived process would have seen as a warning at garbage +collection; they are closed. And `main()` runs its coroutine under a runner with a loop +factory of its own, so a program embedding it next to an event loop of its own finds that +loop where it left it. + +Running the image found two more. `--write` into a directory the container's user cannot +write — a root-owned hostPath is the usual case — was a traceback, and `plan --save` into +one was reported as a database error; both are exit `4` with the path in the message, and +the previous textfile stays where it was. And a Python block hook still running when +`SIGTERM` arrives holds the stop until it returns, because it runs on the loop that +handles the signal; the guides now say so, and that work which can outlast a grace period +belongs in a command hook. + +A read of the whole change before the release found the rest. A run that stopped on a +hook's refusal or a stale plan was a traceback, and is exit `3`; a connection string +SQLAlchemy cannot parse was reported as the database's fault, and is exit `4`; an unknown +`runtime.boundary_codec` and an empty command vector passed `validate` and failed at +`apply`, and are refused where they are written; a command hook on a table partitioned by +a sequence crashed the run building the hook's environment, because a window edge there is +a number; and a bare `pip install pg-partsmith` put a `pg-partsmith` on PATH that died +with a traceback, where it now says what to install and exits `64`. The release itself +would have failed after the PyPI upload, building arm64 on an amd64 machine with nothing +able to run its binaries: the image is now built on each architecture natively, scanned on +each, and finished before anything reaches PyPI. + +### A container image + +`ghcr.io/bedrock-python/pg-partsmith:`, published from the release workflow, so a +Go, Ruby or Node stack runs partition maintenance as a CronJob, a Compose service or an +init container with no Python of its own. The entrypoint is the command itself, it runs as +UID 65532, and the build stage — pip, the build backend, every `__pycache__` — is thrown +away rather than shipped. + +The library, the CLI and the image carry the same number, always; CI refuses to publish an +image whose `--version` disagrees with its tag. Tags are the exact version and a moving +minor, never `latest`: a scheduled job following `latest` would cross a major on its own, +at 02:15, with `DROP` in its hands. The image size is checked against a budget on every +pull request and a regression fails the build. + +The init-container case needs no flag of its own: `apply` without `--allow-destructive` +creates and retires nothing, which is exactly what running maintenance at application +startup should do. The documentation states the grants this thing needs and recommends a +dedicated role, because it issues DDL and nobody should have to guess that. + ## [1.1.0](https://github.com/bedrock-python/pg-partsmith/compare/pg-partsmith-v1.0.0...pg-partsmith-v1.1.0) (2026-09-02) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 60cf7fd..b9b74f3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -64,8 +64,40 @@ make test-integration PG_PARTSMITH_TEST_PG_IMAGE=postgres:15-alpine make test-integration # another server version ``` -CI runs the integration suite on PostgreSQL 15, 16 and 17; the default image is -`postgres:17-alpine`. +CI runs the integration suite on PostgreSQL 15 through 18, on arm64, on Windows and +macOS against a server the runner installs itself, and once with the server's clock at +UTC+14 and the client's at UTC-12. The default image is `postgres:17-alpine`; four +variables steer the session: + +| Variable | What it does | +|---|---| +| `PG_PARTSMITH_TEST_PG_IMAGE` | the container image, when Docker is there | +| `PG_PARTSMITH_TEST_DSN` | any running server instead of a container; the few tests that reach into the container skip | +| `PG_PARTSMITH_TEST_PG_TZ` | the container's default time zone, for a server far from UTC | +| `PG_PARTSMITH_TEST_REDIS_URL` | a running Redis for the lock tests where no container can run; without it, and with a DSN set, they skip | + +Unit tests run on every supported Python on Linux, at both ends of the range on Windows +and macOS, on arm64, and with `TZ` at UTC+14 and UTC-12. One job installs every direct +dependency at the lowest version `pyproject.toml` admits and runs both suites on it; that +is what keeps the declared bounds honest, so raise a bound rather than work around an old +version. Warnings are errors under pytest: a deprecation fails the suite the day it +appears, not the day the removal ships. + +## The image, end to end + +The container image is tested as a container: a read-only root filesystem, every +capability dropped, the document mounted read-only, against a PostgreSQL container on a +network of its own — and the commands are the ones the guides show, with the exit codes +they promise. Docker is required, and the image has to exist: + +```bash +make test-e2e # builds pg-partsmith:local and runs the suite against it +PG_PARTSMITH_E2E_IMAGE=pg-partsmith:ci uv run pytest -m e2e # an image you already have +``` + +Without `PG_PARTSMITH_E2E_IMAGE` the suite skips. CI builds the image and runs it on both +architectures. The Compose test needs the `docker compose` plugin and skips where it is +missing. ## Adding a period strategy @@ -123,7 +155,17 @@ have a sync twin. Releases are cut by [release-please](https://github.com/googleapis/release-please) from the Conventional Commits on `master`: it keeps a release pull request open with the next version and the generated changelog section; merging that PR tags the release, and the publish -workflow builds the package and uploads it to PyPI. +workflow takes it from there, in this order: the image is built, made to say the version, +scanned and pushed by digest on each architecture; the package is uploaded to PyPI; the +two image tags are created over both architectures and signed; and the published image is +pulled back on both architectures and run through the end-to-end suite. Nothing reaches +PyPI unless the image is good, and a run repeated after a failure further down skips what +PyPI already has and carries on. A failure in the last job is a red release run to read, +not an unpublished image. + +The first push creates the `ghcr.io/bedrock-python/pg-partsmith` package private; make it +public in the organisation's package settings once, or every `docker pull` in the guides +is denied. - `feat:` bumps the minor version, `fix:` the patch version, `feat!:` / a `BREAKING CHANGE:` footer bumps the major version (before 1.0 a breaking change bumps the minor version — diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..e21d193 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,116 @@ +# syntax=docker/dockerfile:1 +# +# The image is the product for anyone who is not writing Python: a Go or Ruby +# team runs partition maintenance as a CronJob and never installs this library. +# So it is built the way such a team would judge it -- small, with nothing in +# it that is not needed to run one command and exit. +# +# Two stages. The builder is a full Python image with uv, and everything that +# installs, compiles or strips happens there. The runtime is distroless: glibc, +# OpenSSL, CA certificates, a timezone database, and nothing else -- no shell, +# no package manager, no pip. The interpreter, its standard library and the +# virtualenv are copied over, plus exactly the shared libraries the extension +# modules we keep link against. + +# The base images are written out rather than taken from build arguments: +# Dependabot reads FROM lines, and a rebuild on a base-image fix is what it is for. +FROM ghcr.io/astral-sh/uv:0.12.9 AS uv + +FROM python:3.14-slim-bookworm AS builder + +# binutils for strip; nothing else is installed into the image being built. +RUN apt-get update -qq \ + && apt-get install -y -qq --no-install-recommends binutils >/dev/null \ + && rm -rf /var/lib/apt/lists/* + +COPY --from=uv /uv /bin/uv + +ENV UV_PROJECT_ENVIRONMENT=/opt/venv \ + UV_COMPILE_BYTECODE=1 \ + UV_LINK_MODE=copy \ + UV_PYTHON_DOWNLOADS=never + +WORKDIR /src +COPY pyproject.toml uv.lock README.md LICENSE CHANGELOG.md ./ +COPY pg_partsmith ./pg_partsmith + +# Installed from the lock file and nothing else: the image contains the +# versions the test suite ran against, not whatever the index served today. +# The project itself goes in as a real package, not an editable link to /src, +# and is always rebuilt: the cache keys built wheels by version, and the +# version does not change between two commits of the same release. +RUN --mount=type=cache,target=/root/.cache/uv \ + uv sync --locked --no-dev --no-editable --extra cli --python /usr/local/bin/python3 \ + --reinstall-package pg-partsmith + +# What the runtime image will not have: rich and its dependencies exist for +# typer's coloured --help, which a CronJob log never sees (typer falls back to +# plain help without them). Debug symbols in the compiled extensions +# are most of their size. Then the parts of the standard library nobody runs +# in a container -- the IDE, the GUI toolkit, the test suite, the pager data, +# the base image's own pip, which would otherwise ride along with the standard +# library -- and the extension modules whose libraries the runtime leaves out. +RUN cd /opt/venv/lib/python3.*/site-packages \ + && rm -rf rich rich-*.dist-info pygments pygments-*.dist-info markdown_it markdown_it_py-*.dist-info \ + mdurl mdurl-*.dist-info sqlalchemy/testing greenlet/tests \ + /opt/venv/bin/pygmentize /opt/venv/bin/markdown-it \ + && find /opt/venv -name '*.so' -exec strip --strip-unneeded {} + \ + && find /opt/venv \( -name '*.pyx' -o -name '*.pxd' -o -name '*.c' -o -name '*.h' -o -name '*.pyi' \) -delete \ + && cd /usr/local/lib/python3.* \ + && rm -rf idlelib tkinter turtledemo turtle.py test pydoc_data lib2to3 ensurepip config-3.* \ + site-packages/pip site-packages/pip-*.dist-info site-packages/setuptools* site-packages/wheel* \ + lib-dynload/_tkinter* lib-dynload/_curses* lib-dynload/readline* lib-dynload/_dbm* \ + lib-dynload/_gdbm* lib-dynload/_sqlite3* lib-dynload/_test* lib-dynload/xxlimited* \ + lib-dynload/_ctypes_test* lib-dynload/_xxtestfuzz* lib-dynload/_zstd* \ + && strip --strip-unneeded /usr/local/lib/libpython3.*.so.1.0 lib-dynload/*.so \ + && python3 -m compileall -q -j0 --invalidation-mode unchecked-hash /usr/local/lib/python3.* + +# The shared libraries the kept extension modules need beyond what distroless +# provides (glibc, libgcc, libstdc++, OpenSSL). Staged under the same paths +# they will occupy, so one COPY places them. The multiarch directory comes +# from the interpreter, so the arm64 build stages arm64 libraries. +RUN set -eu \ + && arch="$(python3 -c 'import sysconfig; print(sysconfig.get_config_var("MULTIARCH"))')" \ + && mkdir -p "/staging/usr/lib/${arch}" \ + && for lib in libz.so.1 libbz2.so.1.0 liblzma.so.5 libffi.so.8 libuuid.so.1; do \ + cp "/usr/lib/${arch}/${lib}" "/staging/usr/lib/${arch}/"; \ + done + + +FROM gcr.io/distroless/cc-debian12:nonroot AS runtime + +ARG VERSION=0.0.0 +LABEL org.opencontainers.image.title="pg-partsmith" \ + org.opencontainers.image.description="PostgreSQL partition lifecycle management with a plan you can read before it runs" \ + org.opencontainers.image.version="${VERSION}" \ + org.opencontainers.image.source="https://github.com/bedrock-python/pg-partsmith" \ + org.opencontainers.image.documentation="https://bedrock-python.github.io/pg-partsmith/guide/cli/" \ + org.opencontainers.image.licenses="Apache-2.0" \ + org.opencontainers.image.base.name="gcr.io/distroless/cc-debian12:nonroot" + +COPY --from=builder /staging/ / +COPY --from=builder /usr/local/bin/python3* /usr/local/bin/ +COPY --from=builder /usr/local/lib/libpython3*.so.1.0 /usr/local/lib/ +COPY --from=builder /usr/local/lib/python3.14 /usr/local/lib/python3.14 +COPY --from=builder /opt/venv /opt/venv + +# TYPER_USE_RICH=0: typer assumes rich is installed unless told otherwise, and +# rich is one of the things this image leaves out. Plain --help is what a +# CronJob log shows anyway. +ENV PATH="/opt/venv/bin:/usr/local/bin:${PATH}" \ + PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + PYTHONHOME=/usr/local \ + TYPER_USE_RICH=0 + +# distroless' nonroot is 65532 -- the same fixed UID this image has always +# run as, so a runAsUser that named it keeps naming it. +USER 65532:65532 +WORKDIR /home/nonroot + +# The entrypoint is the command itself, so a Compose service or a CronJob names +# only what it wants done: ["plan", "-c", "/etc/partitions.yaml", "--check"]. +# There is no shell to fall back to; --write and --ok-if-locked cover the two +# things a wrapper used to do. +ENTRYPOINT ["/opt/venv/bin/python", "-m", "pg_partsmith.cli"] +CMD ["--help"] diff --git a/Makefile b/Makefile index 8126fdf..ec11018 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: test test-unit test-integration fmt check build install docs-serve docs-build clean +.PHONY: test test-unit test-integration test-e2e fmt check build install docs-serve docs-build clean install: uv sync --group dev @@ -18,6 +18,10 @@ test-unit: test-integration: uv run --extra pydantic-settings pytest -m integration +test-e2e: + docker build --build-arg VERSION=local -t pg-partsmith:local . + PG_PARTSMITH_E2E_IMAGE=pg-partsmith:local uv run --extra pydantic-settings pytest -m e2e + test: uv run --extra pydantic-settings pytest --cov=pg_partsmith --cov-report=term --cov-fail-under=90 --cov-report=xml:coverage.xml diff --git a/README.md b/README.md index 2af22be..7f5961a 100644 --- a/README.md +++ b/README.md @@ -44,15 +44,26 @@ serialize, filter and apply. No extension, no superuser, no scheduler of its own at their own modulus; partitions the scheme did not produce are reported, never touched; foreign tables are inspected, never dropped - **Async and sync** — `pg_partsmith.aio` on `AsyncEngine`, `pg_partsmith.sync` on `Engine` -- **Hooks, locks, schemas** — six lifecycle hooks; PostgreSQL advisory or Redis locks; - schema-qualified everything -- **Type-safe, tested** — Pydantic models, full mypy, real PostgreSQL 15, 16 and 17 via testcontainers +- **A command line** — `pg-partsmith inspect / plan / validate / apply` over a YAML or + JSON document, with a saved plan as the artifact between plan and apply, and exit codes + a CronJob and a CI step can read +- **A container image** — `ghcr.io/bedrock-python/pg-partsmith`, for stacks with no Python + in them; documented shapes for plain Docker, Compose, Swarm, Kubernetes Pod / Job / + CronJob / init container, CI and systemd +- **Examples that are tested** — every document under `examples/` validates in CI, the hook + scripts parse, and `pg-partsmith schema` gives an editor the JSON Schema +- **Hooks, locks, schemas** — eight lifecycle hooks, in Python or as commands named in a + config file; PostgreSQL advisory or Redis locks; schema-qualified everything +- **Type-safe, tested** — Pydantic models, full mypy, real PostgreSQL 15 through 18 via testcontainers ## Installation ```bash pip install pg-partsmith +# The pg-partsmith command, for a config file and a CronJob instead of Python +pip install "pg-partsmith[cli]" + # With Redis distributed locks pip install "pg-partsmith[redis-locks]" ``` diff --git a/docs/agents.md b/docs/agents.md index 7a328a1..002eb92 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -51,7 +51,45 @@ A configuration is a **scheme** — the shape of the tree, level by level — an each with the reason it is there, plus **findings**: what the planner saw and deliberately did not touch. * `apply()` runs a plan under the table's lock, revalidating every destructive operation - against the catalog first. + against the catalog first, and refusing a plan this configuration did not produce. +* `PartitionToolkit.from_engine(engine, ...)` builds the repository, the metadata provider, + the locks, the service and the maintainer around one engine, giving each setting that + belongs to two of them (`marker_prefix`, `ddl_timezone`, `boundary_codec`) exactly once. +* `pg-partsmith` (extra `cli`) runs `inspect` / `plan` / `validate` / `apply` over a + document and a DSN. The first three issue no DDL; `apply` withholds detaches and drops + unless `--allow-destructive`. `plan --save FILE` writes the artifact `apply --plan FILE` + reads back, and applying it is refused if it was made for another table or under a + configuration that has since changed (`--allow-config-drift` overrides). Exit codes: 0 + nothing pending, 2 drift under `plan --check`, 3 findings or run issues, 4 configuration, + 5 connection, 6 lock held, 64 usage (never the parser's 2, which means drift here), 130 + / 143 stopped by SIGINT / SIGTERM after cleaning up, 1 unexpected. `--output json` is the model dump under a + versioned envelope; `--output metrics` is Prometheus text exposition for a node_exporter + textfile, all gauges, prefixed `pg_partsmith_`; `--write FILE` puts any output in a file + atomically; `plan --locks` prints the heaviest lock each operation takes; + `apply --ok-if-locked` exits 0 on a held lock. There is deliberately no `--sql`. See + `guide/cli.md`. +* `CommandHooks` (both mirrors) runs a configured command per phase with the + `PartitionEvent` as JSON on stdin; a non-zero exit refuses the operation. `PythonHooks` + runs a block of Python per phase with `event` and `log` in scope; raising refuses. In a + document both are the `hooks` section (a command list, or `{python: ...}` / + `{python_file: ...}`), honoured only under `apply --allow-hooks`; every block is compiled + by `validate`. No sandbox is claimed. Hooks never fire during `plan`. See + `guide/hooks-in-config.md`. +* The same CLI ships as `ghcr.io/bedrock-python/pg-partsmith:` with the command + as its entrypoint: distroless, Python 3.14, no shell, no pip, UID 65532, signed, with an + SBOM and provenance; tags are the exact version and a moving minor, never `latest`. See + `guide/container.md` for the image and `guide/running.md` for every harness: plain + Docker, Compose (`docker compose run`, `service_completed_successfully`, a cron + sidecar), Swarm (swarm-cronjob), Kubernetes Pod / Job / CronJob / init container, the + plan-then-apply Jobs, node_exporter textfile, CI, systemd. The DSN can also come from a + secret file via `PG_PARTSMITH_DSN_FILE`. `pg-partsmith schema` prints the document's + JSON Schema; validated examples of every document shape and of hook scripts live under + `examples/` (see `guide/examples.md`). +* `PartitionsDocument` is several tables and their wiring as one validated model — what a + YAML or JSON file parses into. `document.configs()` gives every `TablePartitionConfig`, + `document.config_for(name)` one of them, and + `PartitionToolkit.from_options(engine, document.runtime)` the wiring. The library parses + no files: hand it `yaml.safe_load(...)` / `json.loads(...)` output. * `maintain()` is both under one lock, and is what a scheduled tick calls. Two kinds of level: @@ -230,7 +268,7 @@ Every method takes the `TablePartitionConfig` as its first argument. |---|---|---|---| | `inspect(config)` | no | no | `ActualTree \| None` | | `plan(config, *, mode=PlanMode.MAINTAIN, now=None, windows=None)` | no | no | `MaintenancePlan` | -| `apply(config, plan, *, continue_on_error=False)` | **yes** | yes | `MaintenanceResult` | +| `apply(config, plan, *, continue_on_error=False, allow_config_drift=False)` | **yes** | yes | `MaintenanceResult` | | `maintain(config, *, skip_create=False, skip_detach=False, skip_drop=False, continue_on_error=False)` | **yes** | yes | `MaintenanceResult` | | `reconcile(config)` | no | yes | `MaintenanceResult` | | `ensure_partition(config, period_or_window_or_position)` | no | yes | `PartitionInfo \| None` | @@ -250,9 +288,21 @@ raises and reports the failure on `result.error` instead, which is what a schedu `EXPLICIT` (only the windows named in `windows=`). On a `MaintenancePlan`: `.operations`, `.findings`, `.cursors`, `.generated_at`, -`.creates` / `.attaches` / `.detaches` / `.drops`, `.is_noop`, `.only(*kinds)`, -`.without(*kinds)`, `.describe()`. Filtering a plan and applying the rest is supported and -is how you split creation from pruning across schedules. +`.config_fingerprint`, `.creates` / `.attaches` / `.detaches` / `.drops`, `.is_noop`, +`.only(*kinds)`, `.without(*kinds)`, `.describe()`. Filtering a plan and applying the rest +is supported and is how you split creation from pruning across schedules. + +Every operation dumps its `capabilities` (the heaviest lock it takes, and whether it can +run in a transaction block) and `is_destructive` beside its fields; both are computed on the +way out and ignored on the way in, so the round trip holds. + +Serialize a plan with `model_dump_json(by_alias=True)` — the same vocabulary a +configuration uses (`kind`, `method`, `schema`) — and read it back with +`MaintenancePlan.model_validate_json`. `apply()` refuses a plan made for another table, or +one whose `config_fingerprint` no longer matches `config.fingerprint`, with +`PlanConfigMismatchError`; pass `allow_config_drift=True` to apply it anyway. OID +revalidation asks whether this is still the same relation, the fingerprint whether it is +still the same intent. Results: @@ -373,6 +423,7 @@ for issue in result.issues: # non-fatal, but they are why nothin `InvalidPartitionConfigError` (the config does not match the table), `LockAcquisitionError` (another maintainer holds the lock), `PlanStaleError`, +`PlanConfigMismatchError` (the plan was not made from this configuration), `PartitionTopologyError`, `PartitionReferencedError` (a detach PostgreSQL refused because rows still reference the partition), `RowMoveRefusedError` (a row move an incoming foreign key's `ON DELETE` action would corrupt), `PartitionAlreadyExistsError`, diff --git a/docs/concepts/execution.md b/docs/concepts/execution.md index 2900ee6..6966455 100644 --- a/docs/concepts/execution.md +++ b/docs/concepts/execution.md @@ -138,7 +138,7 @@ one of a small number of states, each of which the next run converges: ## Hooks -Six hooks fire around create, detach and drop, once per **lifecycle unit** — the partition +Eight hooks fire around create, attach, detach and drop, once per **lifecycle unit** — the partition under the root, never per leaf of its subtree — and once per member of a root `HASH` or `LIST`. A `before_*` hook that raises aborts that operation (the partition comes back on the next run); an `after_*` hook that raises is logged and re-raised — the operation has diff --git a/docs/concepts/plan.md b/docs/concepts/plan.md index 6b02647..9a352fa 100644 --- a/docs/concepts/plan.md +++ b/docs/concepts/plan.md @@ -96,7 +96,33 @@ detached this run cannot be dropped this run. The `skip_create` / `skip_detach` The JSON form is what a CLI, a dashboard or an audit log would store. A plan carries the instant it was made (`generated_at`), the cursors it was made against, every operation -with its bounds and reason, and every finding. +with its bounds and reason, every finding, and `config_fingerprint` — a digest of the +configuration it was planned under. + +## Applying a plan that was written down + +`apply()` refuses a plan it was not handed the configuration for: one made for another +table, or one made before the policy was edited. Both raise `PlanConfigMismatchError` +before any DDL runs. + +```python +plan = await service.plan(config) +Path("plan.json").write_text(plan.model_dump_json(by_alias=True)) # zero DDL, review it + +restored = MaintenancePlan.model_validate_json(Path("plan.json").read_text()) +await service.apply(config, restored) # refused if config has moved +await service.apply(config, restored, allow_config_drift=True) # take it as it stands +``` + +The two guards answer different questions and neither replaces the other. Revalidation +against the catalog — done for every destructive operation, always — asks whether the +relation the plan named is still *the same relation*. The fingerprint asks whether the +plan is still *the same intent*: a plan made under `retention_count=12` names exactly the +right partitions to expire, for a reason that stopped being true when someone wrote `120`. + +Serialize with `by_alias=True`. That is the form the configuration vocabulary uses — +`kind`, `method`, `schema` — and the form the documentation describes; both forms read +back, but only one of them matches a config file written by hand. ## Convergence rules diff --git a/docs/getting-started/first-table.md b/docs/getting-started/first-table.md index 826f624..bfce24f 100644 --- a/docs/getting-started/first-table.md +++ b/docs/getting-started/first-table.md @@ -91,6 +91,33 @@ the same table. ) ``` +Spelling the three out is worth doing once, because they are what everything else in +this library is made of. From here on, `PartitionToolkit.from_engine(engine)` builds +exactly this set and hands it back by name — `kit.repo`, `kit.metadata`, `kit.locks`, +`kit.service`, `kit.maintainer`: + +=== "asyncio" + + ```python + from pg_partsmith.aio import PartitionToolkit + + kit = PartitionToolkit.from_engine(engine) + service = kit.service + ``` + +=== "sync" + + ```python + from pg_partsmith.sync import PartitionToolkit + + kit = PartitionToolkit.from_engine(engine) + service = kit.service + ``` + +Use it wherever you would otherwise pass `marker_prefix`, `ddl_timezone` or +`boundary_codec`: each of those belongs to two objects at once, and the toolkit takes it +once instead of leaving you to keep two constructors in step. + ## 4. Look before you leap `plan()` reads the catalog and decides what to do. It issues no DDL and takes no lock, so diff --git a/docs/getting-started/installation.md b/docs/getting-started/installation.md index 0dbebcd..5f8be6c 100644 --- a/docs/getting-started/installation.md +++ b/docs/getting-started/installation.md @@ -18,6 +18,7 @@ pip install pg-partsmith Extras: ```bash +pip install "pg-partsmith[cli]" # the pg-partsmith command pip install "pg-partsmith[redis-locks]" # Redis distributed locks pip install "pg-partsmith[pydantic-settings]" # configuration from environment variables ``` diff --git a/docs/guide/cli.md b/docs/guide/cli.md new file mode 100644 index 0000000..5cba1af --- /dev/null +++ b/docs/guide/cli.md @@ -0,0 +1,306 @@ +# The command line + +```bash +pip install "pg-partsmith[cli]" +``` + +`pg-partsmith` runs partition maintenance over a +[configuration document](../reference/document.md) and a DSN — no Python in your +application, no import, no dependency on this library at all. + +```bash +pg-partsmith validate -c partitions.yaml # does the document match the database? +pg-partsmith inspect -c partitions.yaml # what tree actually exists? +pg-partsmith plan -c partitions.yaml # what would maintenance do, and why? +pg-partsmith apply -c partitions.yaml # do it — creations only, by default +``` + +The first three issue no DDL, take no lock and fire no hook. `apply` is the one that +acts. + +## Every flag + +| Command | Flags | +|---|---| +| all four | `-c/--config FILE` (required), `--dsn`, `--table NAME` (repeatable), `-o/--output human\|json\|metrics`, `--write FILE` (the output, into a file, atomically), `-v/--verbose` | +| `plan` | `--check` exit `2` on pending operations · `--save FILE` write the plan · `--locks` print what each operation locks | +| `apply` | `--plan FILE` apply a saved plan · `--allow-destructive` detach and drop too · `--continue-on-error` isolate a failed operation · `--allow-config-drift` apply a plan whose document changed · `--allow-hooks` run the document's hooks · `--ok-if-locked` exit `0` rather than `6` on a held lock | +| `schema` | no flags: prints the document's JSON Schema for an editor | +| global | `--version` · `--install-completion` · `--show-completion` · `-h/--help` on anything | + +`--help` on any command is generated from the same declarations that parse it, so the +table above can be stale and the help cannot. + +## Being stopped + +Ctrl+C, or the `SIGTERM` a pod is sent at its deadline, cancels the run rather than +killing the process. The statement in flight is cancelled by the driver and its +transaction rolled back, the table's lock is released, the engine is disposed, a hook's +child process is terminated, and the exit code says which signal it was: `130` or `143`. +One line on stderr says the same in words. + +What a stopped run leaves behind is what the library promises for any cancellation: at +most a detached, unattached table (attach is the last step of a creation) or a marked, +half-detached partition, and the next run converges both. + +A block of Python in a hook cannot be interrupted mid-way — the signal is honoured the +moment the block returns. A command can, and is. + +## Shell completion + +```bash +pg-partsmith --install-completion # bash, zsh, fish, PowerShell +``` + +`--help` on any command is generated from the same declarations that parse it, so it +cannot drift from what the command accepts. + +## Where the connection comes from + +`--dsn`, then `$PG_PARTSMITH_DSN`, then the file `$PG_PARTSMITH_DSN_FILE` points at, then +the document's `dsn` — in that order, so a mounted ConfigMap can carry the tables while +the password stays in a secret. The file form is for Docker and Swarm secrets, which +arrive as files under `/run/secrets`. + +A DSN naming no driver (`postgresql://…`) is driven with asyncpg, which the `cli` extra +installs. One that names its own (`postgresql+psycopg://…`) is left exactly as written. + +## Exit codes + +A CronJob and a CI step read the exit code and nothing else, so the codes are worth +distinguishing: + +| Code | Meaning | +|---|---| +| 0 | did what it was asked; nothing pending | +| 1 | something unexpected; the message is on stderr | +| 2 | `plan --check` found operations waiting to be applied | +| 3 | the planner reported something a human has to act on | +| 4 | the document does not parse, or does not match the database | +| 5 | the database: unreachable, refused the credentials, or failed a statement | +| 6 | another maintainer holds the table's lock | +| 64 | the invocation itself was wrong: a misspelled flag, no command | +| 130 | stopped by Ctrl+C, after cleaning up | +| 143 | stopped by `SIGTERM`, after cleaning up | + +Three of those deserve their reasoning spelled out. + +**64 is not 2.** Argument parsers exit `2` on a misspelled flag, and `2` is what this tool +means "drift" by. A CronJob alerting on drift must not page over a typo, so a usage error +has the code `sysexits.h` gave it — `EX_USAGE` — and never the parser's default. + +**3 outranks 2.** Drift is what a maintenance run fixes; a finding is what it cannot — +a range overlap, a hash set with a gap no repair is safe for. If both are true, the one +needing a person wins. + +**6 is not a failure.** Two runs overlapping is ordinary operation, and the second one +correctly declining to proceed is the lock doing its job. Alerting on it is the first +false page every deployment gets, so it is its own code rather than a generic error. + +## Watching for maintenance that stopped running + +```bash +pg-partsmith plan -c partitions.yaml --check +``` + +Exits `2` while anything is pending. That is the check to put on a schedule: it says +"partitions that should exist do not yet", without creating anything to find out. + +## In CI + +```yaml +- run: pg-partsmith validate -c partitions.yaml + env: + PG_PARTSMITH_DSN: ${{ secrets.DATABASE_URL }} +``` + +`validate` answers the question a review cannot: the document parses, the connection +works, and every table it describes is partitioned the way it claims — the right method, +on the right key. + +## JSON + +`--output json` on any command. The payload is the library's own model dump under a +versioned envelope, in the vocabulary a configuration file is written in: + +```json +{ + "version": 1, + "command": "plan", + "generated_at": "2026-09-01T12:00:00+00:00", + "tables": [ + { + "table": "public.events", + "plan": { + "table_name": "public.events", + "generated_at": "2026-09-01T12:00:00+00:00", + "config_fingerprint": "8c1d9f0a3b2e4d57", + "operations": [ + {"kind": "create", "target": "public.events__2026_10", "reason": "create_ahead", "…": "…"} + ], + "findings": [] + } + } + ] +} +``` + +It is the dump, never a shape assembled by the CLI — a hand-rolled one drifts from the +library the first time a field is added. Logs go to stderr, so stdout stays parseable. + +## What will it lock + +```bash +pg-partsmith plan -c partitions.yaml --locks +``` + +``` +plan for public.events at 2026-09-01T02:15:00+00:00 + CREATE public.events__2026_10 (create_ahead) + DETACH public.events__2025_08 (retention_expired) size=1073741824 rows~4021553 + DROP public.events__2025_08 (follows_detach) +locks: + CREATE public.events__2026_10 + ACCESS SHARE on the template during CREATE; SHARE UPDATE EXCLUSIVE on the parent and ACCESS EXCLUSIVE on the new partition (and on a DEFAULT sibling) during ATTACH; SHARE ROW EXCLUSIVE on every table referencing the parent through a foreign key + DETACH public.events__2025_08 (outside a transaction block) + SHARE UPDATE EXCLUSIVE on the parent (CONCURRENTLY), ACCESS EXCLUSIVE on the partition and, in the second transaction, on every table referencing the parent through a foreign key; ... + DROP public.events__2025_08 + ACCESS EXCLUSIVE on the dropped table only +``` + +The heaviest lock each operation takes, and on what, as measured on PostgreSQL 15 and 17 +— the thing a DBA reads before agreeing to a window. An operation that cannot run inside a +transaction block is marked, because it is the one a crash leaves half-done and the next +run completes. The JSON carries the same under each operation's `capabilities`, and +`is_destructive` beside it, whether or not `--locks` was asked for; a saved plan is +therefore reviewable for its locks without the CLI. + +**Why there is no `--sql`.** Printing the statements would be the obvious next thing, and +it is deliberately not offered. The DDL is built at execution time from decisions that are +only made then — whether a `DETACH CONCURRENTLY` has to fall back to the blocking form +because a DEFAULT sibling exists, how rows a DEFAULT partition holds for a new window get +moved, which orphan marker gets cleared — and a rendering that left those out would be +read as a transcript in exactly the cases a review exists to catch. The plan is the +contract: what, why, how big, what it locks. + +## Monitoring, for free + +`--output metrics` renders the same run as Prometheus text exposition, for a node_exporter +textfile collector: + +```bash +pg-partsmith plan -c partitions.yaml --output metrics --write /var/lib/node_exporter/textfile/partsmith.prom +``` + +`--write` writes next to the target and renames, so the collector never reads half a +file; a shell redirect would leave that to luck. + +``` +# HELP pg_partsmith_pending_operations Operations a maintenance run would carry out. +# TYPE pg_partsmith_pending_operations gauge +pg_partsmith_pending_operations{table="public.events",kind="create"} 2 +pg_partsmith_pending_operations{table="public.events",kind="drop"} 0 +# HELP pg_partsmith_findings What the planner saw and left alone. A warning needs a person. +# TYPE pg_partsmith_findings gauge +pg_partsmith_findings{table="public.events",severity="warning"} 0 +``` + +Every command emits something: + +| Command | Series | +|---|---| +| `plan` | `pending_operations{table,kind}`, `pending_relations{table}`, `findings{table,severity}` | +| `inspect` | `partitioned{table}`, `partitions{table}`, `detached_partitions{table}`, `oldest_detached_age_seconds{table}` | +| `validate` | `config_valid{table}` | +| `apply` | `applied_operations{table,operation}`, `issues{table}` | + +All prefixed `pg_partsmith_`, all gauges — a one-shot job cannot own a counter, since the +next run is a new process with no memory of this one. Every run also emits +`pg_partsmith_run_timestamp_seconds{command}`, so a textfile nothing has refreshed is +visible as stale rather than as good news. + +A converged table reports zeroes rather than nothing: a missing series and a zero are +different alerts. + +The numbers are read off the same envelope the JSON is, so a metric cannot disagree with +what the same run printed. + +Three alerts worth having, in the order they will save you: + +- `pg_partsmith_pending_operations` above zero for longer than your schedule — maintenance + has stopped running, and inserts will start being rejected. +- `pg_partsmith_findings{severity="warning"}` above zero — something needs a person. +- `time() - pg_partsmith_run_timestamp_seconds` above a couple of intervals — the job + itself is not running, which no other metric here can tell you. + +## One table at a time + +`--table events` (or `--table public.events`), repeatable. A name that no table in the +document answers to is an error naming the ones that do, rather than a silent run over +nothing. + +## Applying + +```bash +pg-partsmith apply -c partitions.yaml # create what is missing +pg-partsmith apply -c partitions.yaml --allow-destructive # …and retire what expired +``` + +**Destructive operations are withheld unless you ask for them.** Without +`--allow-destructive`, `apply` creates and re-attaches, and detaches and drops nothing. +That is deliberate: the safe behaviour is the default one rather than a second mode +somebody has to remember to select, and it is exactly what an init container wants — +create the partitions the application is about to write into, retire nothing at startup. + +With no `--plan`, planning and applying happen under one lock, which is also what +completes an interrupted `DETACH … CONCURRENTLY` before the rest of the run is decided. + +`--continue-on-error` isolates a failed operation into the run's issues instead of +aborting: a failed create still lets pruning run, a failed detach still lets existing +orphans be dropped. Any issue makes the command exit `3`. + +## The plan as an artifact + +The reason to trust an external tool with `DROP` is that you can read what it will do +first: + +```bash +pg-partsmith plan -c partitions.yaml --save plan.json # zero DDL +# read it, diff it, gate it on a human or a CI approval +pg-partsmith apply -c partitions.yaml --plan plan.json --allow-destructive +``` + +`--save` writes the same JSON envelope `--output json` prints, whatever format the +terminal was given. `apply --plan` reads it back and applies exactly that. + +Two things are checked before anything runs, by the library rather than by the CLI: + +- **The plan must be for this table.** A plan for `public.events` applied under the + configuration of `public.audit` is refused. +- **The configuration must not have moved.** The plan records a fingerprint of the + configuration it was made under; if the document has been edited since, applying it is + refused with exit `4`. `--allow-config-drift` applies it as it stands. + +That second one is not the same as the OID revalidation every destructive operation +already does. Revalidation asks whether the relation is still the same relation. The +fingerprint asks whether the plan is still the same intent: a plan made under +`retention_count: 12` names exactly the right partitions to expire, for a reason that +stopped being true the moment someone wrote `120`. + +## Commands around the lifecycle + +A document can name a command, or a block of Python, to run before a drop, after a +create, and at six other moments. They fire during `apply` only, and only with +`--allow-hooks` — see [Commands around the lifecycle](hooks-in-config.md). + +## In a container, on a schedule, in CI + +The same commands, with nothing installed: `ghcr.io/bedrock-python/pg-partsmith:1.2`. +[The container image](container.md) is about the image; [Ways to run it](running.md) is +every harness — plain Docker, Compose, Swarm, a Pod, a Job, a CronJob, an init +container, CI, systemd — with a copy-pasteable shape for each. + +## What is not here yet + +`partition_data` and `unpartition` — the batched row-movement verbs — are library-only for +now, because both want a progress story a one-shot command does not have yet. diff --git a/docs/guide/container.md b/docs/guide/container.md new file mode 100644 index 0000000..39de74e --- /dev/null +++ b/docs/guide/container.md @@ -0,0 +1,191 @@ +# The container image + +``` +ghcr.io/bedrock-python/pg-partsmith:1.2 +``` + +The image is [the CLI](cli.md) and nothing else: the entrypoint is `pg-partsmith`, so a +Compose service, a Swarm task or a Kubernetes Job names only what it wants done. Every +way of running it — plain Docker, Compose, Swarm, a Pod, a Job, a CronJob, an init +container, CI — is on [Ways to run it](running.md); this page is about the image itself. + +```bash +docker run --rm \ + -v "$PWD/partitions.yaml:/etc/partitions.yaml:ro" \ + -e PG_PARTSMITH_DSN=postgresql://app:secret@db.internal/app \ + ghcr.io/bedrock-python/pg-partsmith:1.2 \ + plan -c /etc/partitions.yaml --check +``` + +## What is inside + +Two stages, and only the second one ships. + +The runtime base is [distroless](https://github.com/GoogleContainerTools/distroless) +`cc-debian12`: glibc, OpenSSL, CA certificates, a timezone database, and nothing else. +**No shell, no package manager, no pip.** Onto that go a Python 3.14 interpreter with a +pruned standard library (no IDE, no Tk, no test suite, no REPL modules), one virtualenv +installed from `uv.lock` — the versions the test suite ran against, never whatever the +index served on build day — and exactly the five shared libraries the extension modules +still link against. Compiled extensions are stripped of debug symbols; bytecode is +precompiled, so a start skips it. typer's `rich` is left out: `--help` is plain text, +which is what a CronJob log shows anyway. + +It runs as UID 65532, distroless' `nonroot` — a fixed high UID so a `runAsUser` can +name the same one and a mounted document can be made readable to it without guessing. It +writes nothing at runtime, so `readOnlyRootFilesystem: true` works; give `plan --save` and +`--write` a volume that UID can write. A hostPath directory is root's, and one the +container cannot write is exit `4` with the path in the message. + +Because there is no shell, the two things a wrapper used to do are flags: +`--write FILE` puts any command's output in a file atomically (a node_exporter +textfile), and `apply --ok-if-locked` makes a held lock exit `0` (an init container). A +command hook inside this image is a binary, or a Python file run as +`["/opt/venv/bin/python", "/opt/hooks/export.py"]` — not a shell script. A team that +needs bash in the image builds one line of its own: `FROM python:3.14-slim` and +`pip install "pg-partsmith[cli]"`. + +## Inputs + +| Input | How | +|---|---| +| the document | mounted at any path, given with `-c`; read-only is fine | +| the connection string | `--dsn`, or `PG_PARTSMITH_DSN`, or `PG_PARTSMITH_DSN_FILE` pointing at a mounted secret, or the document's `dsn` — in that order | +| which tables | `--table`, repeatable; every table in the document otherwise | +| hook commands | must be *in* the image or mounted into it; see [hooks in a cluster](running.md#hooks-in-a-cluster) | + +`PG_PARTSMITH_DSN_FILE` exists for Docker and Swarm secrets, which arrive as files under +`/run/secrets`: naming the file is how the DSN gets in without a shell wrapper and +without appearing in `docker inspect`. + +## What this container can do to your database + +It issues DDL. Say that plainly to whoever approves the deployment, and give it a role of +its own rather than the application's: + +```sql +CREATE ROLE partsmith LOGIN PASSWORD '…'; + +-- Enough to create partitions in the schema and attach them +GRANT USAGE, CREATE ON SCHEMA public TO partsmith; + +-- Enough to detach and drop them: PostgreSQL requires ownership of both the +-- partition and the parent for ATTACH/DETACH, so the role owns the tables it +-- maintains, or is a member of the role that does. +ALTER TABLE public.events OWNER TO partsmith; +-- or: GRANT app_owner TO partsmith; +``` + +The minimum is narrower for the read-only commands: `inspect`, `plan` and `validate` need +only `USAGE` on the schema, `SELECT` on the catalog (which `PUBLIC` already has), and +`SELECT` on a partition when a retention rule asks a `SqlPredicate` about its rows. A +monitoring-only deployment can run under a role with no write grants at all. + +A deployment that never wants this role to destroy anything can leave +`--allow-destructive` off entirely and let a human run the retention half. + +Two things worth knowing before you point it at production: + +- **`plan` runs SQL you configured.** A `SqlPredicate` in a retention rule is executed + while planning. It is read-only, but it is your statement running with these + credentials. +- **`apply` takes locks.** Every operation in a plan reports the heaviest lock it takes; + `plan --locks` prints it and `plan --output json` carries it per operation under + `capabilities`, which is the thing to read before scheduling a window. + +## When the container is killed + +`activeDeadlineSeconds`, an eviction, a rollout, `docker stop`: the runtime sends +`SIGTERM`, waits a grace period, then `SIGKILL`. + +On `SIGTERM` the run cancels itself cleanly — the statement in flight is cancelled and +rolled back, the advisory lock released, a hook's child process terminated — and exits +`143` with `pg-partsmith: terminated` in the log. That takes a few seconds; Docker's +default grace of ten and Kubernetes' thirty are plenty. + +A Python block hook is the exception. It runs on the loop that handles the signal, so a +block still running at the deadline holds the stop until it returns, and past the grace +period the runtime kills the process — the `SIGKILL` case below. Anything that can take +longer than a grace period belongs in a command hook, which is a child the stop terminates. + +On `SIGKILL` none of that runs, and the database is still fine: a dropped connection makes +PostgreSQL cancel the statement and roll back its transaction, a session-level advisory +lock goes with the session, and an interrupted `DETACH … CONCURRENTLY` leaves the pending +state the next run finalizes first. The difference is only that nothing says so in the log, +and a hook's child process is on its own. + +## Tags + +`1.4.2` is exact and immutable. `1.4` moves within the minor version, which is what a +schedule should follow — base-image security rebuilds reach it without a config change. + +There is deliberately **no `latest`**: a scheduled job following it would cross a major +version on its own, at 02:15, with `DROP` in its hands. + +The library, the CLI and the image carry the same number, always: `pg-partsmith` 1.4.2 on +PyPI, `pg-partsmith --version` → 1.4.2, and `ghcr.io/bedrock-python/pg-partsmith:1.4.2` +containing exactly that. The `org.opencontainers.image.version` label says so too, and CI +refuses to publish an image whose `--version` disagrees with its tag. + +## Size + +The image is checked against a budget in CI and a regression fails the build, because for +anyone not writing Python the size is the first thing they read about this project. There +is no Debian userland to carry: the budget is 160 MB and the image sits well under it (the +CI log prints the exact number for every build). A start is an interpreter with nothing to +byte-compile and little else to load. + +## Supply chain + +- **Locked install.** The builder runs `uv sync --locked` from `uv.lock`; a lock file out + of step with `pyproject.toml` fails the build rather than resolving something else. +- **SBOM and provenance.** Every published image carries an SBOM and a SLSA build + provenance attestation, so "what is in it" and "what built it" are answers the registry + gives. +- **Signed.** Every published image is signed keylessly with the release workflow's own + identity. To check that what you are about to run was built by this repository's + release workflow and not by someone holding a token: + + ```bash + cosign verify ghcr.io/bedrock-python/pg-partsmith:1.2.0 \ + --certificate-identity https://github.com/bedrock-python/pg-partsmith/.github/workflows/publish.yml@refs/heads/master \ + --certificate-oidc-issuer https://token.actions.githubusercontent.com + ``` + + The identity is the release workflow on `master`, exactly: not any workflow in the + repository, and not a branch. + +- **Both architectures.** The release builds amd64 and arm64 each on a machine of its own + kind, scans each, and only then joins them under one tag; CI builds and runs both the + same way, with the same size budget and the same scan. +- **The image before the index.** The release builds, proves and scans the image before + anything is uploaded to PyPI, so a base image that fails the scan on release day stops + the release whole rather than leaving a library with no image to go with it. +- **Verified after publishing.** The release workflow pulls the image it just pushed, on + both architectures, and checks it the way this page tells you to: the signature, the + SBOM and the provenance, `--version` and the label against the tag, the minor tag + against the exact one — and then runs the end-to-end suite against it. +- **Scanned**, on every pull request and every release, with `HIGH` and `CRITICAL` failing + the build. The runtime image holds nothing that is not needed to run one command, which + is most of what keeps that list empty. +- **Kept current.** Dependabot opens a pull request for the base images, the actions and + the lock file, so a base-image security rebuild is a merge and a release. + +## Building it yourself + +```bash +docker build --build-arg VERSION=$(python -c 'import pg_partsmith; print(pg_partsmith.__version__)') -t pg-partsmith:local . +``` + +The [Dockerfile](https://github.com/bedrock-python/pg-partsmith/blob/master/Dockerfile) is +two stages and takes one argument, the version to stamp into the OCI label. A derived +image that adds a hook binary is one `FROM` and one `COPY` — see +[hooks in a cluster](running.md#hooks-in-a-cluster). + +## Exit codes + +The same ones [the CLI](cli.md#exit-codes) documents. `0` nothing pending, `2` drift under +`plan --check`, `3` findings or run issues, `4` configuration, `5` the database, `6` the lock +is held, `64` usage, `130` / `143` stopped by a signal, `1` unexpected. Treat `6` as +success in whatever runs this: two runs overlapping is ordinary, and the second standing +aside is the lock doing its job. diff --git a/docs/guide/examples.md b/docs/guide/examples.md new file mode 100644 index 0000000..1855fd2 --- /dev/null +++ b/docs/guide/examples.md @@ -0,0 +1,99 @@ +# Configuration examples + +Every file under [`examples/`](https://github.com/bedrock-python/pg-partsmith/tree/master/examples) +in the repository is validated by the test suite, so what is there is what the current +release reads. Copy one and edit it; `pg-partsmith validate` tells you the moment it +stops being right. + +| File | What it shows | +|---|---| +| [`partitions.minimal.yaml`](https://github.com/bedrock-python/pg-partsmith/blob/master/examples/partitions.minimal.yaml) | one monthly table, everything else default | +| [`partitions.yaml`](https://github.com/bedrock-python/pg-partsmith/blob/master/examples/partitions.yaml) | the one to copy from: `defaults`, a flat table, a nested `RANGE → HASH` scheme with a composed lifecycle, a `LIST` root, leaves, `runtime`, and hooks of every kind | +| [`partitions.queue.yaml`](https://github.com/bedrock-python/pg-partsmith/blob/master/examples/partitions.queue.yaml) | an id-partitioned queue: integer windows, the cursor off the sequence, `keep_behind` | +| [`partitions.cold-tiering.yaml`](https://github.com/bedrock-python/pg-partsmith/blob/master/examples/partitions.cold-tiering.yaml) | foreign leaves on an archive server | +| [`partitions.schema.json`](https://github.com/bedrock-python/pg-partsmith/blob/master/examples/partitions.schema.json) | the document's JSON Schema, for an editor | +| [`hooks/archive-partition.sh`](https://github.com/bedrock-python/pg-partsmith/blob/master/examples/hooks/archive-partition.sh) | a `before_drop` command: `pg_dump` the partition, refuse the drop if that fails | +| [`hooks/notify.sh`](https://github.com/bedrock-python/pg-partsmith/blob/master/examples/hooks/notify.sh) | an `after_create` command: one line to a webhook | +| [`hooks/export_partition.py`](https://github.com/bedrock-python/pg-partsmith/blob/master/examples/hooks/export_partition.py) | a `before_detach` block of Python from a file: `COPY` the rows out, write a manifest | + +## The shape of a document + +```yaml +version: 1 + +defaults: # every table starts from these; a table naming a key owns it + schema: public + granularity: month + create_ahead_count: 3 + retention_count: 12 + +tables: + - table_name: events # the flat spelling, defaults filled in + partition_column: created_at + + - table_name: telemetry # any other topology is a scheme + scheme: + method: range + key: id + boundaries: { kind: time, granularity: week, codec: uuidv7 } + child: { method: hash, key: tenant_id, modulus: 8 } + lifecycle: + creation: { kind: create_ahead, count: 4 } + retention: + kind: all_of + members: + - { kind: keep_for, age: P90D } + - { kind: sql, sql: "SELECT NOT EXISTS (SELECT 1 FROM {partition} WHERE status = 'pending')" } + detach: concurrent + drop: { kind: drop_after, grace: P7D, when: { kind: unreferenced } } + leaves: { kind: local, tablespace: fast_ssd, storage_parameters: { fillfactor: 70 } } + +runtime: # one key per keyword of PartitionToolkit.from_engine + ddl_timezone: UTC + marker_prefix: acme + +hooks: # honoured only under `apply --allow-hooks` + timeout_seconds: 900 + before_drop: ["/opt/hooks/archive-partition.sh"] + before_detach: { python_file: hooks/export_partition.py } + after_drop: + python: | + log.info("dropped %s (%s)", event.partition.name, event.operation.reason) +``` + +The vocabulary is the library's own: every `kind` and `method` is the discriminator the +pydantic models dump, so `TablePartitionConfig.model_dump(mode="json", by_alias=True)` is +also a valid table entry. The full field list is on +[the configuration document](../reference/document.md) and +[configuration fields](../reference/configuration.md). + +## Editor support + +```bash +pg-partsmith schema > partitions.schema.json +``` + +Then, at the top of the document: + +```yaml +# yaml-language-server: $schema=partitions.schema.json +``` + +VS Code's YAML extension, and anything else speaking the YAML language server, validates +keys and offers completion from it. The committed copy under `examples/` is checked +against the generated one by the test suite, so it is never stale. + +## What `validate` catches, and what it does not + +`validate` parses the document, compiles every hook block (file-backed ones included), +connects, and checks each table against the catalog: partitioned at all, by the method +and on the key the scheme claims. It does not know whether a `SqlPredicate` is sensible or +whether an archive script works — `plan --output json` shows what the policy decided, and +a hook's own tests are the hook's own business. + +## Hooks as scripts + +The two shell scripts and the Python file are meant to be copied and edited; each says at +the top what it needs on `PATH` and in the environment. How a script reads the event, and +what it is allowed to do with it, is on +[Commands around the lifecycle](hooks-in-config.md#writing-the-script). diff --git a/docs/guide/hooks-in-config.md b/docs/guide/hooks-in-config.md new file mode 100644 index 0000000..ba1357e --- /dev/null +++ b/docs/guide/hooks-in-config.md @@ -0,0 +1,237 @@ +# Commands around the lifecycle + +Hooks are where the destructive half of this becomes usable: an operator who cannot run +anything before a `DROP` will not point a scheduled job at production. From +[a document](../reference/document.md), a hook is a command: + +```yaml +hooks: + timeout_seconds: 600 + before_drop: ["/usr/local/bin/archive-partition"] + after_create: ["/usr/local/bin/notify", "--channel", "#dba"] +``` + +```bash +pg-partsmith apply -c partitions.yaml --allow-destructive --allow-hooks +``` + +This is deliberately language-neutral. A Go or Ruby team already owns an archiver; what +they need is for it to be invoked at the right moment with the right metadata, not a +Python snippet. + +## What the command is handed + +The whole event, as JSON, on stdin — the same object a Python hook is given: + +```json +{ + "phase": "before_drop", + "config": { "schema": "public", "table_name": "events" }, + "partition": { "name": "public.events__2025_08", "oid": 40321, "bounds": { "kind": "range" } }, + "window": { "start": "2025-08-01T00:00:00+00:00", "end": "2025-09-01T00:00:00+00:00" }, + "operation": { "kind": "drop", "reason": "grace_elapsed", "size_bytes": 1073741824 } +} +``` + +Plus, for shell scripts that would rather not parse it: `PG_PARTSMITH_PHASE`, +`PG_PARTSMITH_TABLE`, `PG_PARTSMITH_PARTITION`, and `PG_PARTSMITH_WINDOW_START` / +`PG_PARTSMITH_WINDOW_END` when the partition covers a period. The rest of the environment +is inherited, because a hook needs its own credentials and its `PATH`. + +`before_drop` is told the window and the size even though `DETACH` has already cleared the +catalog's record of the bounds: what it gets is the window the planner decided the drop on. + +## Writing the script + +The shipped [`examples/hooks/`](https://github.com/bedrock-python/pg-partsmith/tree/master/examples/hooks) +are the templates: a `pg_dump` before a drop, a webhook after a create, a `COPY` out +before a detach. The pattern is the same in any language: read stdin if you want the whole +event, read the environment if the name is enough, do the thing, exit non-zero to refuse. + +**Bash**, with the environment and nothing else: + +```bash +#!/usr/bin/env bash +set -euo pipefail +cat >/dev/null # the event; not needed here +partition="${PG_PARTSMITH_PARTITION:?}" +pg_dump --format=custom --table="$partition" --file="/archive/${partition//./_}.dump.part" +mv "/archive/${partition//./_}.dump.part" "/archive/${partition//./_}.dump" +``` + +**Bash with `jq`**, when the size or the window matters: + +```bash +event=$(cat) +size=$(jq -r '.operation.size_bytes // 0' <<<"$event") +window_end=$(jq -r '.window.end' <<<"$event") +[ "$size" -gt 10737418240 ] && echo "too big to archive tonight" >&2 && exit 1 +``` + +**Go**, for a team that already has one: + +```go +var event struct { + Phase string `json:"phase"` + Partition struct{ Name string `json:"name"` } `json:"partition"` + Operation struct { + Reason string `json:"reason"` + SizeBytes *int64 `json:"size_bytes"` + } `json:"operation"` +} +if err := json.NewDecoder(os.Stdin).Decode(&event); err != nil { log.Fatal(err) } +if err := archive(event.Partition.Name); err != nil { os.Exit(1) } // refuses the drop +``` + +**Python, as a file** (`python_file: hooks/export_partition.py`): no stdin, no JSON — +`event` is the object itself, `log` is a logger, and `raise` refuses: + +```python +if shutil.which("psql") is None: + raise RuntimeError("psql is not on PATH; refusing to detach without an export") +log.info("exporting %s", event.partition.name) +subprocess.run(["psql", "-c", f"COPY {event.partition.name} TO STDOUT WITH (FORMAT csv)"], stdout=out, check=True) +``` + +Three things every script should get right: + +- **Write to a temporary name and rename.** A run can be stopped mid-hook; the child is + terminated, and a half-written dump under the final name looks finished. +- **Refuse loudly.** Whatever went wrong belongs on stderr: it is carried in the error the + run reports, and it is the only place anyone will look at 03:00. +- **Do not talk to the table being dropped through the same connection pool the run + uses.** The hook is a separate process with its own credentials; `PGHOST`, `PGUSER` + and friends are inherited from the run's environment, so `pg_dump` and `psql` just work. + +## The phases + +`before_create`, `after_create`, `before_attach`, `after_attach`, `before_detach`, +`after_detach`, `before_drop`, `after_drop`. Each takes one command. + +Hooks fire once per **lifecycle unit** — the partition directly under the root — never +once per leaf. For a `RANGE → HASH` table, `before_drop` runs once for the week, not once +per bucket. + +## A non-zero exit is a refusal + +Exactly as a raised exception is for a Python hook: the operation is abandoned and planned +again on the next run. A `before_drop` that exits non-zero leaves the partition detached +and undropped, which is what an archiver saying "not yet" should mean. + +By default one refusal aborts the whole run. `--continue-on-error` isolates it to its own +partition and lets the rest of the table be maintained; the failure comes back in the +run's issues, and the command exits `3`. + +A command that outlives `timeout_seconds` (default 300) is killed, and that counts as a +refusal. There is no "wait forever": a hook that hangs is holding the table's maintenance +lock. A command is also stopped when the run is — Ctrl+C, a pod's `SIGTERM` — with +`terminate` first and `kill` a few seconds later, so nothing it started keeps running +unwatched. + +## Hooks never fire during `plan` + +`plan` issues no DDL and runs no hook. That is what makes a plan safe to compute anywhere, +and it is why the plan/apply split is worth having. + +One honest caveat in the other direction: **`plan` does run SQL you configured.** A +`SqlPredicate` in a retention rule is executed while planning. It is read-only, but it is +your statement, running with the credentials the run holds. + +## Why `--allow-hooks` exists + +Running a document's commands is arbitrary code execution in a process holding DDL +credentials. The honest framing: + +- The document **already** authorises dropping tables. A command in the same file is not a + new privilege boundary, as long as the document comes from the same trust domain as the + DSN. +- That stops being true the moment the document is assembled from somewhere less trusted — + a ConfigMap another team can edit, a templated file, anything user-supplied. + +So commands run only when the run is told to run them, and a document declaring hooks is +**refused** rather than quietly stripped when it is not: silently skipping a configured +`before_drop` would let an operator read the file, believe their archiver ran, and be +wrong. A hardened deployment can leave `--allow-hooks` off and prove nothing was executed. + +There is **no sandbox**, and none is claimed. If you need real isolation, the command is +the answer rather than a restricted namespace: put it in a sidecar or a mounted binary +with its own credentials, and let the container boundary be the boundary. + +## A block of Python instead of a command + +For the Python-adjacent audience, a phase can take a block instead of a binary — the +authentik model: a snippet in the document, evaluated with a prepared namespace when the +moment comes. + +```yaml +hooks: + before_drop: + python: | + if event.operation.size_bytes and event.operation.size_bytes > 10 * 2**30: + log.warning("exporting %s before drop", event.partition.name) + export_to_s3(event.partition.name, event.window) + after_create: + python_file: hooks/notify.py +``` + +The block sees two names: `event`, the same `PartitionEvent` a hook class is handed, and +`log`, a logger named for the phase. Nothing else is injected — a block that needs +`datetime` imports it, the way any Python does. Raising is how a block refuses the +operation, exactly as a non-zero exit is for a command. + +Inline blocks get unreadable past a few lines and lose editor support, so `python_file` +points at a file instead, resolved relative to the document. A file can be tested on its +own. + +**Every block is compiled by `validate`**, and inline ones the moment the document is +read: a `SyntaxError` is a validation error with a line number in it, not something a +CronJob discovers at 03:00 after some of the run's DDL has committed. A missing or broken +`python_file` fails `validate` by name. + +The block runs inline, in the process and on the loop that fires it. That is the same +footing as a hook written as a class, and the same responsibility: a block that blocks, +blocks maintenance — and blocks the stop. `SIGTERM` is handled on that same loop, so a +block still running when a pod's deadline comes is killed with the process rather than +cancelled. Work that can outlast a grace period belongs in a command hook, a child the +stop terminates. + +### What this is not + +A sandbox. `exec` with a filtered `__builtins__` is not a security boundary and is +trivially escaped; documenting one would be worse than not having one. The block runs as +the process runs, with every credential the process holds — which is why it is behind +the same `--allow-hooks` as a command, and why the trust argument above applies to it word +for word. If isolation is what you need, a command hook in a container of its own is the +answer, not a restricted namespace. + +## From Python + +The same class, without a document: + +```python +from pg_partsmith import HookPhase +from pg_partsmith.aio import CommandHooks, PartitionToolkit + +kit = PartitionToolkit.from_engine( + engine, + hooks=[CommandHooks({HookPhase.BEFORE_DROP: ["/usr/local/bin/archive-partition"]})], +) +``` + +`pg_partsmith.sync.CommandHooks` is the same thing on a sync engine. Both run the command +the same way, which does not depend on the event loop being able to spawn processes — so a +hook that works in production works on a developer's machine too. + +`PythonHooks` is the block form, and takes the source per phase: + +```python +from pg_partsmith.aio import PythonHooks + +hooks = PythonHooks({HookPhase.BEFORE_DROP: "log.warning('dropping %s', event.partition.name)"}) +``` + +Every block is compiled when the object is built, so a typo is a `SyntaxError` at wiring +time rather than at the first drop. + +For anything that wants to stay inside Python, write an ordinary hook class instead — see +[Extend the library](extending.md). diff --git a/docs/guide/running.md b/docs/guide/running.md new file mode 100644 index 0000000..00cbfca --- /dev/null +++ b/docs/guide/running.md @@ -0,0 +1,508 @@ +# Ways to run it + +`pg-partsmith` is a process that runs one command and exits with a code. It has no +scheduler of its own, on purpose: cron, a CronJob, a CI schedule or a systemd timer +already exist wherever it will run, and a long-lived daemon holding DDL credentials would +need its own liveness story for no gain. Every scenario below is the same four commands +in a different harness. + +The commands, and which ones change anything: + +| Command | DDL | Lock | Hooks | Typical place | +|---|---|---|---|---| +| `validate` | no | no | no | CI, a pre-deploy check | +| `inspect` | no | no | no | a terminal, a dashboard | +| `plan` | no | no | no | review, monitoring (`--check`, `--output metrics`) | +| `apply` | yes | yes | with `--allow-hooks` | a schedule, an init step | + +`apply` creates and re-attaches by default and retires nothing; `--allow-destructive` +adds detaches and drops. That is the whole difference between "safe at startup" and +"nightly maintenance", and it is one flag. + +Everything reads the same three inputs: a [document](../reference/document.md) (`-c`), +a connection string (`--dsn`, then `$PG_PARTSMITH_DSN`, then `$PG_PARTSMITH_DSN_FILE`, +then the document's `dsn`), and an optional `--table` to narrow the run. The exit codes +are in [the CLI page](cli.md#exit-codes); the ones a harness cares about are `0` +(nothing pending), `2` (drift, under `plan --check`), `3` (a person is needed) and `6` +(another run holds the lock — ordinary, not a failure). + +## On a laptop + +```bash +pip install "pg-partsmith[cli]" +export PG_PARTSMITH_DSN=postgresql://app:secret@localhost/app + +pg-partsmith validate -c partitions.yaml +pg-partsmith plan -c partitions.yaml --locks +pg-partsmith apply -c partitions.yaml --allow-destructive +``` + +The review loop, when the drop is one you want a second pair of eyes on: + +```bash +pg-partsmith plan -c partitions.yaml --save plan.json # zero DDL; read it, diff it +pg-partsmith apply -c partitions.yaml --plan plan.json --allow-destructive +``` + +`apply --plan` is refused if the document was edited in between, so what runs is what +was reviewed. + +## Plain Docker + +```bash +docker run --rm \ + -v "$PWD/partitions.yaml:/etc/partitions.yaml:ro" \ + -e PG_PARTSMITH_DSN=postgresql://app:secret@db.internal/app \ + ghcr.io/bedrock-python/pg-partsmith:1.2 \ + plan -c /etc/partitions.yaml --check +``` + +The image's entrypoint is the command, so everything after the image name is the +command line. The document is mounted read-only; the DSN comes from the environment so +the file can be committed. + +A database on the same host, reachable at `localhost` from the host but not from a +container: `--network host`, or point the DSN at `host.docker.internal`. + +### Host cron + +```cron +15 2 * * * docker run --rm -v /etc/pg-partsmith/partitions.yaml:/etc/partitions.yaml:ro \ + --env-file /etc/pg-partsmith/env ghcr.io/bedrock-python/pg-partsmith:1.2 \ + apply -c /etc/partitions.yaml --allow-destructive >> /var/log/pg-partsmith.log 2>&1 +``` + +Two runs overlapping — a slow night, a shortened interval — are not a problem: the second +finds the table's advisory lock held and exits `6`. + +### systemd timer + +```ini +# /etc/systemd/system/pg-partsmith.service +[Unit] +Description=Partition maintenance +After=docker.service + +[Service] +Type=oneshot +EnvironmentFile=/etc/pg-partsmith/env +ExecStart=/usr/bin/docker run --rm \ + -v /etc/pg-partsmith/partitions.yaml:/etc/partitions.yaml:ro \ + -e PG_PARTSMITH_DSN ghcr.io/bedrock-python/pg-partsmith:1.2 \ + apply -c /etc/partitions.yaml --allow-destructive +SuccessExitStatus=6 +``` + +```ini +# /etc/systemd/system/pg-partsmith.timer +[Timer] +OnCalendar=*-*-* 02:15:00 +Persistent=true + +[Install] +WantedBy=timers.target +``` + +`SuccessExitStatus=6` is the lock-held code; without it a run that correctly stood +aside shows up as a failed unit. `Persistent=true` runs a missed tick at the next boot. + +## Docker Compose + +Three shapes, depending on what should own the timing. + +### A service you run, not one that runs + +```yaml +services: + partition-maintenance: + image: ghcr.io/bedrock-python/pg-partsmith:1.2 + profiles: ["maintenance"] # not started by `docker compose up` + environment: + PG_PARTSMITH_DSN_FILE: /run/secrets/pg_dsn + secrets: [pg_dsn] + volumes: + - ./partitions.yaml:/etc/partitions.yaml:ro + depends_on: + db: { condition: service_healthy } + +secrets: + pg_dsn: + file: ./secrets/pg_dsn +``` + +```bash +docker compose run --rm partition-maintenance plan -c /etc/partitions.yaml +docker compose run --rm partition-maintenance apply -c /etc/partitions.yaml --allow-destructive +``` + +The profile keeps it out of `up`; the secret keeps the DSN out of the file and out of +`docker inspect`. `PG_PARTSMITH_DSN_FILE` is read exactly for this: a secret arrives as a +file under `/run/secrets`, and naming it is how it gets in without a shell wrapper. + +### Before the application starts + +Compose has the equivalent of an init container: + +```yaml +services: + partitions: + image: ghcr.io/bedrock-python/pg-partsmith:1.2 + command: ["apply", "-c", "/etc/partitions.yaml"] # creations only + environment: { PG_PARTSMITH_DSN_FILE: /run/secrets/pg_dsn } + secrets: [pg_dsn] + volumes: ["./partitions.yaml:/etc/partitions.yaml:ro"] + depends_on: + db: { condition: service_healthy } + + app: + image: your/app + depends_on: + partitions: { condition: service_completed_successfully } +``` + +`app` does not start until `partitions` exits `0`. Without `--allow-destructive` that +run creates the partitions the application is about to write into and retires nothing, +which is what running at startup should do. + +### On a schedule, inside Compose + +Compose has no clock. Either the host's cron runs `docker compose run` (above), or a +cron sidecar does — [ofelia](https://github.com/mcuadros/ofelia) reads labels: + +```yaml +services: + scheduler: + image: mcuadros/ofelia:latest + command: daemon --docker + volumes: ["/var/run/docker.sock:/var/run/docker.sock:ro"] + + partition-maintenance: + image: ghcr.io/bedrock-python/pg-partsmith:1.2 + command: ["apply", "-c", "/etc/partitions.yaml", "--allow-destructive"] + environment: { PG_PARTSMITH_DSN_FILE: /run/secrets/pg_dsn } + secrets: [pg_dsn] + volumes: ["./partitions.yaml:/etc/partitions.yaml:ro"] + labels: + ofelia.enabled: "true" + ofelia.job-run.maintenance.schedule: "0 15 2 * * *" +``` + +## Docker Swarm + +A Swarm service is expected to keep running; a one-shot task needs +`--restart-condition none`, and a schedule needs something to create the task — +[swarm-cronjob](https://github.com/crazy-max/swarm-cronjob) does that from labels: + +```yaml +services: + cronjob: + image: crazymax/swarm-cronjob:latest + volumes: ["/var/run/docker.sock:/var/run/docker.sock:ro"] + deploy: + placement: + constraints: [node.role == manager] + + partition-maintenance: + image: ghcr.io/bedrock-python/pg-partsmith:1.2 + command: ["apply", "-c", "/etc/partitions.yaml", "--allow-destructive"] + environment: { PG_PARTSMITH_DSN_FILE: /run/secrets/pg_dsn } + secrets: [pg_dsn] + configs: + - source: partitions + target: /etc/partitions.yaml + deploy: + replicas: 0 + restart_policy: { condition: none } + labels: + swarm.cronjob.enable: "true" + swarm.cronjob.schedule: "0 15 2 * * *" + swarm.cronjob.skip-running: "true" + +configs: + partitions: + file: ./partitions.yaml + +secrets: + pg_dsn: + external: true +``` + +`replicas: 0` until the schedule fires; `skip-running` is the outer half of "two runs +must not overlap", the advisory lock is the inner half. A one-off run by hand: + +```bash +docker service create --name partition-plan --restart-condition none --detach=false \ + --config source=partitions,target=/etc/partitions.yaml --secret pg_dsn \ + -e PG_PARTSMITH_DSN_FILE=/run/secrets/pg_dsn \ + ghcr.io/bedrock-python/pg-partsmith:1.2 plan -c /etc/partitions.yaml --locks +docker service logs partition-plan && docker service rm partition-plan +``` + +## Kubernetes + +The document is a ConfigMap, the DSN a Secret, and the pod runs as the image's own +non-root user. What differs between the shapes is who creates the pod and when. + +```yaml +apiVersion: v1 +kind: ConfigMap +metadata: { name: partition-config } +data: + partitions.yaml: | + defaults: { schema: public, granularity: month, create_ahead_count: 3, retention_count: 12 } + tables: + - { table_name: events, partition_column: created_at } +--- +apiVersion: v1 +kind: Secret +metadata: { name: partsmith-dsn } +stringData: + dsn: postgresql://partsmith:secret@db.internal/app +``` + +The container spec every shape shares: + +```yaml +# anchors are illustrative; paste the block where it is needed +- name: pg-partsmith + image: ghcr.io/bedrock-python/pg-partsmith:1.2 + args: ["plan", "-c", "/etc/partitions.yaml"] + env: + - name: PG_PARTSMITH_DSN + valueFrom: { secretKeyRef: { name: partsmith-dsn, key: dsn } } + volumeMounts: + - { name: config, mountPath: /etc/partitions.yaml, subPath: partitions.yaml, readOnly: true } + securityContext: + runAsNonRoot: true + runAsUser: 65532 + readOnlyRootFilesystem: true + allowPrivilegeEscalation: false + resources: + requests: { cpu: 50m, memory: 128Mi } + limits: { memory: 256Mi } +``` + +`readOnlyRootFilesystem: true` works: the image writes nothing at runtime. Give +`plan --save` and `--write` a mounted volume to write to. + +### A Pod, once, by hand + +```bash +kubectl run partition-plan --rm -it --restart=Never \ + --image=ghcr.io/bedrock-python/pg-partsmith:1.2 \ + --env="PG_PARTSMITH_DSN=$(kubectl get secret partsmith-dsn -o jsonpath='{.data.dsn}' | base64 -d)" \ + --overrides='{"spec":{"containers":[{"name":"pg-partsmith","image":"ghcr.io/bedrock-python/pg-partsmith:1.2","args":["inspect","-c","/etc/partitions.yaml"],"volumeMounts":[{"name":"config","mountPath":"/etc/partitions.yaml","subPath":"partitions.yaml"}]}],"volumes":[{"name":"config","configMap":{"name":"partition-config"}}]}}' +``` + +For a look, not a change: `inspect`, `plan --locks`, `validate`. The exit code comes back +as the pod's. + +### A Job: once, reliably + +```yaml +apiVersion: batch/v1 +kind: Job +metadata: { name: partition-converge } +spec: + backoffLimit: 0 # a failed apply is read by a person, not retried blind + ttlSecondsAfterFinished: 86400 # the log stays a day + activeDeadlineSeconds: 3600 + template: + spec: + restartPolicy: Never + containers: + - name: pg-partsmith + image: ghcr.io/bedrock-python/pg-partsmith:1.2 + args: ["apply", "-c", "/etc/partitions.yaml", "--allow-destructive", "--continue-on-error"] + env: + - { name: PG_PARTSMITH_DSN, valueFrom: { secretKeyRef: { name: partsmith-dsn, key: dsn } } } + volumeMounts: + - { name: config, mountPath: /etc/partitions.yaml, subPath: partitions.yaml, readOnly: true } + volumes: + - { name: config, configMap: { name: partition-config } } +``` + +The first run against a table with years of history, a one-off after a policy change, a +migration step in a pipeline. `backoffLimit: 0` because a retry of a failed `apply` with +no one looking is the wrong reflex — the run is idempotent, so re-running it *after +reading the log* is safe and costs nothing. `activeDeadlineSeconds` sends `SIGTERM`, which +the run [handles](cli.md#being-stopped). + +### A CronJob: the nightly tick + +```yaml +apiVersion: batch/v1 +kind: CronJob +metadata: { name: partition-maintenance } +spec: + schedule: "15 2 * * *" + concurrencyPolicy: Forbid + startingDeadlineSeconds: 3600 + successfulJobsHistoryLimit: 3 + failedJobsHistoryLimit: 5 + jobTemplate: + spec: + backoffLimit: 0 + activeDeadlineSeconds: 3600 + template: + spec: + restartPolicy: Never + containers: + - name: pg-partsmith + image: ghcr.io/bedrock-python/pg-partsmith:1.2 + args: ["apply", "-c", "/etc/partitions.yaml", "--allow-destructive"] + env: + - { name: PG_PARTSMITH_DSN, valueFrom: { secretKeyRef: { name: partsmith-dsn, key: dsn } } } + volumeMounts: + - { name: config, mountPath: /etc/partitions.yaml, subPath: partitions.yaml, readOnly: true } + volumes: + - { name: config, configMap: { name: partition-config } } +``` + +`concurrencyPolicy: Forbid` and the advisory lock answer the same question from two +directions; keep both. `startingDeadlineSeconds` lets a tick that missed its slot (the +controller was down) still run within the hour rather than being skipped. + +How often: often enough that the partitions created ahead outlast the longest gap between +ticks. A converged table costs one catalog round-trip and no DDL, so there is no reason +to be stingy — hourly for daily partitions is normal. + +### An init container: create before the app writes + +```yaml +spec: + initContainers: + - name: partitions + image: ghcr.io/bedrock-python/pg-partsmith:1.2 + args: ["apply", "-c", "/etc/partitions.yaml"] # no --allow-destructive + env: + - { name: PG_PARTSMITH_DSN, valueFrom: { secretKeyRef: { name: partsmith-dsn, key: dsn } } } + volumeMounts: + - { name: config, mountPath: /etc/partitions.yaml, subPath: partitions.yaml, readOnly: true } + containers: + - name: app + image: your/app +``` + +Creations only. Retention at application startup is a bad idea — every replica restart +would be a chance to drop something — and the default is what makes it impossible by +accident. Ten replicas starting at once are fine: nine find the lock held, and with +`--ok-if-locked` that is exit `0` rather than `6` — an init container restarts on anything +non-zero, and standing aside is not a failure: + +```yaml + args: ["apply", "-c", "/etc/partitions.yaml", "--ok-if-locked"] +``` + +### Plan on one day, apply on another + +The artifact between the two halves, in a cluster: a small PVC, a Job that writes, a +person, a Job that reads. + +```yaml +# Job 1 +args: ["plan", "-c", "/etc/partitions.yaml", "--save", "/work/plan.json", "--locks"] +volumeMounts: [{ name: work, mountPath: /work }] +# read it: `plan --output json` in the log, or a second Job with a shell mounting the same +# volume -- the image has no tar, which is what `kubectl cp` needs +# Job 2 +args: ["apply", "-c", "/etc/partitions.yaml", "--plan", "/work/plan.json", "--allow-destructive"] +``` + +`apply --plan` refuses the file if the ConfigMap changed in between, so a document edited +after review does not get the old plan applied under it. + +### Metrics, into a node_exporter textfile + +The textfile collector reads a directory on the node; the run writes into it with +`--write`, which writes next to the target and renames, so the collector never reads +half a file: + +```yaml +args: ["plan", "-c", "/etc/partitions.yaml", "--check", "--output", "metrics", "--write", "/textfile/partsmith.prom"] +volumeMounts: + - { name: textfile, mountPath: /textfile } +volumes: + - { name: textfile, hostPath: { path: /var/lib/node_exporter/textfile, type: Directory } } +``` + +The directory is the node's and usually root's, and this container is not root: make it +writable by UID 65532 on the node, or point `--write` at one that is. A directory it +cannot write is exit `4` with the path in the message, and the previous file stays as it +was. + +A `plan --check` on a schedule of its own is the cheapest monitoring there is: exit `2` +means partitions that should exist do not yet, before an insert finds out. + +### Hooks in a cluster + +A command hook runs *inside* this container, so what it runs has to be in it — and the +image has no shell, so it is a binary or a Python file, not a bash script. Two ways in: + +```dockerfile +FROM ghcr.io/bedrock-python/pg-partsmith:1.2 +COPY --chmod=755 archive-partition /usr/local/bin/archive-partition +``` + +or an init container that copies it into a shared `emptyDir` mounted at `/opt/hooks`. A +Python hook file is run through the image's interpreter: + +```yaml +hooks: + before_drop: ["/opt/venv/bin/python", "/opt/hooks/archive.py"] +``` + +Either way, `apply` needs `--allow-hooks`, and the document declaring hooks is refused +without it — see [Commands around the lifecycle](hooks-in-config.md). The bash scripts +under `examples/hooks/` are for a host that has bash; a team that wants them in the image +builds its own from `python:3.14-slim` with `pip install "pg-partsmith[cli]"`. + +## CI + +`validate` is the check that belongs in a pipeline: the document parses, the connection +works, every table it describes is partitioned the way it claims. + +```yaml +# GitHub Actions +- name: Validate partition config + run: pg-partsmith validate -c partitions.yaml + env: + PG_PARTSMITH_DSN: ${{ secrets.STAGING_DATABASE_URL }} +``` + +```yaml +# GitLab CI +validate-partitions: + image: python:3.14-slim + before_script: + - pip install --quiet "pg-partsmith[cli]==1.2.0" + script: + - pg-partsmith validate -c partitions.yaml + variables: + PG_PARTSMITH_DSN: $STAGING_DATABASE_URL +``` + +GitLab runs `script` through a shell, and the published image has none, so a CI job +installs the package instead. A scheduled pipeline running `plan --check` against +production is the same alert as the CronJob version, from the other side. + +## Any other scheduler + +Airflow's `KubernetesPodOperator` or `DockerOperator`, Argo Workflows, Nomad's periodic +jobs, Dagster, Rundeck: anything that runs a container and reads an exit code runs this. +The contract is the four commands, the three inputs, and the codes — nothing about the +harness is assumed. Treat `6` as success and `2` (under `--check`) as a signal, not a +failure, and the rest maps onto whatever the scheduler calls "failed". + +## Several databases + +One document per database, or one document and a different `--dsn` per run — the +document does not have to carry a DSN at all. Narrow a big document with `--table` when +one table needs a run of its own. + +## What to grant + +See [the image page](container.md#what-this-container-can-do-to-your-database): a role +of its own, `USAGE, CREATE` on the schema for creations, ownership of the parent for +detaches and drops. A monitoring-only deployment (`plan`, `inspect`, `validate`) needs +none of the write grants. diff --git a/docs/index.md b/docs/index.md index 963cdc6..f430f67 100644 --- a/docs/index.md +++ b/docs/index.md @@ -98,7 +98,7 @@ result = await service.apply(config, plan) # takes the table's lock, runs the | | | |---|---| -| Requirements | Python 3.11+, PostgreSQL 15+ (tested on 15, 16 and 17), SQLAlchemy 2 | +| Requirements | Python 3.11+, PostgreSQL 15+ (tested on 15 through 18), SQLAlchemy 2 | | Install | `pip install pg-partsmith` | | Partitioning | `RANGE` over time, encoded keys (UUIDv7, epoch) and integers; `LIST` (static and sliding); `HASH`; nested to any depth | | Lifecycle | create ahead / until a horizon / when the newest partition is full; keep by count, age, distance or predicate; detach, then drop after a grace period | diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 81bbb02..4520729 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -144,6 +144,14 @@ drop_max_retries=3, drop_retry_delay=0.5, drop_max_backoff=300)`. `PostgresMetadataProvider(engine, *, marker_prefix=None, boundary_codec=None, ddl_timezone=None)`. +`PartitionToolkit.from_engine(engine, *, hooks=None, locks=None, marker_prefix=None, +ddl_timezone="UTC", ddl_timeout_seconds=30, boundary_codec=None, lock_prefix="partitioner", +lock_min_interval_seconds=0, drop_allow_unmanaged=False, drop_lock_timeout_ms=3000, +drop_max_retries=3, drop_retry_delay=0.5, drop_max_backoff=300)` builds all of them around +one engine and returns them as `repo` / `metadata` / `locks` / `service` / `maintainer`, +with each shared setting given once. Construct `PartitionToolkit(...)` directly to hold +parts of your own. + `marker_prefix` must be the same on the repository and the provider — the first writes the ownership marker, the second finds it — and `PartitionLifecycleService` refuses a pair that disagrees. The provider's `boundary_codec` and `ddl_timezone` are used by @@ -157,7 +165,10 @@ acquire_min_interval_seconds=0)`. ## Serialization `config.model_dump(mode="json", by_alias=True)` round-trips through -`TablePartitionConfig.model_validate`. Boundaries dump with a `kind` (`time`, `integer`, +`TablePartitionConfig.model_validate`. `config.fingerprint` is a digest of that form, +which is what a plan records in `config_fingerprint` and what `apply()` compares against; +anything excluded from serialization is invisible to it, so two configurations differing +only in a `Callback`'s function share a fingerprint. Boundaries dump with a `kind` (`time`, `integer`, `sequence`), levels with `method` (`range`, `list`, `hash`), policies and predicates with `kind`, leaves with `kind` (`local`, `foreign`). Custom calculators, custom codecs and `Callback` functions are left out. diff --git a/docs/reference/document.md b/docs/reference/document.md new file mode 100644 index 0000000..a3a39cb --- /dev/null +++ b/docs/reference/document.md @@ -0,0 +1,125 @@ +# The configuration document + +`pg_partsmith.PartitionsDocument` is every table a deployment maintains, plus the wiring +it maintains them through, as one validated model. It is what a file — a ConfigMap, a +mounted YAML, a JSON blob — parses into. + +The library reads no files and opens no connections. Parse with whatever owns the format, +validate here: + +```python +import yaml + +from pg_partsmith import PartitionsDocument +from pg_partsmith.aio import PartitionToolkit + +document = PartitionsDocument.model_validate(yaml.safe_load(Path("partitions.yaml").read_text())) +kit = PartitionToolkit.from_options(engine, document.runtime) + +for config in document.configs(): + result = await kit.maintainer.run_maintenance_safe(config) +``` + +```yaml +version: 1 + +defaults: + schema: public + granularity: month + create_ahead_count: 3 + retention_count: 12 + +tables: + - table_name: events + partition_column: created_at + + - table_name: audit + partition_column: logged_at + granularity: day + retention_count: 400 + + - table_name: telemetry + scheme: + method: range + key: created_at + boundaries: { kind: time, granularity: week } + child: { method: hash, key: tenant_id, modulus: 4 } + lifecycle: + creation: { kind: create_ahead, count: 4 } + retention: { kind: keep_for, age: P90D } + drop: { kind: drop_after, grace: P7D } + +runtime: + ddl_timezone: UTC + marker_prefix: acme + drop_lock_timeout_ms: 3000 +``` + +Complete, validated examples — one minimal, one with everything, a queue, cold tiering, +and the hook scripts they name — are on [Configuration examples](../guide/examples.md). + +## Fields + +| Field | Type | Default | Meaning | +|---|---|---|---| +| `version` | `1` | `1` | the document format this file is written in | +| `dsn` | text | — | connection string, for whoever connects; the library never does | +| `defaults` | mapping | `{}` | fields every table starts from | +| `tables` | list | required, at least one | the tables to maintain | +| `runtime` | mapping | library defaults | how the collaborators are wired | +| `hooks` | mapping | — | commands to run around the lifecycle; `apply --allow-hooks` only | + +A table entry takes the same fields as +[`PartitionTableSettings`](settings.md) — the environment and the file are one field list, +not two. `schema` is accepted as a spelling of `schema_name`, because that is what +`TablePartitionConfig` dumps. + +`runtime` takes one key per keyword of `PartitionToolkit.from_engine`: +`marker_prefix`, `ddl_timezone`, `ddl_timeout_seconds`, `boundary_codec` (a name — +`uuidv7`, `epoch_seconds`, `epoch_milliseconds`), `lock_prefix`, +`lock_min_interval_seconds`, `drop_allow_unmanaged`, `drop_lock_timeout_ms`, +`drop_max_retries`, `drop_retry_delay`, `drop_max_backoff`. + +## What is refused + +- **An unknown key**, in a table entry, in `runtime`, or in `defaults`. A misspelled field + in a file nobody reads until 03:00 is a silent policy, not a typo — `granuality: month` + is reported where it is written rather than defaulting the whole document to no calendar. +- **A document with no tables.** Maintaining nothing is a configuration error, not a + successful run that did nothing. +- **One relation described twice.** Two entries for `public.events` would maintain it under + two policies, in an order the file does not make visible. + +## How `defaults` merges + +Key by key, and only at the top level: a table naming a key owns it entirely. A table with +its own `lifecycle` replaces the default `lifecycle` rather than being merged into it — +a half-inherited policy is one nobody can read off the file. + +```yaml +defaults: + retention_count: 12 +tables: + - { table_name: events, partition_column: created_at, granularity: month } # keeps 12 + - { table_name: audit, partition_column: at, granularity: day, retention_count: 400 } +``` + +## Hooks + +`hooks` names a command, or a block of Python (`python`, or `python_file` relative to the +document), to run at each lifecycle moment — see +[Commands around the lifecycle](../guide/hooks-in-config.md). They fire during `apply` +only, and the CLI refuses a document declaring them unless `--allow-hooks` is passed. + +## Building the wiring from it + +`PartitionToolkit.from_options(engine, document.runtime, hooks=[...])` is +`from_engine` with the document's `runtime` section as its keywords, the codec name +resolved to a codec. `document.runtime.to_kwargs()` is those keywords on their own, for +code that builds the parts itself. + +## One table at a time + +`document.config_for("public.events")` returns one table's configuration by the name +PostgreSQL knows it as, and raises `KeyError` naming the tables the document does describe +— which is what a `--table` flag needs. diff --git a/docs/reference/index.md b/docs/reference/index.md index ea73f3d..fd8a8bf 100644 --- a/docs/reference/index.md +++ b/docs/reference/index.md @@ -154,6 +154,7 @@ entities, exceptions and period calculators. - OperationKind - OperationCapabilities - PartitionBy + - validate_plan_for_config ::: pg_partsmith.planner options: @@ -185,6 +186,31 @@ entities, exceptions and period calculators. - hash_keyspace_covered - missing_remainders +### The document + +A deployment's tables and their wiring, written down: what a ConfigMap, a mounted YAML or a +JSON blob parses into, and what the command line reads. + +::: pg_partsmith.document + options: + heading_level: 4 + members: + - PartitionsDocument + - PartitionTableSpec + - ToolkitOptions + - HookOptions + - PythonHook + +### Hook events + +::: pg_partsmith.events + options: + heading_level: 4 + members: + - PartitionEvent + - HookPhase + - hook_environment + ### Exceptions ::: pg_partsmith.exceptions @@ -203,6 +229,7 @@ entities, exceptions and period calculators. - PartitionTopologyError - PartitionReferencedError - PlanStaleError + - PlanConfigMismatchError - RowMoveRefusedError ### Period strategies @@ -294,6 +321,20 @@ Async implementations: service, executor, inspector, repositories, lock managers options: heading_level: 4 +::: pg_partsmith.aio.command_hooks.CommandHooks + options: + heading_level: 4 + +::: pg_partsmith.aio.python_hooks.PythonHooks + options: + heading_level: 4 + +### The toolkit + +::: pg_partsmith.aio.toolkit.PartitionToolkit + options: + heading_level: 4 + --- ## pg_partsmith.sync @@ -344,6 +385,18 @@ built on the sync SQLAlchemy `Engine`. options: heading_level: 4 +::: pg_partsmith.sync.command_hooks.CommandHooks + options: + heading_level: 4 + +::: pg_partsmith.sync.python_hooks.PythonHooks + options: + heading_level: 4 + +::: pg_partsmith.sync.toolkit.PartitionToolkit + options: + heading_level: 4 + --- ## pg_partsmith.settings diff --git a/docs/reference/settings.md b/docs/reference/settings.md index 4524443..95963a7 100644 --- a/docs/reference/settings.md +++ b/docs/reference/settings.md @@ -58,7 +58,10 @@ calculators and custom codecs cannot be expressed in JSON; build those configs i ## Several tables -One subclass per table, each with its own prefix: +A deployment maintaining several tables from a file wants +[the configuration document](document.md): one list of tables, shared `defaults`, and the +same field list as below. From the environment, it is one subclass per table, each with its +own prefix: ```python class EventsSettings(PartitionTableSettings): diff --git a/examples/hooks/archive-partition.sh b/examples/hooks/archive-partition.sh new file mode 100755 index 0000000..4d20876 --- /dev/null +++ b/examples/hooks/archive-partition.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# A before_drop hook: dump the partition somewhere durable, and refuse the +# drop if that did not work. A non-zero exit is how a hook says "not yet". +# +# The whole event arrives as JSON on stdin. The facts a script usually needs +# are also in the environment, so jq is optional: +# PG_PARTSMITH_PHASE before_drop +# PG_PARTSMITH_TABLE public.events +# PG_PARTSMITH_PARTITION public.events__2025_08 +# PG_PARTSMITH_WINDOW_START / _END ISO 8601, when the partition covers a period +# +# Needs: pg_dump on PATH, PGHOST/PGUSER/PGPASSWORD (or a .pgpass) for it, +# and ARCHIVE_DIR writable. Everything else is inherited from the run. +set -euo pipefail + +event=$(cat) # keep it; jq can read the rest from here +partition="${PG_PARTSMITH_PARTITION:?not run as a pg-partsmith hook}" +archive_dir="${ARCHIVE_DIR:-/var/lib/pg-partsmith/archive}" +target="${archive_dir}/${partition//./_}.dump" + +if command -v jq >/dev/null; then + size=$(jq -r '.operation.size_bytes // "unknown"' <<<"$event") + reason=$(jq -r '.operation.reason' <<<"$event") + echo "archiving ${partition} (${size} bytes, ${reason}) to ${target}" +else + echo "archiving ${partition} to ${target}" +fi + +mkdir -p "$archive_dir" +# --table takes the schema-qualified name; -Fc is compressed and restorable +# with pg_restore. Write to a temp name and rename, so a half-written dump is +# never mistaken for a finished one. +pg_dump --format=custom --table="$partition" --file="${target}.part" +mv "${target}.part" "$target" +echo "archived ${partition}: $(wc -c <"$target") bytes" diff --git a/examples/hooks/export_partition.py b/examples/hooks/export_partition.py new file mode 100644 index 0000000..257b052 --- /dev/null +++ b/examples/hooks/export_partition.py @@ -0,0 +1,49 @@ +# A before_detach hook written as a block of Python, referenced from the +# document as `python_file: hooks/export_partition.py`. +# +# Two names are in scope: `event`, the PartitionEvent (the same object a +# hook class is handed), and `log`, a logger named for the phase. Anything +# else is imported, the way any Python is. Raising refuses the operation; +# the partition stays attached and the next run plans it again. +# +# This one copies the partition's rows out with COPY, through psql, into a +# directory an archiver picks up, and records what it did next to the file. +import json +import os +import shutil +import subprocess +from pathlib import Path + +if shutil.which("psql") is None: + msg = "psql is not on PATH; refusing to detach without an export" + raise RuntimeError(msg) + +target_dir = Path(os.environ.get("EXPORT_DIR", "/var/lib/pg-partsmith/export")) +target_dir.mkdir(parents=True, exist_ok=True) +stem = event.partition.name.replace(".", "_") +data = target_dir / f"{stem}.csv" +manifest = target_dir / f"{stem}.json" + +log.info("exporting %s to %s", event.partition.name, data) +with data.open("wb") as out: + subprocess.run( + ["psql", "--no-psqlrc", "--command", f"COPY {event.partition.name} TO STDOUT WITH (FORMAT csv, HEADER)"], + stdout=out, + check=True, + ) + +manifest.write_text( + json.dumps( + { + "table": event.table_name, + "partition": event.partition.name, + "window": None if event.window is None else [event.window.start.isoformat(), event.window.end.isoformat()], + "reason": event.operation.reason.value, + "size_bytes": event.operation.size_bytes, + "rows_estimate": event.operation.row_estimate, + }, + indent=2, + ), + encoding="utf-8", +) +log.info("exported %s: %d bytes", event.partition.name, data.stat().st_size) diff --git a/examples/hooks/notify.sh b/examples/hooks/notify.sh new file mode 100755 index 0000000..292175a --- /dev/null +++ b/examples/hooks/notify.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +# An after_create / before_detach hook: post one line to a webhook. +# Exits non-zero only if the webhook is unreachable -- which, for an +# after_* phase, abandons what is left of the operation and lets the next +# run plan it again. Drop the `-f` if a failed notification should never +# stop maintenance. +set -euo pipefail + +cat >/dev/null # the event on stdin; this one only needs the environment +url="${WEBHOOK_URL:?set WEBHOOK_URL}" +text="pg-partsmith: ${PG_PARTSMITH_PHASE} ${PG_PARTSMITH_PARTITION} (${PG_PARTSMITH_TABLE})" + +curl -fsS -X POST -H 'Content-Type: application/json' \ + --data "{\"text\": \"${text}\"}" "$url" >/dev/null diff --git a/examples/partitions.cold-tiering.yaml b/examples/partitions.cold-tiering.yaml new file mode 100644 index 0000000..88931e2 --- /dev/null +++ b/examples/partitions.cold-tiering.yaml @@ -0,0 +1,21 @@ +# Cold tiering: leaves are foreign tables on an archive server, so old data +# lives elsewhere and PostgreSQL still sees one table. Foreign leaves are +# inspected and retired, never dropped from the archive side. + +tables: + - table_name: metrics + schema: public + partition_column: ts + granularity: month + create_ahead_count: 2 + retention_count: 24 + leaves: + kind: foreign + server: archive + options: + table_name: "{relname}" + schema_name: "{schema}" + +hooks: + # Tell the archive side a partition is about to be retired on this side. + before_detach: ["/opt/hooks/notify.sh"] diff --git a/examples/partitions.minimal.yaml b/examples/partitions.minimal.yaml new file mode 100644 index 0000000..bb06519 --- /dev/null +++ b/examples/partitions.minimal.yaml @@ -0,0 +1,11 @@ +# The ordinary case: one table, partitioned by month on a timestamp, three +# months kept ahead, a year kept behind. Everything else is a default. +# +# pg-partsmith plan -c partitions.minimal.yaml --dsn postgresql://app@localhost/app + +tables: + - table_name: events + partition_column: created_at + granularity: month + create_ahead_count: 3 + retention_count: 12 diff --git a/examples/partitions.queue.yaml b/examples/partitions.queue.yaml new file mode 100644 index 0000000..0760148 --- /dev/null +++ b/examples/partitions.queue.yaml @@ -0,0 +1,18 @@ +# An id-partitioned queue: fixed-width windows over a BIGSERIAL, the cursor +# read off the sequence rather than max(id), twenty windows kept behind the +# cursor and four ahead of it. Time plays no part. + +tables: + - table_name: outbox + schema: app + scheme: + method: range + key: id + boundaries: + kind: integer + step: 1000000 + cursor_source: sequence + lifecycle: + creation: { kind: create_ahead, count: 4 } + retention: { kind: keep_behind, distance: 20 } + drop: { kind: drop_after, grace: PT0S } diff --git a/examples/partitions.schema.json b/examples/partitions.schema.json new file mode 100644 index 0000000..2314705 --- /dev/null +++ b/examples/partitions.schema.json @@ -0,0 +1,570 @@ +{ + "$defs": { + "HookOptions": { + "additionalProperties": false, + "description": "What to run at each lifecycle moment, as a file writes it.\n\nOne field per phase, spelled out rather than a free mapping, so a\nmisspelled ``befor_drop`` is refused where it is written instead of\nsilently never running -- which, for the phase that exports data before a\n``DROP``, is the difference between an archive and no archive.\n\nA phase takes either a command -- an argument vector, never a shell string,\nso a partition name can never be read as syntax -- or a block of Python,\ninline as ``python`` or from a file as ``python_file``.\n\nHooks fire during ``apply`` only. ``plan`` issues no DDL and runs no hook,\nwhich is what makes a plan safe to compute anywhere.", + "properties": { + "timeout_seconds": { + "default": 300.0, + "description": "How long a command may run before it is killed; it holds the table's lock", + "exclusiveMinimum": 0, + "title": "Timeout Seconds", + "type": "number" + }, + "before_create": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, + { + "$ref": "#/$defs/PythonHook" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Before a partition exists", + "title": "Before Create" + }, + "after_create": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, + { + "$ref": "#/$defs/PythonHook" + }, + { + "type": "null" + } + ], + "default": null, + "description": "After it is created and attached", + "title": "After Create" + }, + "before_attach": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, + { + "$ref": "#/$defs/PythonHook" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Before a detached partition returns", + "title": "Before Attach" + }, + "after_attach": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, + { + "$ref": "#/$defs/PythonHook" + }, + { + "type": "null" + } + ], + "default": null, + "description": "After it is taking rows again", + "title": "After Attach" + }, + "before_detach": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, + { + "$ref": "#/$defs/PythonHook" + }, + { + "type": "null" + } + ], + "default": null, + "description": "While its rows are still reachable", + "title": "Before Detach" + }, + "after_detach": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, + { + "$ref": "#/$defs/PythonHook" + }, + { + "type": "null" + } + ], + "default": null, + "description": "After it stands alone", + "title": "After Detach" + }, + "before_drop": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, + { + "$ref": "#/$defs/PythonHook" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The last moment its rows exist", + "title": "Before Drop" + }, + "after_drop": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, + { + "$ref": "#/$defs/PythonHook" + }, + { + "type": "null" + } + ], + "default": null, + "description": "After the table is gone", + "title": "After Drop" + } + }, + "title": "HookOptions", + "type": "object" + }, + "PartitionGranularity": { + "description": "Time-based partition granularity.\n\nAttributes:\n HOUR: Hourly partitions.\n DAY: Daily partitions.\n WEEK: Weekly partitions.\n MONTH: Monthly partitions.\n QUARTER: Quarterly partitions.\n YEAR: Yearly partitions.", + "enum": [ + "hour", + "day", + "week", + "month", + "quarter", + "year" + ], + "title": "PartitionGranularity", + "type": "string" + }, + "PartitionStrategy": { + "description": "What drives a root table's partitions.\n\nDerived from the scheme; accepted as input only to be checked against it.\n\nAttributes:\n TIME_BASED: RANGE over a time axis.\n NUMERIC_BASED: RANGE over an integer axis.\n VALUE_BASED: LIST.\n HASH_BASED: HASH.", + "enum": [ + "time_based", + "numeric_based", + "value_based", + "hash_based" + ], + "title": "PartitionStrategy", + "type": "string" + }, + "PartitionTableSpec": { + "additionalProperties": false, + "description": "One table's entry: a configuration written down rather than constructed.\n\nThe flat fields describe the ordinary time-partitioned table; any other\ntopology is given as ``scheme``, which takes precedence over them;\n``lifecycle`` and ``leaves`` take the same JSON their models dump.\n``PartitionType``, ``PartitionStrategy`` and ``PartitionGranularity`` are\n``StrEnum`` values, so their lowercase spellings are what a file writes.\n\n``schema`` is accepted as a spelling of ``schema_name``, because that is\nwhat :class:`~pg_partsmith.TablePartitionConfig` dumps and what an operator\nwrites.\n\nUnknown keys are refused rather than ignored: a misspelled field in a file\nnobody reads until 03:00 is a silent policy, not a typo.", + "properties": { + "schema_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "PostgreSQL schema (omit for public)", + "title": "Schema Name" + }, + "table_name": { + "description": "Partitioned table name", + "title": "Table Name", + "type": "string" + }, + "partition_type": { + "anyOf": [ + { + "$ref": "#/$defs/PartitionType" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Checked against the scheme: range, list, hash" + }, + "partition_strategy": { + "anyOf": [ + { + "$ref": "#/$defs/PartitionStrategy" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Checked against the scheme: time_based, numeric_based, value_based, hash_based" + }, + "partition_column": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Leading column of a time-partitioned root", + "title": "Partition Column" + }, + "trailing_partition_columns": { + "default": [], + "description": "Rest of a composite partition key, as JSON: [\"tenant_id\"]", + "items": { + "type": "string" + }, + "title": "Trailing Partition Columns", + "type": "array" + }, + "granularity": { + "anyOf": [ + { + "$ref": "#/$defs/PartitionGranularity" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Time granularity: hour, day, week, month, quarter, year" + }, + "tz": { + "default": "UTC", + "description": "IANA timezone the calendar is computed in", + "title": "Tz", + "type": "string" + }, + "boundary_codec": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Physical key encoding by name: uuidv7, epoch_seconds, epoch_milliseconds", + "title": "Boundary Codec" + }, + "create_ahead_count": { + "default": 6, + "description": "Number of periods to ensure exist, including the current period", + "minimum": 1, + "title": "Create Ahead Count", + "type": "integer" + }, + "retention_count": { + "default": 12, + "description": "Number of newest periods to keep, current one included", + "minimum": 1, + "title": "Retention Count", + "type": "integer" + }, + "scheme": { + "anyOf": [ + { + "additionalProperties": true, + "type": "object" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Any topology, as JSON: {\"method\": \"range\", \"key\": \"created_at\", \"boundaries\": {\"kind\": \"time\", \"granularity\": \"week\"}, \"child\": {\"method\": \"hash\", \"key\": \"tenant_id\", \"modulus\": 4}}", + "title": "Scheme" + }, + "lifecycle": { + "anyOf": [ + { + "additionalProperties": true, + "type": "object" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Lifecycle policy, as JSON: {\"creation\": {\"kind\": \"create_ahead\", \"count\": 3}, ...}", + "title": "Lifecycle" + }, + "leaves": { + "anyOf": [ + { + "additionalProperties": true, + "type": "object" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Leaf backend, as JSON: {\"kind\": \"local\", \"tablespace\": \"fast\", \"storage_parameters\": {\"fillfactor\": 70}} or {\"kind\": \"foreign\", \"server\": \"archive\", \"options\": {\"table_name\": \"{relname}\"}}", + "title": "Leaves" + } + }, + "required": [ + "table_name" + ], + "title": "PartitionTableSpec", + "type": "object" + }, + "PartitionType": { + "description": "PostgreSQL partitioning method.\n\nAttributes:\n RANGE: Range partitioning (e.g., by date ranges).\n LIST: List partitioning (e.g., by specific values).\n HASH: Hash partitioning (e.g., by hash of key).", + "enum": [ + "range", + "list", + "hash" + ], + "title": "PartitionType", + "type": "string" + }, + "PythonHook": { + "additionalProperties": false, + "description": "A block of Python to run at one lifecycle moment, inline or from a file.\n\nExactly one of the two. An inline block is compiled the moment the document\nis validated, so a ``SyntaxError`` is a validation error with a line number\nin it rather than something a CronJob finds at 03:00. A file is resolved\nand compiled by whoever reads the document, relative to where the document\nlives, since only they know where that is.\n\nAttributes:\n python: The block itself.\n python_file: A path to it, for blocks past a few lines -- editor\n support, and a file that can be tested on its own.", + "properties": { + "python": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The block, inline", + "title": "Python" + }, + "python_file": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "A path to the block, relative to the document", + "title": "Python File" + } + }, + "title": "PythonHook", + "type": "object" + }, + "ToolkitOptions": { + "additionalProperties": false, + "description": "The wiring every table in the document is maintained through.\n\nOne field per keyword of ``PartitionToolkit.from_engine``, so a document\nconfigures the wiring the way code does. ``boundary_codec`` is a name here\n(``uuidv7``, ``epoch_seconds``, ``epoch_milliseconds``); :meth:`to_kwargs`\nresolves it to the codec itself.", + "properties": { + "marker_prefix": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "COMMENT prefix marking detached partitions as ours", + "title": "Marker Prefix" + }, + "ddl_timezone": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": "UTC", + "description": "Session timezone naive boundary literals are written and read in", + "title": "Ddl Timezone" + }, + "ddl_timeout_seconds": { + "default": 30.0, + "description": "Statement timeout", + "exclusiveMinimum": 0, + "title": "Ddl Timeout Seconds", + "type": "number" + }, + "boundary_codec": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Codec name encoded bounds are read with", + "title": "Boundary Codec" + }, + "lock_prefix": { + "default": "partitioner", + "description": "Prefix of the advisory lock keys", + "title": "Lock Prefix", + "type": "string" + }, + "lock_min_interval_seconds": { + "default": 0.0, + "description": "Minimum seconds between acquire attempts per table; 0 disables", + "minimum": 0, + "title": "Lock Min Interval Seconds", + "type": "number" + }, + "drop_allow_unmanaged": { + "default": false, + "description": "Allow dropping a relation with no ownership marker", + "title": "Drop Allow Unmanaged", + "type": "boolean" + }, + "drop_lock_timeout_ms": { + "default": 3000, + "description": "lock_timeout for a drop", + "minimum": 0, + "title": "Drop Lock Timeout Ms", + "type": "integer" + }, + "drop_max_retries": { + "default": 3, + "description": "Attempts a drop makes", + "minimum": 1, + "title": "Drop Max Retries", + "type": "integer" + }, + "drop_retry_delay": { + "default": 0.5, + "description": "Delay before the retry", + "minimum": 0, + "title": "Drop Retry Delay", + "type": "number" + }, + "drop_max_backoff": { + "default": 300.0, + "description": "Ceiling on that backoff", + "minimum": 0, + "title": "Drop Max Backoff", + "type": "number" + } + }, + "title": "ToolkitOptions", + "type": "object" + } + }, + "additionalProperties": false, + "description": "Every table a deployment maintains, and the wiring it maintains them through.\n\n``defaults`` is merged into each entry of ``tables`` before validation, key\nby key: a table naming a key owns it entirely. The merge is deliberately\nshallow -- a table with its own ``lifecycle`` replaces the default one\nrather than being merged into it, because a half-inherited policy is one\nnobody can read off the file.\n\n``dsn`` is for whoever connects; the library opens no connection of its own,\nand a deployment is free to keep the DSN out of the file entirely.\n\n``hooks`` names commands to run around the lifecycle. They are code this\nfile causes to run in a process holding DDL credentials -- which is not a\nnew privilege boundary, since the same file already authorises dropping\ntables, but it stops being true the moment the document is assembled from\nsomewhere less trusted than the DSN. Whoever runs the document decides\nwhether they are honoured; the CLI refuses to apply a document declaring\nhooks unless it is told to.", + "properties": { + "version": { + "const": 1, + "default": 1, + "description": "Document format version", + "title": "Version", + "type": "integer" + }, + "dsn": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Connection string, when the file carries one", + "title": "Dsn" + }, + "defaults": { + "additionalProperties": true, + "description": "Fields every table starts from", + "title": "Defaults", + "type": "object" + }, + "tables": { + "description": "The tables to maintain", + "items": { + "$ref": "#/$defs/PartitionTableSpec" + }, + "minItems": 1, + "title": "Tables", + "type": "array" + }, + "runtime": { + "$ref": "#/$defs/ToolkitOptions", + "description": "How the collaborators are wired" + }, + "hooks": { + "anyOf": [ + { + "$ref": "#/$defs/HookOptions" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Commands to run around the lifecycle; they fire during apply only" + } + }, + "required": [ + "tables" + ], + "title": "PartitionsDocument", + "type": "object" +} diff --git a/examples/partitions.yaml b/examples/partitions.yaml new file mode 100644 index 0000000..f13ddd3 --- /dev/null +++ b/examples/partitions.yaml @@ -0,0 +1,90 @@ +# A deployment's tables, all in one file. Every key is documented on +# https://bedrock-python.github.io/pg-partsmith/reference/document/ ; unknown +# keys are refused, so a typo is a validation error and not a silent policy. +# +# Editor support: pg-partsmith schema > partitions.schema.json +# then, at the top of this file: +# yaml-language-server: $schema=partitions.schema.json + +version: 1 + +# No dsn here on purpose: it carries a password. It comes from --dsn, +# $PG_PARTSMITH_DSN, or a secret file named by $PG_PARTSMITH_DSN_FILE. + +# Every table starts from these; a table naming a key owns it entirely. +defaults: + schema: public + tz: Europe/Berlin + granularity: month + create_ahead_count: 3 + retention_count: 12 + +tables: + # The flat spelling: a time-partitioned table, defaults filled in. + - table_name: events + partition_column: created_at + + # Same shape, a different calendar and a longer memory. + - table_name: audit_log + partition_column: logged_at + granularity: day + retention_count: 400 + + # Any other topology is spelled out as a scheme: here RANGE by week over a + # UUIDv7 key (the timestamp lives inside the identifier), HASH by tenant + # underneath. Hooks fire once per week, never once per bucket. + - table_name: telemetry + scheme: + method: range + key: id + boundaries: { kind: time, granularity: week, codec: uuidv7 } + child: { method: hash, key: tenant_id, modulus: 8 } + lifecycle: + creation: { kind: create_ahead, count: 4 } + # Expire after 90 days, but never while rows are still pending -- the + # SQL is yours, evaluated while planning, {partition} is the candidate. + retention: + kind: all_of + members: + - { kind: keep_for, age: P90D } + - { kind: sql, sql: "SELECT NOT EXISTS (SELECT 1 FROM {partition} WHERE status = 'pending')" } + detach: concurrent + # A week between detach and drop, and only once nothing references it. + drop: { kind: drop_after, grace: P7D, when: { kind: unreferenced } } + leaves: + kind: local + tablespace: fast_ssd + storage_parameters: { fillfactor: 70 } + inherit_privileges: true + + # A LIST root with a fixed set of groups and a catch-all. A set level: the + # planner fills gaps in the set and never expires a group. + - table_name: shipments + scheme: + method: list + key: region + groups: + - { name: eu, values: [de, fr, nl] } + - { name: us, values: [us, ca] } + include_default: true + +# The wiring every table is maintained through: one key per keyword of +# PartitionToolkit.from_engine. Omit the section for the library's defaults. +runtime: + ddl_timezone: Europe/Berlin + marker_prefix: acme + drop_lock_timeout_ms: 3000 + drop_max_retries: 3 + +# What to run around the lifecycle. Commands are argument vectors, never +# shell strings; a block of Python sees `event` and `log`. Honoured only +# under `apply --allow-hooks` -- they run in a process holding DDL rights. +hooks: + timeout_seconds: 900 + before_drop: ["/opt/hooks/archive-partition.sh"] + after_create: ["/opt/hooks/notify.sh"] + before_detach: + python_file: hooks/export_partition.py + after_drop: + python: | + log.info("dropped %s (%s)", event.partition.name, event.operation.reason) diff --git a/pg_partsmith/__init__.py b/pg_partsmith/__init__.py index 329f165..1b59a86 100644 --- a/pg_partsmith/__init__.py +++ b/pg_partsmith/__init__.py @@ -13,6 +13,7 @@ UUIDv7BoundaryCodec, Window, ) +from .document import HookOptions, PartitionsDocument, PartitionTableSpec, PythonHook, ToolkitOptions from .entities import ( DefaultBounds, HashBounds, @@ -43,6 +44,7 @@ PartitionNotFoundError, PartitionReferencedError, PartitionTopologyError, + PlanConfigMismatchError, PlanStaleError, RowMoveRefusedError, UnmanagedPartitionDropError, @@ -89,6 +91,7 @@ PartitionBy, Reason, Severity, + validate_plan_for_config, ) from .planner import PlanMode, PlanningContext, plan_maintenance from .protocols import ( @@ -148,6 +151,7 @@ "ForeignLeaves", "HashBounds", "HashPartitioning", + "HookOptions", "HookPhase", "HourPeriodCalculator", "IntegerSequence", @@ -190,15 +194,19 @@ "PartitionReferencedError", "PartitionScheme", "PartitionStrategy", + "PartitionTableSpec", "PartitionTopologyError", "PartitionType", + "PartitionsDocument", "Period", "PeriodCalculator", + "PlanConfigMismatchError", "PlanMode", "PlanStaleError", "PlanningContext", "PositionedCalculator", "Predicate", + "PythonHook", "QuarterPeriodCalculator", "RangeBoundaries", "RangeBoundaryCodec", @@ -215,6 +223,7 @@ "TablePartitionConfig", "TimeBoundaries", "TimezoneAwareCalculator", + "ToolkitOptions", "UUIDv7BoundaryCodec", "UnmanagedPartitionDropError", "Unreferenced", @@ -227,4 +236,5 @@ "plan_maintenance", "qualify", "split_qualified_name", + "validate_plan_for_config", ] diff --git a/pg_partsmith/aio/__init__.py b/pg_partsmith/aio/__init__.py index 1f89442..760475b 100644 --- a/pg_partsmith/aio/__init__.py +++ b/pg_partsmith/aio/__init__.py @@ -1,5 +1,6 @@ """Async implementations for partition management.""" +from .command_hooks import CommandHookError, CommandHooks from .hooks import BasePartitionLifecycleHooks, PartitionLifecycleHooks from .lock import PostgresAdvisoryLockManager, RedisDistributedLockManager from .maintainer import PartitionMaintainer, maintain_partitions @@ -10,12 +11,16 @@ PartitionMetadataProvider, PartitionRepository, ) +from .python_hooks import PythonHookError, PythonHooks from .repositories import PostgresPartitionRepository from .service import PartitionLifecycleService from .services import PartitionInspector, PartitionValidationService, PlanExecutor +from .toolkit import PartitionToolkit __all__ = [ "BasePartitionLifecycleHooks", + "CommandHookError", + "CommandHooks", "LockManager", "PartitionInspector", "PartitionLifecycle", @@ -24,11 +29,14 @@ "PartitionMaintainer", "PartitionMetadataProvider", "PartitionRepository", + "PartitionToolkit", "PartitionValidationService", "PlanExecutor", "PostgresAdvisoryLockManager", "PostgresMetadataProvider", "PostgresPartitionRepository", + "PythonHookError", + "PythonHooks", "RedisDistributedLockManager", "maintain_partitions", ] diff --git a/pg_partsmith/aio/command_hooks.py b/pg_partsmith/aio/command_hooks.py new file mode 100644 index 0000000..cb7ac15 --- /dev/null +++ b/pg_partsmith/aio/command_hooks.py @@ -0,0 +1,131 @@ +"""Lifecycle hooks that run a command, for the stacks this library is not written in. + +A Go or Ruby team already owns an archiver; what they need is for it to be +invoked at the right moment with the right metadata. That is all this is: one +hook object that runs a configured command per phase, hands it the +:class:`~pg_partsmith.events.PartitionEvent` as JSON on stdin, and treats a +non-zero exit exactly as a raised exception -- the operation is aborted and +left for the next run. + +Nothing here needs a new context: the event is already a pydantic model, so the +payload the command reads is the same object a Python hook is handed, dumped +with ``by_alias=True``. + +Usage:: + + hooks = CommandHooks({HookPhase.BEFORE_DROP: ["/usr/local/bin/archive"]}) + service = PartitionLifecycleService(repo=repo, metadata=metadata, locks=locks, hooks=[hooks]) + +The command's stdout is logged. Its stderr is carried in the error when it +fails, which is the only place an operator will look at 03:00. +""" + +from __future__ import annotations + +import asyncio +import logging +from typing import TYPE_CHECKING + +from pg_partsmith.constants import DEFAULT_HOOK_TIMEOUT_SECONDS +from pg_partsmith.events import HookPhase, hook_environment +from pg_partsmith.hook_commands import ( + CommandHookError, + finish_hook_command, + start_hook_command, + stop_hook_command, + tail, +) + +from .hooks import BasePartitionLifecycleHooks + +if TYPE_CHECKING: + from collections.abc import Mapping, Sequence + + from pg_partsmith.events import PartitionEvent + +logger = logging.getLogger(__name__) + +__all__ = ["CommandHookError", "CommandHooks"] + + +class CommandHooks(BasePartitionLifecycleHooks): + """Runs one configured command per phase, with the event as JSON on stdin. + + Overrides :meth:`on_event` alone rather than one method per phase: the + phase is in the event, and a dispatch table reads better than eight + delegating methods that would each have to be added to again. The + per-phase methods come from the no-op base, which the executor calls after + this one. + """ + + def __init__( + self, + commands: Mapping[HookPhase, Sequence[str]], + *, + timeout_seconds: float = DEFAULT_HOOK_TIMEOUT_SECONDS, + ) -> None: + """Wire the commands. + + Args: + commands: The command to run at each phase, as an argument vector. + A vector rather than a string: nothing is passed through a + shell, so a partition name can never be read as syntax. + timeout_seconds: How long a command may take before it is killed and + the operation abandoned. A hook that hangs holds the table's + maintenance lock, so there is no "wait forever" option. + + Raises: + ValueError: If a command is empty, or its phase is not a hook phase. + """ + for phase, command in commands.items(): + if phase not in set(HookPhase): + msg = f"{phase!r} is not a hook phase; expected one of: {', '.join(p.value for p in HookPhase)}" + raise ValueError(msg) + if not command or not all(isinstance(part, str) for part in command): + msg = f"The {phase.value} command must be a non-empty list of strings" + raise ValueError(msg) + self._commands = {phase: tuple(command) for phase, command in commands.items()} + self._timeout = timeout_seconds + + @property + def phases(self) -> tuple[HookPhase, ...]: + """The phases a command is configured for, in declaration order.""" + return tuple(self._commands) + + async def on_event(self, event: PartitionEvent) -> None: + """Run the command configured for this event's phase, if there is one. + + Raises: + CommandHookError: If the command exits non-zero, cannot be run, or + outlives its timeout. A ``before_*`` hook failing this way + abandons the operation; an ``after_*`` one abandons what is left + of it, and the next run plans it again. + """ + command = self._commands.get(event.phase) + if command is None: + return + process = start_hook_command( + command, phase=event.phase, partition_name=event.partition.name, environment=hook_environment(event) + ) + try: + stdout = await asyncio.to_thread( + finish_hook_command, + process, + event.model_dump_json(by_alias=True).encode(), + phase=event.phase, + partition_name=event.partition.name, + timeout_seconds=self._timeout, + ) + except asyncio.CancelledError: + # The run is being stopped -- Ctrl+C, a pod's SIGTERM. The waiting + # thread cannot be cancelled, but the child can be stopped, which + # ends the wait and leaves nothing running unwatched. + await asyncio.to_thread(stop_hook_command, process) + raise + if stdout: + logger.info( + "%s hook said: %s", + event.phase.value, + tail(stdout), + extra={"partition_name": event.partition.name, "table_name": event.table_name}, + ) diff --git a/pg_partsmith/aio/python_hooks.py b/pg_partsmith/aio/python_hooks.py new file mode 100644 index 0000000..1f60c80 --- /dev/null +++ b/pg_partsmith/aio/python_hooks.py @@ -0,0 +1,86 @@ +"""Lifecycle hooks written as Python blocks in a configuration file. + +One hook object holds one compiled block per phase and runs it with ``event`` +and ``log`` in scope when that phase fires. Every block is compiled when the +object is built, so a document with a typo in it is refused before any DDL +runs rather than after some of it has. + +Usage:: + + hooks = PythonHooks({HookPhase.BEFORE_DROP: "log.warning('dropping %s', event.partition.name)"}) + service = PartitionLifecycleService(repo=repo, metadata=metadata, locks=locks, hooks=[hooks]) + +The block runs inline, in the process and on the loop that fires it. That is +the same footing as any hook written as a class, and the same responsibility: +a block that blocks, blocks maintenance. +""" + +from __future__ import annotations + +import logging +from typing import TYPE_CHECKING + +from pg_partsmith.events import HookPhase +from pg_partsmith.python_hooks import PythonHookError, compile_hook_source, run_hook_source + +from .hooks import BasePartitionLifecycleHooks + +if TYPE_CHECKING: + from collections.abc import Mapping + from types import CodeType + + from pg_partsmith.events import PartitionEvent + +__all__ = ["PythonHookError", "PythonHooks"] + + +class PythonHooks(BasePartitionLifecycleHooks): + """Runs one configured block of Python per phase. + + Overrides :meth:`on_event` alone; the phase is in the event, and the + per-phase methods come from the no-op base, which the executor calls after + this one. + """ + + def __init__(self, sources: Mapping[HookPhase, str], *, names: Mapping[HookPhase, str] | None = None) -> None: + """Compile every block now. + + Args: + sources: The block to run at each phase. + names: What tracebacks call each block -- the file it came from, + when it came from one. The phase by default. + + Raises: + SyntaxError: If a block does not parse. Its line and column are + the message, so it is not wrapped. + ValueError: If a phase is not a hook phase, or a block is empty. + """ + compiled: dict[HookPhase, CodeType] = {} + for phase, source in sources.items(): + if phase not in set(HookPhase): + msg = f"{phase!r} is not a hook phase; expected one of: {', '.join(p.value for p in HookPhase)}" + raise ValueError(msg) + if not source or not source.strip(): + msg = f"The {phase.value} block is empty" + raise ValueError(msg) + name = (names or {}).get(phase, f"") + compiled[phase] = compile_hook_source(source, name=name) + self._code = compiled + self._loggers = {phase: logging.getLogger(f"pg_partsmith.hook.{phase.value}") for phase in compiled} + + @property + def phases(self) -> tuple[HookPhase, ...]: + """The phases a block is configured for, in declaration order.""" + return tuple(self._code) + + async def on_event(self, event: PartitionEvent) -> None: + """Run the block configured for this event's phase, if there is one. + + Raises: + PythonHookError: If the block raises, which is how it refuses the + operation. + """ + code = self._code.get(event.phase) + if code is None: + return + run_hook_source(code, event, logger=self._loggers[event.phase]) diff --git a/pg_partsmith/aio/service.py b/pg_partsmith/aio/service.py index 42335a7..dcf87e8 100644 --- a/pg_partsmith/aio/service.py +++ b/pg_partsmith/aio/service.py @@ -135,23 +135,32 @@ async def apply( plan: MaintenancePlan, *, continue_on_error: bool = False, + allow_config_drift: bool = False, ) -> MaintenanceResult: """Execute a plan under the table's lock. Every destructive operation is revalidated against the catalog first: - a relation that no longer has the OID the plan saw is left alone. + a relation that no longer has the OID the plan saw is left alone, and + a plan made for another table, or under a configuration that has since + been edited, is refused before anything is executed. Args: config: The configuration the plan was made from. plan: The plan, possibly filtered. continue_on_error: Isolate operation failures into ``MaintenanceResult.issues`` instead of aborting. + allow_config_drift: Apply a plan whose fingerprint no longer + matches ``config`` -- it was planned under a policy that has + since changed, and its operations still carry the old reasons. Raises: LockAcquisitionError: If the table-level maintenance lock is unavailable. + PlanConfigMismatchError: If the plan was not made from ``config``. """ async with self._locks.acquire_lock(config.qualified_name): - return await self._executor.apply(config, plan, continue_on_error=continue_on_error) + return await self._executor.apply( + config, plan, continue_on_error=continue_on_error, allow_config_drift=allow_config_drift + ) async def maintain( self, diff --git a/pg_partsmith/aio/services/execution.py b/pg_partsmith/aio/services/execution.py index c125fe5..7f94589 100644 --- a/pg_partsmith/aio/services/execution.py +++ b/pg_partsmith/aio/services/execution.py @@ -45,6 +45,7 @@ FindingReason, MaintenancePlan, Operation, + validate_plan_for_config, ) from pg_partsmith.planner import PlanMode, PlanningContext, plan_maintenance, to_maintenance_issue from pg_partsmith.scheme import ListPartitioning, RangePartitioning @@ -89,6 +90,7 @@ async def apply( plan: MaintenancePlan, *, continue_on_error: bool = False, + allow_config_drift: bool = False, ) -> MaintenanceResult: """Execute every operation of ``plan`` in order. @@ -105,10 +107,16 @@ async def apply( plan: The plan. continue_on_error: Isolate operation failures into ``MaintenanceResult.issues`` instead of aborting. + allow_config_drift: Execute a plan whose fingerprint no longer + matches ``config``. Returns: The counters, the issues, and the plan itself. + + Raises: + PlanConfigMismatchError: If the plan was not made from ``config``. """ + validate_plan_for_config(config, plan, allow_config_drift=allow_config_drift) tally = _Tally() issues: list[MaintenanceIssue] = [to_maintenance_issue(f) for f in plan.actionable_findings] detached: set[str] = set() diff --git a/pg_partsmith/aio/services/inspection.py b/pg_partsmith/aio/services/inspection.py index 7b8468d..25999a1 100644 --- a/pg_partsmith/aio/services/inspection.py +++ b/pg_partsmith/aio/services/inspection.py @@ -3,7 +3,7 @@ from __future__ import annotations from datetime import UTC, datetime -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING from pg_partsmith.boundaries import Axis, CursorSource, Window from pg_partsmith.planner import PlanMode, PlanningContext, fact_targets @@ -67,7 +67,7 @@ async def context( if instant.tzinfo is None: instant = instant.replace(tzinfo=UTC) - cursors: dict[str, Any] = {} + cursors: dict[str, int] = {} for level in config.levels: boundaries = level.progression if boundaries is None or boundaries.axis is not Axis.INTEGER: diff --git a/pg_partsmith/aio/toolkit.py b/pg_partsmith/aio/toolkit.py new file mode 100644 index 0000000..3317e66 --- /dev/null +++ b/pg_partsmith/aio/toolkit.py @@ -0,0 +1,182 @@ +"""One set of collaborators for a table's maintenance, wired so they agree. + +Three settings live on two objects and have to match. ``marker_prefix`` +stamps a detached partition and decides what counts as ours when dropping, +so a prefix given to the repository alone leaves the metadata provider +unable to see the orphans it made -- they are never dropped. +``ddl_timezone`` writes naive boundary literals and reads them back in +:meth:`is_partition_closed`, and the two objects do not even default to the +same value. ``boundary_codec`` must be the one the bounds were encoded with. + +:meth:`PartitionToolkit.from_engine` takes each of those once and hands them +to everything that needs them, and returns the parts by name rather than +just a maintainer -- code that calls ``metadata.is_partition_closed`` or +``locks.acquire_lock`` directly should not have to build a second set and +keep it consistent by hand. + +Usage:: + + kit = PartitionToolkit.from_engine(engine, hooks=[ExportHooks()]) + plan = await kit.service.plan(config) + result = await kit.maintainer.run_maintenance_safe(config) +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from pg_partsmith.constants import ( + DEFAULT_DDL_TIMEOUT_SECONDS, + DEFAULT_DDL_TIMEZONE, + DEFAULT_DROP_LOCK_TIMEOUT_MS, + DEFAULT_DROP_MAX_BACKOFF, + DEFAULT_DROP_MAX_RETRIES, + DEFAULT_DROP_RETRY_DELAY, + DEFAULT_LOCK_PREFIX, +) +from pg_partsmith.document import ToolkitOptions + +from .lock import PostgresAdvisoryLockManager +from .maintainer import PartitionMaintainer +from .metadata import PostgresMetadataProvider +from .repositories import PostgresPartitionRepository +from .service import PartitionLifecycleService + +if TYPE_CHECKING: + from sqlalchemy.ext.asyncio import AsyncEngine + + from pg_partsmith.boundaries import RangeBoundaryCodec + + from .hooks import PartitionLifecycleHooks + from .protocols import LockManager, PartitionMetadataProvider, PartitionRepository + + +@dataclass(frozen=True, slots=True) +class PartitionToolkit: + """The repository, provider, locks, service and maintainer of one wiring. + + Build it with :meth:`from_engine`, or construct it directly around parts + of your own -- a repository against another database, a Redis lock + manager -- when the defaults do not fit. + + Attributes: + repo: DDL operations on partitions. + metadata: Read-only catalog access. + locks: The lock one maintenance run at a time is taken under. + service: The three verbs: plan, apply, maintain. + maintainer: The service with timing, logging and error handling, which + is what a scheduled tick calls. + """ + + repo: PartitionRepository + metadata: PartitionMetadataProvider + locks: LockManager + service: PartitionLifecycleService + maintainer: PartitionMaintainer + + @classmethod + def from_engine( + cls, + engine: AsyncEngine, + *, + hooks: list[PartitionLifecycleHooks] | None = None, + locks: LockManager | None = None, + marker_prefix: str | None = None, + ddl_timezone: str | None = DEFAULT_DDL_TIMEZONE, + ddl_timeout_seconds: float = DEFAULT_DDL_TIMEOUT_SECONDS, + boundary_codec: RangeBoundaryCodec | None = None, + lock_prefix: str = DEFAULT_LOCK_PREFIX, + lock_min_interval_seconds: float = 0.0, + drop_allow_unmanaged: bool = False, + drop_lock_timeout_ms: int = DEFAULT_DROP_LOCK_TIMEOUT_MS, + drop_max_retries: int = DEFAULT_DROP_MAX_RETRIES, + drop_retry_delay: float = DEFAULT_DROP_RETRY_DELAY, + drop_max_backoff: float = DEFAULT_DROP_MAX_BACKOFF, + ) -> PartitionToolkit: + """Wire every part around one engine, with the shared settings given once. + + Args: + engine: The engine every part works through. + hooks: Lifecycle hooks, handed to the service. + locks: A lock manager of your own -- Redis, or an advisory manager + with a different ID derivation. A PostgreSQL advisory manager + on ``engine`` by default. + marker_prefix: Orphan marker prefix, given to the repository that + writes it and the provider that looks for it. + ddl_timezone: Session timezone naive boundary literals are written + and read in, given to both for the same reason. + ddl_timeout_seconds: Statement timeout for DDL. + boundary_codec: Codec ``is_partition_closed`` reads encoded bounds + with; only needed when the key is an encoded identifier. + lock_prefix: Prefix of the default advisory lock manager's keys. + lock_min_interval_seconds: Minimum seconds between acquire attempts + per table; 0 disables the rate limit. + drop_allow_unmanaged: Let the repository drop a relation carrying no + ownership marker. + drop_lock_timeout_ms: ``lock_timeout`` a drop attempt runs under. + drop_max_retries: Attempts a drop makes before giving up. + drop_retry_delay: Delay before the second attempt; it backs off. + drop_max_backoff: Ceiling on that backoff. + + Returns: + The parts, wired consistently. + """ + repo = PostgresPartitionRepository( + engine, + ddl_timezone=ddl_timezone, + ddl_timeout_seconds=ddl_timeout_seconds, + marker_prefix=marker_prefix, + drop_allow_unmanaged=drop_allow_unmanaged, + drop_lock_timeout_ms=drop_lock_timeout_ms, + drop_max_retries=drop_max_retries, + drop_retry_delay=drop_retry_delay, + drop_max_backoff=drop_max_backoff, + ) + metadata = PostgresMetadataProvider( + engine, + marker_prefix=marker_prefix, + boundary_codec=boundary_codec, + ddl_timezone=ddl_timezone, + ) + lock_manager = ( + locks + if locks is not None + else PostgresAdvisoryLockManager( + engine, prefix=lock_prefix, acquire_min_interval_seconds=lock_min_interval_seconds + ) + ) + service = PartitionLifecycleService(repo=repo, metadata=metadata, locks=lock_manager, hooks=hooks) + return cls( + repo=repo, + metadata=metadata, + locks=lock_manager, + service=service, + maintainer=PartitionMaintainer(service), + ) + + @classmethod + def from_options( + cls, + engine: AsyncEngine, + options: ToolkitOptions, + *, + hooks: list[PartitionLifecycleHooks] | None = None, + locks: LockManager | None = None, + ) -> PartitionToolkit: + """Wire every part from the ``runtime`` section of a document. + + Args: + engine: The engine every part works through. + options: The wiring, as a file writes it -- one field per keyword + of :meth:`from_engine`, with ``boundary_codec`` as a name. + hooks: Lifecycle hooks, handed to the service. + locks: A lock manager of your own, as in :meth:`from_engine`. + + Returns: + The parts, wired consistently. + + Raises: + ValueError: If ``options.boundary_codec`` names no known codec. + """ + return cls.from_engine(engine, hooks=hooks, locks=locks, **options.to_kwargs()) diff --git a/pg_partsmith/cli/__init__.py b/pg_partsmith/cli/__init__.py new file mode 100644 index 0000000..ca2ed7d --- /dev/null +++ b/pg_partsmith/cli/__init__.py @@ -0,0 +1,19 @@ +"""The ``pg-partsmith`` command line. + +Requires the ``cli`` extra:: + + pip install "pg-partsmith[cli]" + +Four commands over a configuration document and a DSN: ``inspect``, ``plan`` +and ``validate`` issue no DDL, and ``apply`` withholds every destructive +operation unless it is asked for them. ``plan`` and ``apply`` stay separable, +with a saved plan as the artifact between them: what this reads, prints and +writes is the library's own :class:`~pg_partsmith.MaintenancePlan`, not a +summary of one. +""" + +from .exit_codes import ExitCode +from .loader import ConfigError +from .main import app, main + +__all__ = ["ConfigError", "ExitCode", "app", "main"] diff --git a/pg_partsmith/cli/__main__.py b/pg_partsmith/cli/__main__.py new file mode 100644 index 0000000..bb3376c --- /dev/null +++ b/pg_partsmith/cli/__main__.py @@ -0,0 +1,6 @@ +"""``python -m pg_partsmith.cli``.""" + +from .main import main + +if __name__ == "__main__": # pragma: no cover - the interpreter's entry, exercised by hand + raise SystemExit(main()) diff --git a/pg_partsmith/cli/commands.py b/pg_partsmith/cli/commands.py new file mode 100644 index 0000000..7654104 --- /dev/null +++ b/pg_partsmith/cli/commands.py @@ -0,0 +1,236 @@ +"""What each command does, once the document is read and the engine is up. + +``inspect``, ``plan`` and ``validate`` are read-only: no DDL, no lock, no hook. +``apply`` is the one that acts, and it withholds every destructive operation +unless it was asked for them. What they all share is that a CronJob and a CI +step read the exit code and nothing else. +""" + +from __future__ import annotations + +import logging +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any + +from pg_partsmith.aio import PartitionToolkit, PartitionValidationService +from pg_partsmith.exceptions import InvalidPartitionConfigError +from pg_partsmith.plan import MaintenancePlan, OperationKind + +from .exit_codes import ExitCode +from .loader import ConfigError +from .metrics import render_metrics +from .render import describe_locks, describe_tree, envelope, plan_entry, to_json, tree_entry + +if TYPE_CHECKING: + from collections.abc import Sequence + + from pg_partsmith.entities import MaintenanceResult, TablePartitionConfig + +logger = logging.getLogger("pg_partsmith.cli") + +__all__ = ["CommandResult", "run_apply", "run_inspect", "run_plan", "run_validate"] + + +@dataclass(frozen=True, slots=True) +class CommandResult: + """What a command produced: what to print, and what to exit with. + + Attributes: + code: The exit status. + lines: Everything to write to stdout, one entry per block. + payload: The JSON envelope, when the command was asked for JSON. + """ + + code: ExitCode + lines: list[str] = field(default_factory=list) + payload: dict[str, Any] | None = None + + def render(self, *, output: str = "human") -> str: + """The text to print, in the form that was asked for. + + The JSON and the metrics are read off the same envelope, so a number in + one cannot disagree with a number in the other. + """ + if self.payload is not None: + if output == "json": + return to_json(self.payload) + if output == "metrics": + return render_metrics(self.payload).rstrip("\n") + return "\n\n".join(self.lines) + + +async def run_inspect(kit: PartitionToolkit, configs: Sequence[TablePartitionConfig]) -> CommandResult: + """Read the real tree of every selected table and show it. + + A table the document describes but PostgreSQL does not partition is + reported and makes the command exit ``CONFIG``: the document is describing + something that is not there. + """ + blocks: list[str] = [] + entries: list[dict[str, Any]] = [] + code = ExitCode.OK + for config in configs: + tree = await kit.service.inspect(config) + entries.append(tree_entry(config.qualified_name, tree)) + if tree is None: + code = ExitCode.CONFIG + blocks.append(f"{config.qualified_name} — not a partitioned table") + continue + blocks.append(describe_tree(tree)) + return CommandResult(code=code, lines=blocks, payload=envelope("inspect", entries)) + + +async def run_plan( + kit: PartitionToolkit, configs: Sequence[TablePartitionConfig], *, check: bool, locks: bool = False +) -> CommandResult: + """Plan every selected table, and issue no DDL doing it. + + With ``check``, pending operations are drift and are exited on, which is + what lets an alert say "maintenance has not been running". A finding + outranks that: drift is what a run fixes, a finding is what it cannot. + + With ``locks``, each operation is followed by the heaviest lock it takes + and on what -- the thing a DBA reads before agreeing to a window. The JSON + carries the same under ``capabilities`` whether or not it was asked for. + """ + blocks: list[str] = [] + entries: list[dict[str, Any]] = [] + drift = False + findings = False + for config in configs: + plan = await kit.service.plan(config) + entries.append(plan_entry(plan)) + blocks.append(plan.describe() + ("\n" + describe_locks(plan) if locks else "")) + drift = drift or not plan.is_noop + findings = findings or bool(plan.actionable_findings) + + code = ExitCode.OK + if findings: + code = ExitCode.FINDINGS + elif check and drift: + code = ExitCode.DRIFT + return CommandResult(code=code, lines=blocks, payload=envelope("plan", entries)) + + +async def run_validate(kit: PartitionToolkit, configs: Sequence[TablePartitionConfig]) -> CommandResult: + """Check every selected table's configuration against the catalog. + + This is the one that belongs in CI: the document has already parsed by the + time this runs, so what is left to answer is whether the tables it + describes are the tables that exist -- partitioned at all, by the method + and on the key the scheme claims. + """ + blocks: list[str] = [] + entries: list[dict[str, Any]] = [] + validation = PartitionValidationService(kit.metadata) + code = ExitCode.OK + for config in configs: + try: + await validation.validate_config(config) + except InvalidPartitionConfigError as exc: + code = ExitCode.CONFIG + entries.append({"table": config.qualified_name, "ok": False, "error": str(exc)}) + blocks.append(f"{config.qualified_name} — {exc}") + continue + entries.append({"table": config.qualified_name, "ok": True, "error": None}) + blocks.append(f"{config.qualified_name} — ok") + return CommandResult(code=code, lines=blocks, payload=envelope("validate", entries)) + + +async def run_apply( + kit: PartitionToolkit, + configs: Sequence[TablePartitionConfig], + *, + plans: dict[str, MaintenancePlan] | None = None, + allow_destructive: bool = False, + continue_on_error: bool = False, + allow_config_drift: bool = False, +) -> CommandResult: + """Execute maintenance: either a plan read from a file, or one made here. + + Destructive operations are withheld unless they are asked for. That makes + the safe mode the default one -- an init container that creates what the + application is about to write into, and retires nothing -- rather than a + second mode somebody has to remember to select. + + A plan read from a file is applied through the library's own guard: it is + refused unless it was made for this table, under this configuration. + + Args: + kit: The wiring. + configs: The tables to maintain, in order. + plans: Plans read from a file, keyed by table; None to plan here. + allow_destructive: Carry out detaches and drops as well as creations. + continue_on_error: Isolate a failed operation instead of aborting. + allow_config_drift: Apply a saved plan whose configuration has changed. + + Returns: + What was done, and the code to exit with. + + Raises: + ConfigError: If a table was selected and the plan file has nothing for it. + """ + blocks: list[str] = [] + entries: list[dict[str, Any]] = [] + issues = False + for config in configs: + if plans is not None: + plan = _plan_for(config, plans) + if not allow_destructive: + plan = plan.without(OperationKind.DETACH, OperationKind.DROP) + result = await kit.service.apply( + config, plan, continue_on_error=continue_on_error, allow_config_drift=allow_config_drift + ) + applied: MaintenancePlan | None = plan + else: + # Planning and applying under one lock is what maintain() is for, + # and it is also what completes an interrupted DETACH CONCURRENTLY + # before deciding the rest of the run. + result = await kit.service.maintain( + config, + skip_detach=not allow_destructive, + skip_drop=not allow_destructive, + continue_on_error=continue_on_error, + ) + applied = result.maintenance_plan + + issues = issues or bool(result.issues) + entries.append( + { + "table": config.qualified_name, + "result": result.model_dump(mode="json", by_alias=True), + # The result excludes its plan from serialization, so it is + # dumped beside it: an audit log wants what was done and why. + "plan": None if applied is None else applied.model_dump(mode="json", by_alias=True), + } + ) + blocks.append(_describe_result(config.qualified_name, result)) + + if not allow_destructive: + blocks.append("Creations only: detaches and drops need --allow-destructive.") + return CommandResult( + code=ExitCode.FINDINGS if issues else ExitCode.OK, + lines=blocks, + payload=envelope("apply", entries), + ) + + +def _plan_for(config: TablePartitionConfig, plans: dict[str, MaintenancePlan]) -> MaintenancePlan: + """The saved plan for one table, or a refusal naming what the file does hold.""" + plan = plans.get(config.qualified_name) + if plan is None: + known = ", ".join(sorted(plans)) or "nothing" + msg = f"The plan file has nothing for {config.qualified_name!r}; it holds {known}" + raise ConfigError(msg) + return plan + + +def _describe_result(table_name: str, result: MaintenanceResult) -> str: + """One block per table: what it did, then anything it wants a human to see.""" + counts = ( + f"created {result.created_count}, repaired {result.repaired_count}, attached {result.attached_count}, " + f"detached {result.detached_count}, dropped {result.dropped_count}" + ) + lines = [f"{table_name} — {counts}"] + lines.extend(f" [{issue.step.value}] {issue.partition_name}: {issue.error}" for issue in result.issues) + return "\n".join(lines) diff --git a/pg_partsmith/cli/exit_codes.py b/pg_partsmith/cli/exit_codes.py new file mode 100644 index 0000000..fc3f949 --- /dev/null +++ b/pg_partsmith/cli/exit_codes.py @@ -0,0 +1,45 @@ +"""What the process returns, because a CronJob and a CI step read that and nothing else.""" + +from enum import IntEnum + +__all__ = ["ExitCode"] + + +class ExitCode(IntEnum): + """The exit status of one command. + + Distinguishable on purpose: "nothing to do", "there is drift", "a human has + to look at this" and "it did not run" are four different pages, and a tool + that returns 1 for all of them is alerted on by nobody. + + Attributes: + OK: The command did what it was asked, and found nothing pending. + FAILED: Something unexpected. The message is on stderr. + DRIFT: ``plan --check`` found operations waiting to be applied. Not a + failure -- it is what "maintenance has not run lately" looks like. + FINDINGS: The planner reported something an operator has to act on. + Outranks :attr:`DRIFT`: drift is what a run fixes, a finding is not. + CONFIG: The document does not parse, or does not match the database. + CONNECTION: The database: unreachable, refused the credentials, or failed a statement. + LOCKED: Another maintainer holds the table's lock. Overlapping runs are + ordinary, so this is its own code rather than a failure to page on. + USAGE: The invocation itself was wrong -- a misspelled flag, no command. + ``EX_USAGE`` from ``sysexits.h``, and deliberately not the ``2`` + argument parsers default to: that is what this tool means "drift" + by, and a CronJob alerting on drift must not page over a typo. + INTERRUPTED: Stopped by ``SIGINT`` -- Ctrl+C -- after cleaning up. + ``128 + 2``, the shell's own spelling of it. + TERMINATED: Stopped by ``SIGTERM`` -- what a pod is sent at its + deadline -- after cleaning up. ``128 + 15``, likewise. + """ + + OK = 0 + FAILED = 1 + DRIFT = 2 + FINDINGS = 3 + CONFIG = 4 + CONNECTION = 5 + LOCKED = 6 + USAGE = 64 + INTERRUPTED = 130 + TERMINATED = 143 diff --git a/pg_partsmith/cli/loader.py b/pg_partsmith/cli/loader.py new file mode 100644 index 0000000..5313917 --- /dev/null +++ b/pg_partsmith/cli/loader.py @@ -0,0 +1,291 @@ +"""Reading the document off disk, and deciding what to connect to. + +The library parses no files and opens no connections; the CLI is where both +happen, and this is that layer. It is deliberately thin: a format is chosen by +extension, parsed by whoever owns it, and handed to +:class:`~pg_partsmith.PartitionsDocument` to be validated in one place. +""" + +from __future__ import annotations + +import json +import os +from pathlib import Path +from typing import Any + +from pg_partsmith.document import HookOptions, PartitionsDocument +from pg_partsmith.entities import TablePartitionConfig +from pg_partsmith.events import HookPhase +from pg_partsmith.plan import MaintenancePlan +from pg_partsmith.python_hooks import compile_hook_source + +from .render import OUTPUT_VERSION + +__all__ = [ + "DSN_ENV_VAR", + "DSN_FILE_ENV_VAR", + "ConfigError", + "async_url", + "load_document", + "load_plans", + "load_python_hooks", + "resolve_dsn", + "select_configs", +] + +DSN_ENV_VAR = "PG_PARTSMITH_DSN" +"""Environment variable read when neither ``--dsn`` nor the document carries one.""" + +DSN_FILE_ENV_VAR = "PG_PARTSMITH_DSN_FILE" +"""A file holding the DSN -- a Docker or Swarm secret under ``/run/secrets`` -- read after the variable.""" + +_YAML_SUFFIXES = frozenset({".yaml", ".yml"}) +_JSON_SUFFIXES = frozenset({".json"}) + + +class ConfigError(Exception): + """The document cannot be read, parsed, or validated.""" + + +def load_document(path: Path) -> PartitionsDocument: + """Read one configuration document. + + The format is chosen by extension: ``.json`` by the standard library, + ``.yaml`` / ``.yml`` by PyYAML's safe loader. A document is validated the + same way whichever it came from -- the format is not the contract, the + document is. + + Args: + path: The file to read. + + Returns: + The validated document. + + Raises: + ConfigError: If the file is missing, is in a format this build cannot + read, does not parse, or does not validate. + """ + try: + text = path.read_text(encoding="utf-8") + except OSError as exc: + msg = f"Cannot read {path}: {exc.strerror or exc}" + raise ConfigError(msg) from exc + + suffix = path.suffix.lower() + if suffix in _JSON_SUFFIXES: + payload = _parse_json(text, path) + elif suffix in _YAML_SUFFIXES: + payload = _parse_yaml(text, path) + else: + known = ", ".join(sorted(_JSON_SUFFIXES | _YAML_SUFFIXES)) + msg = f"{path} has no format this reads; name it with one of: {known}" + raise ConfigError(msg) + + if not isinstance(payload, dict): + msg = f"{path} is not a document: its top level is {type(payload).__name__}, not a mapping" + raise ConfigError(msg) + try: + return PartitionsDocument.model_validate(payload) + except ValueError as exc: + msg = f"{path} is not a valid document:\n{exc}" + raise ConfigError(msg) from exc + + +def resolve_dsn(document: PartitionsDocument, *, override: str | None = None) -> str: + """The connection string: the flag, the environment, a secret file, then the document. + + In that order, because that is the order of how specific to this run each + one is -- and because a DSN carries a password, which a deployment may well + want to keep out of a file it mounts from a ConfigMap. ``PG_PARTSMITH_DSN_FILE`` + is the Docker and Swarm secrets convention: the secret arrives as a file + under ``/run/secrets``, and naming the file is how a Compose stack hands it + over without a shell in between. + + Args: + document: The document, which may carry a ``dsn``. + override: What ``--dsn`` said, when it said anything. + + Returns: + The connection string. + + Raises: + ConfigError: If none of the four names one, or the named file cannot be read. + """ + dsn = override or os.environ.get(DSN_ENV_VAR) or _dsn_from_file() or document.dsn + if not dsn: + msg = f"No connection string: pass --dsn, set {DSN_ENV_VAR} or {DSN_FILE_ENV_VAR}, or give the document a dsn" + raise ConfigError(msg) + return dsn + + +def _dsn_from_file() -> str | None: + """The DSN a secret file holds, when ``PG_PARTSMITH_DSN_FILE`` names one.""" + path = os.environ.get(DSN_FILE_ENV_VAR) + if not path: + return None + try: + return Path(path).read_text(encoding="utf-8").strip() + except OSError as exc: + msg = f"Cannot read the DSN from {path} ({DSN_FILE_ENV_VAR}): {exc.strerror or exc}" + raise ConfigError(msg) from exc + + +def async_url(dsn: str) -> str: + """The DSN with an async driver named, since that is what the CLI drives. + + ``postgresql://…`` means psycopg2 to SQLAlchemy, which cannot be driven + asynchronously; a DSN that already names its driver is left exactly as it + is, so ``postgresql+psycopg://`` keeps working for whoever installed it. + """ + scheme, separator, rest = dsn.partition("://") + if not separator or "+" in scheme: + return dsn + if scheme in {"postgresql", "postgres"}: + return f"postgresql+asyncpg://{rest}" + return dsn + + +def select_configs(document: PartitionsDocument, tables: tuple[str, ...]) -> tuple[TablePartitionConfig, ...]: + """The document's configurations, narrowed to the tables ``--table`` named. + + A name is matched as written and as it qualifies -- ``events`` finds + ``public.events`` -- so an operator does not have to know whether the + document spelled the schema out. + + Args: + document: The document. + tables: The names asked for; empty means every table. + + Returns: + The configurations, in document order. + + Raises: + ConfigError: If a name matches no table in the document. + """ + configs = document.configs() + if not tables: + return configs + selected: list[TablePartitionConfig] = [] + for name in tables: + matches = [c for c in configs if name in {c.qualified_name, c.table_name}] + if not matches: + known = ", ".join(c.qualified_name for c in configs) + msg = f"{name!r} is not in this document; it describes {known}" + raise ConfigError(msg) + selected.extend(m for m in matches if m not in selected) + return tuple(selected) + + +def _parse_json(text: str, path: Path) -> Any: + try: + return json.loads(text) + except json.JSONDecodeError as exc: + msg = f"{path} is not valid JSON: {exc}" + raise ConfigError(msg) from exc + + +def _parse_yaml(text: str, path: Path) -> Any: + # Imported here, not at the top: PyYAML is an extra, and a JSON document + # must load on an installation without it. A module-level fallback to None + # is unreachable to mypy once the stubs are installed, which CI has. + try: + import yaml # noqa: PLC0415 + except ImportError as exc: # pragma: no cover - exercised by the extra being absent + msg = f"Reading {path} needs PyYAML: pip install 'pg-partsmith[cli]' (or write the document as JSON)" + raise ConfigError(msg) from exc + try: + return yaml.safe_load(text) + except yaml.YAMLError as exc: + msg = f"{path} is not valid YAML: {exc}" + raise ConfigError(msg) from exc + + +def load_plans(path: Path) -> dict[str, MaintenancePlan]: + """Read plans written by ``plan --save``, keyed by the table each is for. + + The envelope carries its own version so a reader can tell what it is + holding; a file from a future format is refused rather than half-read. + + Args: + path: The file ``plan --save`` wrote. + + Returns: + One plan per table named in the file. + + Raises: + ConfigError: If the file cannot be read, is not that envelope, or holds + a plan this version cannot validate. + """ + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except OSError as exc: + msg = f"Cannot read {path}: {exc.strerror or exc}" + raise ConfigError(msg) from exc + except json.JSONDecodeError as exc: + msg = f"{path} is not valid JSON: {exc}" + raise ConfigError(msg) from exc + + if not isinstance(payload, dict) or "tables" not in payload: + msg = f"{path} is not a saved plan: it has no 'tables'" + raise ConfigError(msg) + version = payload.get("version") + if version != OUTPUT_VERSION: + msg = f"{path} is version {version!r}; this reads version {OUTPUT_VERSION}" + raise ConfigError(msg) + + plans: dict[str, MaintenancePlan] = {} + for entry in payload["tables"]: + if not isinstance(entry, dict) or "plan" not in entry: + msg = f"{path} holds an entry with no plan in it" + raise ConfigError(msg) + try: + plan = MaintenancePlan.model_validate(entry["plan"]) + except ValueError as exc: + msg = f"{path} holds a plan this version cannot read:\n{exc}" + raise ConfigError(msg) from exc + plans[plan.table_name] = plan + if not plans: + msg = f"{path} names no table" + raise ConfigError(msg) + return plans + + +def load_python_hooks(hooks: HookOptions, base_dir: Path) -> tuple[dict[HookPhase, str], dict[HookPhase, str]]: + """Every Python block the document names, with file-backed ones read and compiled. + + Inline blocks were compiled when the document validated. A ``python_file`` + is resolved here, relative to the document, because only the reader knows + where the document lives -- and it is compiled here for the same reason the + inline ones were: a mistake belongs to ``validate``, not to 03:00. + + Args: + hooks: The document's hooks section. + base_dir: The directory the document was read from. + + Returns: + The source per phase, and what tracebacks should call each one. + + Raises: + ConfigError: If a file cannot be read or does not parse. + """ + sources: dict[HookPhase, str] = {} + names: dict[HookPhase, str] = {} + for phase, block in hooks.python_blocks().items(): + if block.python is not None: + sources[phase] = block.python + names[phase] = f"" + continue + path = (base_dir / str(block.python_file)).resolve() + try: + source = path.read_text(encoding="utf-8") + except OSError as exc: + msg = f"Cannot read the {phase.value} hook {path}: {exc.strerror or exc}" + raise ConfigError(msg) from exc + try: + compile_hook_source(source, name=str(path)) + except SyntaxError as exc: + msg = f"The {phase.value} hook {path} does not parse: {exc.msg} (line {exc.lineno})" + raise ConfigError(msg) from exc + sources[phase] = source + names[phase] = str(path) + return sources, names diff --git a/pg_partsmith/cli/main.py b/pg_partsmith/cli/main.py new file mode 100644 index 0000000..63ff63a --- /dev/null +++ b/pg_partsmith/cli/main.py @@ -0,0 +1,666 @@ +"""The command line: argument parsing, the engine, and what the process exits with. + +``inspect``, ``plan`` and ``validate`` issue no DDL; ``apply`` is the one that +acts, and withholds every destructive operation unless it is asked for them. +Logging goes to stderr so stdout stays parseable; ``--output json`` is the +models' own dump, so it cannot drift from the library. + +The arguments are declared as type annotations and parsed by typer, which is +click underneath: every flag has a type, the help is generated from the same +declarations that parse it, and shell completion comes for free. The process +still leaves through :func:`main`, which turns whatever a command returns -- +or whatever parsing raised -- into one :class:`~pg_partsmith.cli.exit_codes.ExitCode`. +""" + +from __future__ import annotations + +import asyncio +import json +import logging +import os +import signal +import sys +from dataclasses import dataclass +from enum import StrEnum +from pathlib import Path +from typing import TYPE_CHECKING, Annotated + +import typer +from sqlalchemy.exc import ArgumentError, NoSuchModuleError, SQLAlchemyError +from sqlalchemy.ext.asyncio import create_async_engine + +from pg_partsmith.__version__ import __version__ +from pg_partsmith.aio import CommandHooks, PartitionToolkit, PythonHooks +from pg_partsmith.document import PartitionsDocument +from pg_partsmith.exceptions import ( + InvalidPartitionConfigError, + LockAcquisitionError, + PartitionError, + PlanConfigMismatchError, +) +from pg_partsmith.hook_commands import CommandHookError +from pg_partsmith.python_hooks import PythonHookError + +from .commands import CommandResult, run_apply, run_inspect, run_plan, run_validate +from .exit_codes import ExitCode +from .loader import ( + DSN_ENV_VAR, + DSN_FILE_ENV_VAR, + ConfigError, + async_url, + load_document, + load_plans, + load_python_hooks, + resolve_dsn, + select_configs, +) +from .render import to_json + +try: + from asyncpg.exceptions import InterfaceError as _DriverInterfaceError + from asyncpg.exceptions import PostgresError as _DriverPostgresError +except ImportError: # pragma: no cover - the cli extra brings asyncpg; a bare install may not + _DRIVER_ERRORS: tuple[type[Exception], ...] = () +else: + _DRIVER_ERRORS = (_DriverPostgresError, _DriverInterfaceError) + +# Whatever the database answers with, at any depth, so the mapping to exit 5 is one place. +_DATABASE_ERRORS: tuple[type[Exception], ...] = (SQLAlchemyError, OSError, *_DRIVER_ERRORS) + +if TYPE_CHECKING: + from collections.abc import Sequence + + from pg_partsmith.aio import PartitionLifecycleHooks + +logger = logging.getLogger("pg_partsmith.cli") + +__all__ = ["app", "main"] + +_EPILOG = ( + "Exit codes: 0 nothing pending, 2 drift found (plan --check), 3 findings need a human, " + "4 configuration, 5 the database, 6 another maintainer holds the lock, 64 usage, " + "130 / 143 stopped by a signal, 1 unexpected." +) + + +class Output(StrEnum): + """The forms a result can be printed in.""" + + human = "human" + json = "json" + metrics = "metrics" + + +app = typer.Typer( + name="pg-partsmith", + help="Inspect, plan and run PostgreSQL partition maintenance from a configuration document.", + epilog=_EPILOG, + no_args_is_help=True, + context_settings={"help_option_names": ["-h", "--help"]}, + # Tracebacks are ours to print, under --verbose; a rich one for an operator + # reading a CronJob log is noise dressed up. + pretty_exceptions_enable=False, +) + + +# ── Options every command takes ───────────────────────────────────────────────── + +ConfigOption = Annotated[ + Path, + typer.Option("--config", "-c", metavar="FILE", show_default=False, help="the configuration document (.yaml/.json)"), +] +DsnOption = Annotated[ + str | None, + typer.Option( + "--dsn", + show_default=False, + help=f"connection string; falls back to ${DSN_ENV_VAR}, then to the file ${DSN_FILE_ENV_VAR} names, " + "then to the document's dsn", + ), +] +TableOption = Annotated[ + list[str] | None, + typer.Option( + "--table", + metavar="NAME", + show_default=False, + help="only this table, qualified or bare; repeatable. Every table in the document otherwise", + ), +] +OutputOption = Annotated[ + Output, + typer.Option("--output", "-o", help="human, json, or Prometheus text for a node_exporter textfile"), +] +VerboseOption = Annotated[bool, typer.Option("--verbose", "-v", help="log what it is doing, to stderr")] +WriteOption = Annotated[ + Path | None, + typer.Option( + "--write", + metavar="FILE", + show_default=False, + help="write the output to FILE instead of stdout, atomically; for a node_exporter textfile", + ), +] + + +@dataclass(frozen=True, slots=True) +class _Invocation: + """One parsed command, with every flag it could carry.""" + + command: str + config: Path + dsn: str | None + tables: tuple[str, ...] + output: Output + verbose: bool + check: bool = False + save: Path | None = None + locks: bool = False + plan: Path | None = None + allow_destructive: bool = False + continue_on_error: bool = False + allow_config_drift: bool = False + allow_hooks: bool = False + write: Path | None = None + ok_if_locked: bool = False + + +def _version(value: bool) -> None: + """``--version`` reads the library's own number: there is deliberately no second one.""" + if value: + typer.echo(f"pg-partsmith {__version__}") + raise typer.Exit + + +@app.callback() +def _root( + version: Annotated[ + bool, typer.Option("--version", callback=_version, is_eager=True, help="show the version and exit") + ] = False, +) -> None: + """Inspect, plan and run PostgreSQL partition maintenance from a configuration document.""" + + +# ── The commands ──────────────────────────────────────────────────────────────── + + +@app.command() +def inspect( + config: ConfigOption, + dsn: DsnOption = None, + table: TableOption = None, + output: OutputOption = Output.human, + verbose: VerboseOption = False, + write: WriteOption = None, +) -> int: + """Read the partition tree that exists and print it.""" + return _execute( + _Invocation( + "inspect", config=config, dsn=dsn, tables=tuple(table or ()), output=output, verbose=verbose, write=write + ) + ) + + +@app.command() +def plan( + config: ConfigOption, + dsn: DsnOption = None, + table: TableOption = None, + output: OutputOption = Output.human, + verbose: VerboseOption = False, + write: WriteOption = None, + check: Annotated[ + bool, + typer.Option( + "--check", + help="exit 2 when any operation is pending, for alerting on maintenance that has stopped running", + ), + ] = False, + save: Annotated[ + Path | None, + typer.Option( + "--save", metavar="FILE", show_default=False, help="write the plan to FILE, for `apply --plan FILE`" + ), + ] = None, + locks: Annotated[ + bool, typer.Option("--locks", help="after each operation, the heaviest lock it takes and on what") + ] = False, +) -> int: + """Show what maintenance would do, and why. Issues no DDL.""" + return _execute( + _Invocation( + "plan", + config=config, + dsn=dsn, + tables=tuple(table or ()), + output=output, + verbose=verbose, + check=check, + save=save, + locks=locks, + write=write, + ) + ) + + +@app.command() +def validate( + config: ConfigOption, + dsn: DsnOption = None, + table: TableOption = None, + output: OutputOption = Output.human, + verbose: VerboseOption = False, + write: WriteOption = None, +) -> int: + """Check the document against the catalog. Exits non-zero on a problem.""" + return _execute( + _Invocation( + "validate", config=config, dsn=dsn, tables=tuple(table or ()), output=output, verbose=verbose, write=write + ) + ) + + +@app.command() +def apply( + config: ConfigOption, + dsn: DsnOption = None, + table: TableOption = None, + output: OutputOption = Output.human, + verbose: VerboseOption = False, + write: WriteOption = None, + plan: Annotated[ + Path | None, + typer.Option( + "--plan", + metavar="FILE", + show_default=False, + help="apply the plan saved in FILE instead of planning now; refused if it was not made from this document", + ), + ] = None, + allow_destructive: Annotated[ + bool, + typer.Option( + "--allow-destructive", + help="carry out detaches and drops as well; without it, only partitions are created", + ), + ] = False, + continue_on_error: Annotated[ + bool, + typer.Option("--continue-on-error", help="isolate a failed operation into the issues instead of aborting"), + ] = False, + allow_config_drift: Annotated[ + bool, + typer.Option( + "--allow-config-drift", help="apply a saved plan whose configuration has changed since it was made" + ), + ] = False, + allow_hooks: Annotated[ + bool, + typer.Option( + "--allow-hooks", + help="run what the document's hooks section names; without it, a document declaring any is refused", + ), + ] = False, + ok_if_locked: Annotated[ + bool, + typer.Option( + "--ok-if-locked", + help="exit 0 rather than 6 when another maintainer holds the lock; for an init container", + ), + ] = False, +) -> int: + """Carry out maintenance. Creations only, unless --allow-destructive.""" + return _execute( + _Invocation( + "apply", + config=config, + dsn=dsn, + tables=tuple(table or ()), + output=output, + verbose=verbose, + plan=plan, + allow_destructive=allow_destructive, + continue_on_error=continue_on_error, + allow_config_drift=allow_config_drift, + allow_hooks=allow_hooks, + write=write, + ok_if_locked=ok_if_locked, + ) + ) + + +@app.command() +def schema() -> int: + """Print the document's JSON Schema, for an editor to validate against.""" + sys.stdout.write(json.dumps(PartitionsDocument.model_json_schema(), indent=2) + "\n") + return ExitCode.OK + + +# ── Leaving the process ───────────────────────────────────────────────────────── + + +def main(argv: Sequence[str] | None = None) -> int: + """Run one command and answer with its exit status. + + Parsing is left to typer, but the process leaves through here, so that a + usage error -- a misspelled flag, no command at all -- has a code of its own + rather than the ``2`` argparse and click both use, which this tool means + "drift" by. A CronJob alerting on drift must not page over a typo. + + Args: + argv: Arguments, or None to read ``sys.argv``. + + Returns: + The exit status, as :class:`~pg_partsmith.cli.exit_codes.ExitCode`. + """ + _survive_any_console_encoding() + try: + outcome = app(args=list(argv) if argv is not None else None, prog_name="pg-partsmith", standalone_mode=False) + except typer.Abort: # pragma: no cover - interactive only + return _failed("interrupted", ExitCode.FAILED) + except Exception as exc: + if not _is_usage_error(exc): + raise + _usage_error(exc) + return ExitCode.USAGE + return _as_code(outcome) + + +def _execute(invocation: _Invocation) -> ExitCode: + """Read, connect, dispatch, print, and turn every failure into its code.""" + logging.basicConfig( + stream=sys.stderr, + level=logging.DEBUG if invocation.verbose else logging.WARNING, + format="%(levelname)s %(name)s: %(message)s", + ) + try: + # A Runner with a loop factory rather than asyncio.run: the process is left + # with the current-loop state it had, which matters to a program that + # embeds main() next to a loop of its own, and to a test session. + with asyncio.Runner(loop_factory=asyncio.new_event_loop) as runner: + result = runner.run(_supervised(invocation)) + except (ConfigError, InvalidPartitionConfigError, PlanConfigMismatchError) as exc: + return _failed(str(exc), ExitCode.CONFIG) + except LockAcquisitionError as exc: + # An overlapping run is ordinary operation, not a failure to page on -- + # and for an init container, which restarts on anything non-zero, it + # is not even worth a code of its own. + return _failed(str(exc), ExitCode.OK if invocation.ok_if_locked else ExitCode.LOCKED) + except (PartitionError, CommandHookError, PythonHookError) as exc: + # A run that stopped on its own terms -- a hook refused, a plan went + # stale, a partition is still referenced -- is a finding for a person, + # the way --continue-on-error would have recorded it. Not a traceback. + return _failed(str(exc), ExitCode.FINDINGS) + except (ArgumentError, NoSuchModuleError) as exc: + # A connection string SQLAlchemy cannot parse, or one naming a driver + # that is not installed: the deployment's to fix, before any database. + return _failed(f"the connection string is not usable: {exc}", ExitCode.CONFIG) + except _DATABASE_ERRORS as exc: + # A refused connection surfaces as a bare OSError and a rejected + # password as the driver's own error: both come before SQLAlchemy has + # a DBAPI error to wrap. Reading the document is already behind + # ConfigError, so anything here is the database. + return _failed(f"database error: {exc}", ExitCode.CONNECTION) + except _StopSignalError as exc: + word, code = _STOP_SIGNALS[exc.signum] + return _failed(word, code) + except KeyboardInterrupt: # pragma: no cover - the Windows route; CI runs on Linux + # Where the loop cannot take a signal handler of its own -- Windows -- + # asyncio.run's own Ctrl+C handling cancels the task and raises this + # once it has cleaned up. The same outcome, by the runner's route. + return _failed("interrupted", ExitCode.INTERRUPTED) + + text = result.render(output=invocation.output.value) + if invocation.write is not None: + try: + _write_atomically(invocation.write, text + "\n") + except OSError as exc: + # A textfile directory the container's user cannot write -- a + # root-owned hostPath, usually -- is the deployment's to fix. The + # run has done its work; say which path, and leave the previous + # file where it was. + return _failed(f"Cannot write {invocation.write}: {exc.strerror or exc}", ExitCode.CONFIG) + logger.info("wrote %s output to %s", invocation.output.value, invocation.write) + elif text: + sys.stdout.write(text + "\n") + return result.code + + +class _StopSignalError(Exception): + """The run was stopped by a signal, and has cleaned up on the way here.""" + + def __init__(self, signum: int) -> None: + super().__init__(signum) + self.signum = signum + + +_STOP_SIGNALS: dict[int, tuple[str, ExitCode]] = { + signal.SIGINT: ("interrupted", ExitCode.INTERRUPTED), + signal.SIGTERM: ("terminated", ExitCode.TERMINATED), +} + + +async def _supervised(invocation: _Invocation) -> CommandResult: + """Run the command, with a stop signal turned into a cancellation that cleans up. + + ``SIGTERM`` is what a pod is sent at its deadline, and Python's default for + it is to die on the spot -- no ``finally``, no lock released by us, no line + in the log. The database survives that (a dropped connection cancels the + statement and rolls the transaction back; a session lock goes with the + session), but "survives" is not "was told". Cancelling the task instead + takes the same path a raised exception takes: the statement is cancelled + by the driver, the lock is released, the engine is disposed, a hook's child + process is stopped, and the exit code says which signal it was. + + Where the loop cannot take signal handlers -- a worker thread, Windows -- + nothing is installed and ``asyncio.run``'s own Ctrl+C handling applies. + """ + loop = asyncio.get_running_loop() + task = asyncio.current_task() + received: list[int] = [] + + def stop(signum: int) -> None: + # A second signal changes nothing: the first already cancelled the run, + # and what is left is the cleanup, which is worth letting finish. + if not received and task is not None: + received.append(signum) + task.cancel() + + installed: list[int] = [] + for signum in _STOP_SIGNALS: + try: + loop.add_signal_handler(signum, stop, signum) + except (NotImplementedError, RuntimeError, ValueError): # pragma: no cover - Windows, or a worker thread + break + installed.append(signum) + try: + return await _run(invocation) + except asyncio.CancelledError: + if received: + raise _StopSignalError(received[0]) from None + raise + finally: + for signum in installed: + loop.remove_signal_handler(signum) + + +async def _run(invocation: _Invocation) -> CommandResult: + """Read the document, bring up the engine, and dispatch one command.""" + document = load_document(invocation.config) + _check_python_hooks(document, invocation.config) + configs = select_configs(document, invocation.tables) + url = async_url(resolve_dsn(document, override=invocation.dsn)) + + engine = create_async_engine(url) + try: + try: + hooks = _hooks( + document, command=invocation.command, config=invocation.config, allow_hooks=invocation.allow_hooks + ) + kit = PartitionToolkit.from_options(engine, document.runtime, hooks=hooks) + except ValueError as exc: + # The models refuse what they can see; whatever the wiring still + # objects to is the document's fault all the same. + raise ConfigError(str(exc)) from exc + if invocation.command == "inspect": + return await run_inspect(kit, configs) + if invocation.command == "plan": + result = await run_plan(kit, configs, check=invocation.check, locks=invocation.locks) + if invocation.save is not None: + _save_plan(invocation.save, result) + return result + if invocation.command == "apply": + return await run_apply( + kit, + configs, + plans=load_plans(invocation.plan) if invocation.plan is not None else None, + allow_destructive=invocation.allow_destructive, + continue_on_error=invocation.continue_on_error, + allow_config_drift=invocation.allow_config_drift, + ) + return await run_validate(kit, configs) + finally: + await engine.dispose() + + +def _hooks( + document: PartitionsDocument, *, command: str, config: Path, allow_hooks: bool +) -> list[PartitionLifecycleHooks] | None: + """The hooks this run honours, and a refusal when it was not told to honour any. + + Hooks fire during ``apply`` alone, so nothing else has to decide. Ignoring a + configured ``before_drop`` silently would be the worst outcome available: an + operator would read the file, believe their archiver ran, and be wrong. So a + document declaring hooks is refused rather than quietly stripped. + + Raises: + ConfigError: If the document names hooks and ``--allow-hooks`` was not given. + """ + hooks = document.hooks + if hooks is None or hooks.is_empty: + return None + if command != "apply": + return None + if not allow_hooks: + named = ", ".join(phase.value for phase in hooks.actions()) + msg = ( + f"This document runs code at {named}. It executes in a process holding DDL credentials, " + "so it runs only when asked for: pass --allow-hooks, or remove the hooks section." + ) + raise ConfigError(msg) + # Annotated as the protocol, not the class: a list is invariant, and the + # toolkit takes any hook implementation. + configured: list[PartitionLifecycleHooks] = [] + if hooks.commands(): + configured.append(CommandHooks(hooks.commands(), timeout_seconds=hooks.timeout_seconds)) + sources, names = load_python_hooks(hooks, config.resolve().parent) + if sources: + configured.append(PythonHooks(sources, names=names)) + return configured + + +def _check_python_hooks(document: PartitionsDocument, config: Path) -> None: + """Read and compile every file-backed block, whatever the command. + + Inline blocks were compiled when the document validated; a file has to be + found and read first, and ``validate`` is the command that should find it + missing or broken -- not ``apply``, and not at 03:00. + """ + if document.hooks is not None and document.hooks.python_blocks(): + load_python_hooks(document.hooks, config.resolve().parent) + + +def _write_atomically(path: Path, text: str) -> None: + """Write next to the target and rename, so a reader never sees half a file. + + A node_exporter textfile collector reads whenever it likes; a partially + written file parses as a broken one, and a broken one is dropped whole. + """ + temporary = path.with_name(f".{path.name}.{os.getpid()}.tmp") + temporary.write_text(text, encoding="utf-8") + temporary.replace(path) + + +def _save_plan(path: Path, result: CommandResult) -> None: + """Write the plan envelope where ``apply --plan`` can read it back. + + Written whatever ``--output`` says: the file is the artifact between plan + and apply, and what a person reads on the terminal is a separate question. + """ + if result.payload is None: # pragma: no cover - every command builds one + msg = "the command produced no plan to save" + raise ConfigError(msg) + try: + path.write_text(to_json(result.payload) + "\n", encoding="utf-8") + except OSError as exc: + # Raised inside the run, where a bare OSError would be read as the database's. + msg = f"Cannot write the plan to {path}: {exc.strerror or exc}" + raise ConfigError(msg) from exc + + +def _as_code(outcome: object) -> ExitCode: + """What ``app()`` handed back, as an exit code. + + A command returns its :class:`ExitCode`; ``--help`` and ``--version`` leave + through click's own ``Exit`` and come back as ``0``. + """ + if isinstance(outcome, ExitCode): + return outcome + if isinstance(outcome, int): + return ExitCode(outcome) if outcome in set(ExitCode) else ExitCode.FAILED + return ExitCode.OK + + +def _is_usage_error(exc: Exception) -> bool: + """Whether parsing, not the command, raised this. + + Recognised by click's own ``UsageError`` interface rather than by class: + typer vendors its copy of click from 0.27 and imports the real one before + that, so the class lives in two places across the versions this supports, + one of them private. The interface -- ``exit_code`` of ``2`` and + ``format_message`` -- is the documented, stable part. + """ + return getattr(exc, "exit_code", None) == 2 and callable(getattr(exc, "format_message", None)) + + +def _usage_error(exc: Exception) -> None: + """Say what was wrong with the invocation, and how it is spelled. + + No command at all is the one usage error that has already explained + itself: click prints the help for it before raising, so there is nothing + to add but the exit code. + """ + if type(exc).__name__ == "NoArgsIsHelpError": + return + ctx = getattr(exc, "ctx", None) + if ctx is not None: + sys.stderr.write(ctx.get_usage() + "\n") + sys.stderr.write(f"pg-partsmith: {exc.format_message()}\n") # type: ignore[attr-defined] + + +def _failed(message: str, code: ExitCode) -> ExitCode: + """Say what went wrong on stderr, and answer with the code that names it. + + Not a log record: this is the message a person reads. The traceback behind + it is kept for ``--verbose``, where the debug stream is already on. + """ + sys.stderr.write(f"pg-partsmith: {message}\n") + logger.debug("command failed with %s", code.name, exc_info=True) + return code + + +def _survive_any_console_encoding() -> None: + """Never die on a character the console cannot show. + + Human output has an em dash in it, and a Windows pipe or a bare POSIX + locale may be encoding in something without one. An escaped character in + a CronJob log beats a traceback there. + """ + for stream in (sys.stdout, sys.stderr): + reconfigure = getattr(stream, "reconfigure", None) + if reconfigure is None: + continue + try: + reconfigure(errors="backslashreplace") + except (OSError, ValueError): # pragma: no cover - a closed or exotic stream + pass diff --git a/pg_partsmith/cli/metrics.py b/pg_partsmith/cli/metrics.py new file mode 100644 index 0000000..8ad05ab --- /dev/null +++ b/pg_partsmith/cli/metrics.py @@ -0,0 +1,221 @@ +"""The same run, as numbers a Prometheus node_exporter can pick up. + +Most systems that partition PostgreSQL have no monitoring of it at all -- they +find out at 03:00, from an insert that PostgreSQL rejected. A CronJob already +runs this tool on a schedule, so the cheapest possible monitoring is for that +run to leave a textfile behind: + + pg-partsmith plan -c partitions.yaml --output metrics > /var/lib/node_exporter/partsmith.prom + +Every command can do it. The numbers are read off the JSON envelope rather than +collected separately, so a metric cannot disagree with what the same run +printed. + +The format is the text exposition one: ``HELP``, ``TYPE``, then samples. Every +value is a gauge, because a one-shot job cannot own a counter -- the next run is +a new process with no memory of this one. +""" + +from __future__ import annotations + +from collections import Counter +from collections.abc import Sequence +from datetime import UTC, datetime +from typing import Any + +__all__ = ["render_metrics"] + +_PREFIX = "pg_partsmith" + + +def render_metrics(payload: dict[str, Any]) -> str: + """Render one command's envelope as Prometheus text exposition. + + Args: + payload: The envelope the command built. + + Returns: + The metrics, ending in a newline, ready to write to a textfile + collector's directory. + """ + command = str(payload.get("command", "unknown")) + lines: list[str] = [] + _emit( + lines, + f"{_PREFIX}_run_timestamp_seconds", + "When this run happened, so a stale textfile is visible as one.", + [({"command": command}, _timestamp(payload.get("generated_at")))], + ) + + tables = [entry for entry in payload.get("tables", []) if isinstance(entry, dict)] + renderer = _RENDERERS.get(command) + if renderer is not None: + renderer(lines, tables) + return "\n".join(lines) + "\n" + + +# ── Per command ───────────────────────────────────────────────────────────────── + + +def _plan_metrics(lines: list[str], tables: list[dict[str, Any]]) -> None: + """What is waiting to be applied, and what nothing will apply.""" + pending: list[tuple[dict[str, str], float]] = [] + relations: list[tuple[dict[str, str], float]] = [] + findings: list[tuple[dict[str, str], float]] = [] + for entry in tables: + table = str(entry.get("table", "")) + plan = entry.get("plan") or {} + operations = plan.get("operations", []) + counted = Counter(str(op.get("kind", "unknown")) for op in operations) + for kind in ("create", "attach", "detach", "drop"): + pending.append(({"table": table, "kind": kind}, counted.get(kind, 0))) + relations.append(({"table": table}, _relation_count(operations))) + by_severity = Counter(str(f.get("severity", "unknown")) for f in plan.get("findings", [])) + for severity in ("info", "warning"): + findings.append(({"table": table, "severity": severity}, by_severity.get(severity, 0))) + + _emit(lines, f"{_PREFIX}_pending_operations", "Operations a maintenance run would carry out.", pending) + _emit( + lines, + f"{_PREFIX}_pending_relations", + "Relations those operations would create, subtrees included.", + relations, + ) + _emit( + lines, + f"{_PREFIX}_findings", + "What the planner saw and left alone. A warning needs a person.", + findings, + ) + + +def _inspect_metrics(lines: list[str], tables: list[dict[str, Any]]) -> None: + """What exists, and what is waiting to be cleaned up.""" + partitions: list[tuple[dict[str, str], float]] = [] + orphans: list[tuple[dict[str, str], float]] = [] + oldest: list[tuple[dict[str, str], float]] = [] + partitioned: list[tuple[dict[str, str], float]] = [] + now = datetime.now(UTC) + for entry in tables: + table = str(entry.get("table", "")) + tree = entry.get("tree") + partitioned.append(({"table": table}, 0 if tree is None else 1)) + if tree is None: + continue + detached = [o for o in tree.get("orphans", []) if isinstance(o, dict)] + partitions.append(({"table": table}, _count_nodes(tree.get("root", {})))) + orphans.append(({"table": table}, len(detached))) + age = _oldest_age_seconds(detached, now) + if age is not None: + oldest.append(({"table": table}, age)) + + _emit(lines, f"{_PREFIX}_partitioned", "1 when the table is partitioned at all, 0 when it is not.", partitioned) + _emit(lines, f"{_PREFIX}_partitions", "Relations attached below the root, at every level.", partitions) + _emit(lines, f"{_PREFIX}_detached_partitions", "Detached partitions this library has not dropped yet.", orphans) + _emit( + lines, + f"{_PREFIX}_oldest_detached_age_seconds", + "Age of the oldest detached partition. A number that only grows means drops are not happening.", + oldest, + ) + + +def _validate_metrics(lines: list[str], tables: list[dict[str, Any]]) -> None: + """Whether the document still describes the database.""" + valid = [({"table": str(entry.get("table", ""))}, 1 if entry.get("ok") else 0) for entry in tables] + _emit(lines, f"{_PREFIX}_config_valid", "1 when the table matches the configuration describing it.", valid) + + +def _apply_metrics(lines: list[str], tables: list[dict[str, Any]]) -> None: + """What the run actually did, and what it could not.""" + applied: list[tuple[dict[str, str], float]] = [] + issues: list[tuple[dict[str, str], float]] = [] + for entry in tables: + table = str(entry.get("table", "")) + result = entry.get("result") or {} + for name in ("created", "repaired", "attached", "detached", "dropped"): + applied.append(({"table": table, "operation": name}, result.get(f"{name}_count", 0))) + issues.append(({"table": table}, len(result.get("issues", [])))) + + _emit(lines, f"{_PREFIX}_applied_operations", "What this run carried out.", applied) + _emit(lines, f"{_PREFIX}_issues", "Problems this run reported and did not fail on.", issues) + + +_RENDERERS = { + "plan": _plan_metrics, + "inspect": _inspect_metrics, + "validate": _validate_metrics, + "apply": _apply_metrics, +} + + +# ── Module helpers ────────────────────────────────────────────────────────────── + + +def _emit(lines: list[str], name: str, help_text: str, samples: Sequence[tuple[dict[str, str], float]]) -> None: + """One metric family: its documentation, its type, and every sample of it.""" + if not samples: + return + lines.append(f"# HELP {name} {help_text}") + lines.append(f"# TYPE {name} gauge") + for labels, value in samples: + lines.append(f"{name}{_labels(labels)} {_number(value)}") + + +def _labels(labels: dict[str, str]) -> str: + """Render a label set, escaping what the exposition format reserves.""" + if not labels: + return "" + rendered = ",".join(f'{key}="{_escape(value)}"' for key, value in labels.items()) + return "{" + rendered + "}" + + +def _escape(value: str) -> str: + return value.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n") + + +def _number(value: float) -> str: + """Integers without a decimal point, everything else as a plain float.""" + return str(int(value)) if float(value).is_integer() else repr(float(value)) + + +def _timestamp(generated_at: object) -> float: + """The envelope's instant as a UNIX timestamp, falling back to now.""" + if isinstance(generated_at, str): + try: + return datetime.fromisoformat(generated_at).timestamp() + except ValueError: + pass + return datetime.now(UTC).timestamp() + + +def _relation_count(operations: list[Any]) -> int: + """Every relation the creations would make, nested children included.""" + total = 0 + for operation in operations: + if isinstance(operation, dict) and operation.get("kind") == "create": + total += 1 + _relation_count(operation.get("children", [])) + return total + + +def _count_nodes(node: dict[str, Any]) -> int: + """Relations below the root, the root itself not counted.""" + children = node.get("children", []) + return sum(1 + _count_nodes(child) for child in children if isinstance(child, dict)) + + +def _oldest_age_seconds(orphans: list[dict[str, Any]], now: datetime) -> float | None: + """How long the longest-waiting orphan has been detached, when any says.""" + ages = [] + for orphan in orphans: + detached_at = orphan.get("detached_at") + if not isinstance(detached_at, str): + continue + try: + moment = datetime.fromisoformat(detached_at) + except ValueError: + continue + if moment.tzinfo is None: + moment = moment.replace(tzinfo=UTC) + ages.append((now - moment).total_seconds()) + return max(ages) if ages else None diff --git a/pg_partsmith/cli/render.py b/pg_partsmith/cli/render.py new file mode 100644 index 0000000..48c85e3 --- /dev/null +++ b/pg_partsmith/cli/render.py @@ -0,0 +1,116 @@ +"""Two ways to say the same thing: one for a person, one for a pipe. + +The JSON is the models' own dump, never a shape assembled here -- a hand-rolled +one drifts from the library the first time a field is added. It is emitted with +``by_alias=True``, which is the vocabulary a configuration file is written in +(``kind``, ``method``, ``schema``), so what comes out of ``plan`` and what goes +into a document are one language. +""" + +from __future__ import annotations + +import json +from datetime import UTC, datetime +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from pg_partsmith.plan import MaintenancePlan + from pg_partsmith.topology import ActualTree, PartitionNode + +__all__ = ["OUTPUT_VERSION", "describe_locks", "describe_tree", "envelope", "plan_entry", "to_json", "tree_entry"] + +OUTPUT_VERSION = 1 +"""Schema version of the JSON envelope, so a reader can tell what it is holding.""" + + +def envelope(command: str, tables: list[dict[str, Any]]) -> dict[str, Any]: + """The outer shape every JSON output shares. + + Args: + command: The command that produced it. + tables: One entry per table, in the order they were handled. + + Returns: + The envelope, ready to serialize. + """ + return { + "version": OUTPUT_VERSION, + "command": command, + "generated_at": datetime.now(UTC).isoformat(), + "tables": tables, + } + + +def to_json(payload: dict[str, Any]) -> str: + """Render an envelope, pretty enough to read and stable enough to diff.""" + return json.dumps(payload, indent=2, sort_keys=False, default=str) + + +def plan_entry(plan: MaintenancePlan) -> dict[str, Any]: + """One table's plan, as the model dumps it.""" + return {"table": plan.table_name, "plan": plan.model_dump(mode="json", by_alias=True)} + + +def tree_entry(table_name: str, tree: ActualTree | None) -> dict[str, Any]: + """One table's tree, as the model dumps it. ``None`` when it is not partitioned.""" + return { + "table": table_name, + "tree": None if tree is None else tree.model_dump(mode="json", by_alias=True), + } + + +def describe_locks(plan: MaintenancePlan) -> str: + """What each operation will lock, which is what a window is scheduled around. + + One line per top-level operation. A subtree is built detached and attached + once, so its children take nothing the parent's line does not already say. + An operation that cannot run in a transaction block says so: it is the one + a crash leaves half-done, and the next run completes. + """ + if plan.is_noop: + return "locks: none, nothing to do" + lines = ["locks:"] + for op in plan.operations: + transactional = "" if op.capabilities.transactional else " (outside a transaction block)" + lines.append(f" {op.kind.value.upper()} {op.target}{transactional}") + lines.append(f" {op.capabilities.lock}") + return "\n".join(lines) + + +def describe_tree(tree: ActualTree) -> str: + """Render a tree the way a person reads one: indented, bounds on each line.""" + lines = [f"{tree.root.name} — {tree.root.describe_topology()}"] + lines.extend(_describe_children(tree.root, depth=1)) + if tree.orphans: + lines.append(" detached, ours to clean up:") + for orphan in tree.orphans: + when = "" if orphan.detached_at is None else f" detached {orphan.detached_at.isoformat()}" + lines.append(f" {orphan.name}{when}") + return "\n".join(lines) + + +def _describe_children(node: PartitionNode, depth: int) -> list[str]: + lines: list[str] = [] + for child in node.children: + lines.append(f"{' ' * depth}{child.relname}{_annotations(child)}") + lines.extend(_describe_children(child, depth + 1)) + return lines + + +def _annotations(node: PartitionNode) -> str: + """What is worth saying about one node, after its name. + + The bound is shown as ``pg_get_expr`` rendered it rather than re-spelled + from the parsed form: an operator comparing the output against + ``\\d+ events`` should see the same string PostgreSQL shows them. + """ + parts = [] + if node.bounds_expr: + parts.append(node.bounds_expr) + if node.is_foreign: + parts.append("foreign") + if node.detach_pending: + parts.append("detach pending") + if node.has_unaddressable_children: + parts.append("children omitted: unaddressable names") + return f" — {', '.join(parts)}" if parts else "" diff --git a/pg_partsmith/console.py b/pg_partsmith/console.py new file mode 100644 index 0000000..073760f --- /dev/null +++ b/pg_partsmith/console.py @@ -0,0 +1,30 @@ +"""The console script: what ``pip install pg-partsmith`` puts on PATH, with or without the extra. + +The package registers ``pg-partsmith`` unconditionally, since a script cannot +be conditional on an extra. A bare install therefore has the command too, and +there one sentence and exit 64 beat a ModuleNotFoundError traceback. This +module imports nothing the extra brings until it is asked to run. +""" + +from __future__ import annotations + +import sys +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Sequence + +__all__ = ["main"] + +USAGE = 64 +"""``EX_USAGE``: the command line itself is not usable here.""" + + +def main(argv: Sequence[str] | None = None) -> int: + """Run the command line, or say what is missing.""" + try: + from pg_partsmith.cli import main as run # noqa: PLC0415 - the import that needs the extra + except ImportError as exc: + sys.stderr.write(f'pg-partsmith needs the cli extra: pip install "pg-partsmith[cli]" ({exc})\n') + return USAGE + return run(argv) diff --git a/pg_partsmith/constants.py b/pg_partsmith/constants.py index cf1f3a3..bb9307c 100644 --- a/pg_partsmith/constants.py +++ b/pg_partsmith/constants.py @@ -28,6 +28,9 @@ DEFAULT_DROP_RETRY_DELAY = 0.5 DEFAULT_DROP_MAX_BACKOFF = 300.0 +DEFAULT_HOOK_TIMEOUT_SECONDS = 300.0 +"""How long a configured command hook may run before it is killed: it holds the table's lock.""" + # Hashed into advisory lock IDs / Redis keys; changing it breaks cross-version # mutual exclusion between deployments. DEFAULT_LOCK_PREFIX = "partitioner" diff --git a/pg_partsmith/document.py b/pg_partsmith/document.py new file mode 100644 index 0000000..dc4f714 --- /dev/null +++ b/pg_partsmith/document.py @@ -0,0 +1,405 @@ +"""One document describing every partitioned table of a deployment. + +A real deployment maintains several tables in one run, and describes them in a +file -- a ConfigMap, a mounted YAML, a JSON blob -- rather than in Python. This +module is that document, as models: :class:`PartitionTableSpec` is one table's +entry, :class:`ToolkitOptions` the wiring every table is maintained through, +and :class:`PartitionsDocument` the whole file. + +Nothing here reads a file or opens a connection. The document is parsed by +whoever owns the format (``json.loads``, ``tomllib.load``, a YAML loader) and +validated here, so one field list serves a file, an environment and a Python +caller alike -- :class:`~pg_partsmith.settings.PartitionTableSettings` is the +same fields read from the environment. + +Usage:: + + document = PartitionsDocument.model_validate(yaml.safe_load(text)) + kit = PartitionToolkit.from_options(engine, document.runtime) + for config in document.configs(): + await kit.service.maintain(config) +""" + +from __future__ import annotations + +from datetime import UTC, tzinfo +from typing import Annotated, Any, Literal + +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator + +from .boundaries import resolve_codec +from .constants import ( + DEFAULT_CREATE_AHEAD_COUNT, + DEFAULT_DDL_TIMEOUT_SECONDS, + DEFAULT_DDL_TIMEZONE, + DEFAULT_DROP_LOCK_TIMEOUT_MS, + DEFAULT_DROP_MAX_BACKOFF, + DEFAULT_DROP_MAX_RETRIES, + DEFAULT_DROP_RETRY_DELAY, + DEFAULT_HOOK_TIMEOUT_SECONDS, + DEFAULT_LOCK_PREFIX, + DEFAULT_RETENTION_COUNT, +) +from .entities import PartitionGranularity, PartitionStrategy, PartitionType, TablePartitionConfig +from .events import HookPhase +from .python_hooks import compile_hook_source +from .strategies import BasePeriodCalculator, get_period_calculator + +__all__ = ["HookAction", "HookOptions", "PartitionTableSpec", "PartitionsDocument", "PythonHook", "ToolkitOptions"] + + +class PartitionTableSpec(BaseModel): + """One table's entry: a configuration written down rather than constructed. + + The flat fields describe the ordinary time-partitioned table; any other + topology is given as ``scheme``, which takes precedence over them; + ``lifecycle`` and ``leaves`` take the same JSON their models dump. + ``PartitionType``, ``PartitionStrategy`` and ``PartitionGranularity`` are + ``StrEnum`` values, so their lowercase spellings are what a file writes. + + ``schema`` is accepted as a spelling of ``schema_name``, because that is + what :class:`~pg_partsmith.TablePartitionConfig` dumps and what an operator + writes. + + Unknown keys are refused rather than ignored: a misspelled field in a file + nobody reads until 03:00 is a silent policy, not a typo. + """ + + model_config = ConfigDict(extra="forbid", populate_by_name=True) + + schema_name: str | None = Field(default=None, description="PostgreSQL schema (omit for public)") + table_name: str = Field(..., description="Partitioned table name") + partition_type: PartitionType | None = Field( + default=None, description="Checked against the scheme: range, list, hash" + ) + partition_strategy: PartitionStrategy | None = Field( + default=None, + description="Checked against the scheme: time_based, numeric_based, value_based, hash_based", + ) + partition_column: str | None = Field(default=None, description="Leading column of a time-partitioned root") + trailing_partition_columns: tuple[str, ...] = Field( + default=(), + description='Rest of a composite partition key, as JSON: ["tenant_id"]', + ) + granularity: PartitionGranularity | None = Field( + default=None, + description="Time granularity: hour, day, week, month, quarter, year", + ) + tz: str = Field(default="UTC", description="IANA timezone the calendar is computed in") + boundary_codec: str | None = Field( + default=None, + description="Physical key encoding by name: uuidv7, epoch_seconds, epoch_milliseconds", + ) + create_ahead_count: int = Field( + default=DEFAULT_CREATE_AHEAD_COUNT, + ge=1, + description="Number of periods to ensure exist, including the current period", + ) + retention_count: int = Field( + default=DEFAULT_RETENTION_COUNT, + ge=1, + description="Number of newest periods to keep, current one included", + ) + scheme: dict[str, Any] | None = Field( + default=None, + description=( + "Any topology, as JSON: " + '{"method": "range", "key": "created_at", "boundaries": {"kind": "time", "granularity": "week"}, ' + '"child": {"method": "hash", "key": "tenant_id", "modulus": 4}}' + ), + ) + lifecycle: dict[str, Any] | None = Field( + default=None, + description='Lifecycle policy, as JSON: {"creation": {"kind": "create_ahead", "count": 3}, ...}', + ) + leaves: dict[str, Any] | None = Field( + default=None, + description=( + "Leaf backend, as JSON: " + '{"kind": "local", "tablespace": "fast", "storage_parameters": {"fillfactor": 70}} or ' + '{"kind": "foreign", "server": "archive", "options": {"table_name": "{relname}"}}' + ), + ) + + @model_validator(mode="before") + @classmethod + def _accept_schema_as_schema_name(cls, data: Any) -> Any: + """Take ``schema``, the spelling a configuration dumps, as ``schema_name``.""" + return _with_schema_name(data) if isinstance(data, dict) else data + + def to_config(self) -> TablePartitionConfig: + """Build a :class:`~pg_partsmith.TablePartitionConfig` from these fields.""" + fields: dict[str, Any] = {"schema": self.schema_name, "table_name": self.table_name} + if self.partition_type is not None: + fields["partition_type"] = self.partition_type + if self.partition_strategy is not None: + fields["partition_strategy"] = self.partition_strategy + + if self.scheme is not None: + fields["scheme"] = self.scheme + else: + fields.update( + partition_column=self.partition_column, + trailing_partition_columns=self.trailing_partition_columns, + granularity=self.granularity, + tz=self.tz, + boundary_codec=self.boundary_codec, + ) + + if self.lifecycle is not None: + fields["lifecycle"] = self.lifecycle + else: + fields.update(create_ahead_count=self.create_ahead_count, retention_count=self.retention_count) + if self.leaves is not None: + fields["leaves"] = self.leaves + + return TablePartitionConfig(**fields) + + def get_period_calculator(self, tz: tzinfo = UTC) -> BasePeriodCalculator: + """Return the period calculator matching :attr:`granularity`. + + Args: + tz: Timezone the calculator works in (``datetime.UTC`` or a keyed + :class:`zoneinfo.ZoneInfo`). HOUR accepts only UTC. + + Raises: + ValueError: If ``granularity`` is ``None`` or has no registered + calculator, or ``tz`` is unsupported for it. + """ + if self.granularity is None: + msg = "Cannot resolve a period calculator: granularity is not set" + raise ValueError(msg) + return get_period_calculator(self.granularity, tz=tz) + + +class ToolkitOptions(BaseModel): + """The wiring every table in the document is maintained through. + + One field per keyword of ``PartitionToolkit.from_engine``, so a document + configures the wiring the way code does. ``boundary_codec`` is a name here + (``uuidv7``, ``epoch_seconds``, ``epoch_milliseconds``); :meth:`to_kwargs` + resolves it to the codec itself. + """ + + model_config = ConfigDict(frozen=True, extra="forbid") + + marker_prefix: str | None = Field(default=None, description="COMMENT prefix marking detached partitions as ours") + ddl_timezone: str | None = Field( + default=DEFAULT_DDL_TIMEZONE, + description="Session timezone naive boundary literals are written and read in", + ) + ddl_timeout_seconds: float = Field(default=DEFAULT_DDL_TIMEOUT_SECONDS, gt=0, description="Statement timeout") + boundary_codec: str | None = Field(default=None, description="Codec name encoded bounds are read with") + lock_prefix: str = Field(default=DEFAULT_LOCK_PREFIX, description="Prefix of the advisory lock keys") + lock_min_interval_seconds: float = Field( + default=0.0, ge=0, description="Minimum seconds between acquire attempts per table; 0 disables" + ) + drop_allow_unmanaged: bool = Field(default=False, description="Allow dropping a relation with no ownership marker") + drop_lock_timeout_ms: int = Field(default=DEFAULT_DROP_LOCK_TIMEOUT_MS, ge=0, description="lock_timeout for a drop") + drop_max_retries: int = Field(default=DEFAULT_DROP_MAX_RETRIES, ge=1, description="Attempts a drop makes") + drop_retry_delay: float = Field(default=DEFAULT_DROP_RETRY_DELAY, ge=0, description="Delay before the retry") + drop_max_backoff: float = Field(default=DEFAULT_DROP_MAX_BACKOFF, ge=0, description="Ceiling on that backoff") + + @field_validator("boundary_codec") + @classmethod + def _a_codec_that_exists(cls, value: str | None) -> str | None: + # Resolved here, where `validate` sees it and names the field, and again + # in to_kwargs for the object itself. + resolve_codec(value) + return value + + def to_kwargs(self) -> dict[str, Any]: + """These options as the keywords ``PartitionToolkit.from_engine`` takes. + + Raises: + ValueError: If ``boundary_codec`` names no known codec. + """ + return {**self.model_dump(), "boundary_codec": resolve_codec(self.boundary_codec)} + + +class PythonHook(BaseModel): + """A block of Python to run at one lifecycle moment, inline or from a file. + + Exactly one of the two. An inline block is compiled the moment the document + is validated, so a ``SyntaxError`` is a validation error with a line number + in it rather than something a CronJob finds at 03:00. A file is resolved + and compiled by whoever reads the document, relative to where the document + lives, since only they know where that is. + + Attributes: + python: The block itself. + python_file: A path to it, for blocks past a few lines -- editor + support, and a file that can be tested on its own. + """ + + model_config = ConfigDict(frozen=True, extra="forbid") + + python: str | None = Field(default=None, description="The block, inline") + python_file: str | None = Field(default=None, description="A path to the block, relative to the document") + + @model_validator(mode="after") + def _one_source_that_compiles(self) -> PythonHook: + """Exactly one of the two, and the inline one parses.""" + if (self.python is None) == (self.python_file is None): + msg = "a Python hook is either 'python' (a block) or 'python_file' (a path), not both and not neither" + raise ValueError(msg) + if self.python is not None: + if not self.python.strip(): + msg = "the Python block is empty" + raise ValueError(msg) + try: + compile_hook_source(self.python, name="") + except SyntaxError as exc: + msg = f"the Python block does not parse: {exc.msg} (line {exc.lineno})" + raise ValueError(msg) from exc + return self + + +HookAction = Annotated[tuple[str, ...], Field(min_length=1)] | PythonHook +"""What a phase runs: a command as an argument vector, never an empty one, or a block of Python.""" + + +class HookOptions(BaseModel): + """What to run at each lifecycle moment, as a file writes it. + + One field per phase, spelled out rather than a free mapping, so a + misspelled ``befor_drop`` is refused where it is written instead of + silently never running -- which, for the phase that exports data before a + ``DROP``, is the difference between an archive and no archive. + + A phase takes either a command -- an argument vector, never a shell string, + so a partition name can never be read as syntax -- or a block of Python, + inline as ``python`` or from a file as ``python_file``. + + Hooks fire during ``apply`` only. ``plan`` issues no DDL and runs no hook, + which is what makes a plan safe to compute anywhere. + """ + + model_config = ConfigDict(frozen=True, extra="forbid") + + timeout_seconds: float = Field( + default=DEFAULT_HOOK_TIMEOUT_SECONDS, + gt=0, + description="How long a command may run before it is killed; it holds the table's lock", + ) + before_create: HookAction | None = Field(default=None, description="Before a partition exists") + after_create: HookAction | None = Field(default=None, description="After it is created and attached") + before_attach: HookAction | None = Field(default=None, description="Before a detached partition returns") + after_attach: HookAction | None = Field(default=None, description="After it is taking rows again") + before_detach: HookAction | None = Field(default=None, description="While its rows are still reachable") + after_detach: HookAction | None = Field(default=None, description="After it stands alone") + before_drop: HookAction | None = Field(default=None, description="The last moment its rows exist") + after_drop: HookAction | None = Field(default=None, description="After the table is gone") + + def actions(self) -> dict[HookPhase, HookAction]: + """Everything a phase was given, in lifecycle order.""" + return {phase: action for phase in HookPhase if (action := getattr(self, phase.value)) is not None} + + def commands(self) -> dict[HookPhase, tuple[str, ...]]: + """The phases a command was given for, in lifecycle order.""" + return {phase: action for phase, action in self.actions().items() if isinstance(action, tuple)} + + def python_blocks(self) -> dict[HookPhase, PythonHook]: + """The phases a block of Python was given for, in lifecycle order.""" + return {phase: action for phase, action in self.actions().items() if isinstance(action, PythonHook)} + + @property + def is_empty(self) -> bool: + """True when the section names nothing to run at all.""" + return not self.actions() + + +class PartitionsDocument(BaseModel): + """Every table a deployment maintains, and the wiring it maintains them through. + + ``defaults`` is merged into each entry of ``tables`` before validation, key + by key: a table naming a key owns it entirely. The merge is deliberately + shallow -- a table with its own ``lifecycle`` replaces the default one + rather than being merged into it, because a half-inherited policy is one + nobody can read off the file. + + ``dsn`` is for whoever connects; the library opens no connection of its own, + and a deployment is free to keep the DSN out of the file entirely. + + ``hooks`` names commands to run around the lifecycle. They are code this + file causes to run in a process holding DDL credentials -- which is not a + new privilege boundary, since the same file already authorises dropping + tables, but it stops being true the moment the document is assembled from + somewhere less trusted than the DSN. Whoever runs the document decides + whether they are honoured; the CLI refuses to apply a document declaring + hooks unless it is told to. + """ + + model_config = ConfigDict(frozen=True, extra="forbid") + + version: Literal[1] = Field(default=1, description="Document format version") + dsn: str | None = Field(default=None, description="Connection string, when the file carries one") + defaults: dict[str, Any] = Field(default_factory=dict, description="Fields every table starts from") + tables: tuple[PartitionTableSpec, ...] = Field(..., min_length=1, description="The tables to maintain") + runtime: ToolkitOptions = Field(default_factory=ToolkitOptions, description="How the collaborators are wired") + hooks: HookOptions | None = Field( + default=None, description="Commands to run around the lifecycle; they fire during apply only" + ) + + @model_validator(mode="before") + @classmethod + def _apply_defaults(cls, data: Any) -> Any: + """Start every table from ``defaults``, and refuse a default no table field takes.""" + if not isinstance(data, dict): + return data + defaults = data.get("defaults") + if not isinstance(defaults, dict) or not defaults: + # Nothing to merge, or a ``defaults`` the field's own validation refuses. + return data + unknown = sorted(set(defaults) - set(PartitionTableSpec.model_fields) - {"schema"}) + if unknown: + msg = f"defaults names fields no table has: {', '.join(unknown)}" + raise ValueError(msg) + tables = data.get("tables") + if not isinstance(tables, (list, tuple)): + return data + # Both sides are normalised before they meet: a default written as + # ``schema`` and a table written as ``schema_name`` are one key, not two + # that survive the merge and read as an unknown field. + shared = _with_schema_name(defaults) + merged = [{**shared, **_with_schema_name(table)} if isinstance(table, dict) else table for table in tables] + return {**data, "tables": merged} + + @model_validator(mode="after") + def _refuse_a_table_described_twice(self) -> PartitionsDocument: + """Two entries for one relation would maintain it under two policies.""" + seen: set[str] = set() + for spec in self.tables: + name = spec.to_config().qualified_name + if name in seen: + msg = f"Table {name!r} is described twice; one relation is maintained under one policy" + raise ValueError(msg) + seen.add(name) + return self + + def configs(self) -> tuple[TablePartitionConfig, ...]: + """Every table as a :class:`~pg_partsmith.TablePartitionConfig`, in document order.""" + return tuple(spec.to_config() for spec in self.tables) + + def config_for(self, qualified_name: str) -> TablePartitionConfig: + """The configuration of one table, by the name PostgreSQL knows it as. + + Raises: + KeyError: If the document describes no such table. + """ + configs = self.configs() + for config in configs: + if config.qualified_name == qualified_name: + return config + known = ", ".join(config.qualified_name for config in configs) + msg = f"{qualified_name!r} is not in this document; it describes {known}" + raise KeyError(msg) + + +def _with_schema_name(mapping: dict[str, Any]) -> dict[str, Any]: + """``schema`` renamed to the field it fills, leaving everything else alone.""" + if "schema" not in mapping: + return mapping + renamed = {key: value for key, value in mapping.items() if key != "schema"} + renamed.setdefault("schema_name", mapping["schema"]) + return renamed diff --git a/pg_partsmith/entities.py b/pg_partsmith/entities.py index d191ba6..9f6654b 100644 --- a/pg_partsmith/entities.py +++ b/pg_partsmith/entities.py @@ -2,6 +2,7 @@ from __future__ import annotations +import hashlib from enum import StrEnum from typing import TYPE_CHECKING, Any @@ -383,6 +384,19 @@ def qualified_name(self) -> str: """``schema.table`` when a schema is set, else the bare table name.""" return qualify(self.schema_name, self.table_name) + @property + def fingerprint(self) -> str: + """Digest of the configuration, identifying what a plan was planned under. + + Taken over the serialized form, so it moves with everything a plan + could have been planned differently for -- the scheme, the policy, the + leaves -- and not with the identity of the object. What serialization + leaves out is invisible to it: two configurations differing only in a + ``Callback``'s function, or in the behaviour of two custom codecs of + the same class name, share a fingerprint. + """ + return hashlib.sha256(self.model_dump_json(by_alias=True).encode()).hexdigest()[:16] + @property def root(self) -> SchemeBase: """The root level of the scheme.""" diff --git a/pg_partsmith/events.py b/pg_partsmith/events.py index 2dbfaff..176c302 100644 --- a/pg_partsmith/events.py +++ b/pg_partsmith/events.py @@ -11,6 +11,7 @@ from __future__ import annotations import inspect +import os from collections.abc import Iterable from enum import StrEnum from typing import TYPE_CHECKING @@ -169,3 +170,32 @@ def validate_hook_signatures(hooks: Iterable[object]) -> None: f"event.table_name, event.window, event.operation.reason." ) raise ValueError(msg) from None + + +def hook_environment(event: PartitionEvent) -> dict[str, str]: + """The process environment a command hook is run with. + + The whole event arrives on stdin; these are the three facts a shell script + reaches for often enough that parsing JSON to get them would be silly. The + parent environment is inherited, because a hook needs its own credentials, + its ``PATH`` and its proxy settings, and stripping those would leave it + unable to do the one thing it exists for. + """ + environment = dict(os.environ) + environment.update( + PG_PARTSMITH_PHASE=event.phase.value, + PG_PARTSMITH_TABLE=event.table_name, + PG_PARTSMITH_PARTITION=event.partition.name, + ) + if event.window is not None: + environment.update( + PG_PARTSMITH_WINDOW_START=_position(event.window.start), + PG_PARTSMITH_WINDOW_END=_position(event.window.end), + ) + return environment + + +def _position(value: object) -> str: + """A window edge as text: ISO 8601 for a moment, the number itself on an integer axis.""" + render = getattr(value, "isoformat", None) + return str(render()) if callable(render) else str(value) diff --git a/pg_partsmith/exceptions.py b/pg_partsmith/exceptions.py index 722572f..bbf49b1 100644 --- a/pg_partsmith/exceptions.py +++ b/pg_partsmith/exceptions.py @@ -151,6 +151,25 @@ def __init__(self, partition_name: str, detail: str) -> None: self.detail = detail +class PlanConfigMismatchError(PartitionError): + """Raised when a plan is applied under a configuration it was not made from. + + In one process the plan and the configuration come from the same two + lines and cannot disagree. Once the plan is an artifact -- written by one + run, read by another, picked out of a document describing several tables + -- they can: the plan for one table applied under another's configuration, + or a plan made before the policy it was planned under was edited. Neither + is caught by the identity revalidation each destructive operation already + does, which answers whether this is still the same relation, not whether + it is still the same intent. + """ + + def __init__(self, table_name: str, detail: str) -> None: + super().__init__(f"Plan for {table_name!r} does not match this configuration: {detail}") + self.table_name = table_name + self.detail = detail + + class UnmanagedPartitionDropError(PartitionError): """Raised when attempting to drop a table not managed by this library.""" diff --git a/pg_partsmith/hook_commands.py b/pg_partsmith/hook_commands.py new file mode 100644 index 0000000..351a47c --- /dev/null +++ b/pg_partsmith/hook_commands.py @@ -0,0 +1,187 @@ +"""Running somebody else's program as a lifecycle hook, once, for both mirrors. + +The command, its payload and everything that can go wrong with it are the same +question in the aio and the sync worlds; only the waiting differs. So the +running lives here, as ordinary blocking calls, and the aio mirror hands the +waiting to a thread. + +That is also what makes it work everywhere. ``asyncio.create_subprocess_exec`` +needs a loop that can spawn processes -- on Windows a selector loop, which is +what an asyncpg or psycopg deployment often installs, raises +``NotImplementedError`` instead -- and a hook that runs on Linux but not on a +developer's machine is a hook nobody trusts. + +The run is split in three -- start, finish, stop -- rather than one call, so +that a run being cancelled can stop the child it started. A hook process that +outlives the maintenance run that fired it is a process nobody is watching. +""" + +from __future__ import annotations + +import contextlib +import subprocess +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Mapping, Sequence + + from .events import HookPhase + +__all__ = ["CommandHookError", "finish_hook_command", "run_hook_command", "start_hook_command", "stop_hook_command"] + +_OUTPUT_TAIL = 2000 +_STOP_GRACE_SECONDS = 5.0 + + +class CommandHookError(RuntimeError): + """A configured command refused the operation, or could not be run. + + Raised so the executor treats it like any other hook failure: the operation + is abandoned and planned again next run, and under ``continue_on_error`` the + rest of the table is still maintained. + """ + + def __init__(self, phase: HookPhase, partition_name: str, detail: str) -> None: + super().__init__(f"{phase.value} hook for {partition_name!r} failed: {detail}") + self.phase = phase + self.partition_name = partition_name + self.detail = detail + + +def start_hook_command( + command: Sequence[str], + *, + phase: HookPhase, + partition_name: str, + environment: Mapping[str, str], +) -> subprocess.Popen[bytes]: + """Start one command with its stdin, stdout and stderr piped. + + Args: + command: The argument vector. Never a shell string, so a partition name + cannot be read as syntax. + phase: Which moment this is, for the error. + partition_name: What the operation is about, for the error. + environment: The process environment. + + Returns: + The running process, for :func:`finish_hook_command`. + + Raises: + CommandHookError: If it cannot be started at all -- not found, not + executable. + """ + try: + return subprocess.Popen( # noqa: S603 - an argument vector, never a shell + list(command), + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + env=dict(environment), + ) + except OSError as exc: + raise CommandHookError(phase, partition_name, f"{command[0]}: {exc}") from exc + + +def finish_hook_command( + process: subprocess.Popen[bytes], + payload: bytes, + *, + phase: HookPhase, + partition_name: str, + timeout_seconds: float, +) -> bytes: + """Hand the payload over, wait for the exit, and answer with stdout. + + Args: + process: What :func:`start_hook_command` returned. + payload: The event, as JSON, for the command's stdin. + phase: Which moment this is, for the error. + partition_name: What the operation is about, for the error. + timeout_seconds: How long it may take. A hook that hangs holds the + table's maintenance lock, so there is no "wait forever". + + Returns: + Whatever the command wrote to stdout. + + Raises: + CommandHookError: If it exits non-zero or outlives the timeout -- each + of which abandons the operation. A child that outlived its timeout, + or that was still running when the wait was interrupted, is stopped + before this returns or raises: nothing it started keeps running + unwatched. + """ + name = process.args[0] if isinstance(process.args, (list, tuple)) else str(process.args) + try: + stdout, stderr = process.communicate(payload, timeout=timeout_seconds) + except subprocess.TimeoutExpired: + stop_hook_command(process) + detail = f"{name} did not finish within {timeout_seconds}s and was killed" + raise CommandHookError(phase, partition_name, detail) from None + except BaseException: + # Ctrl+C in the sync mirror lands here; the child goes with the run. + stop_hook_command(process) + raise + + if process.returncode != 0: + detail = f"{name} exited {process.returncode}: {tail(stderr)}" + raise CommandHookError(phase, partition_name, detail) + return stdout + + +def stop_hook_command(process: subprocess.Popen[bytes], *, grace_seconds: float = _STOP_GRACE_SECONDS) -> None: + """Stop a child the run no longer waits for: ask first, then insist. + + ``terminate`` gives an archiver a moment to close what it was writing; + ``kill`` follows if it does not take it. Idempotent, and never raises: it + runs on the way out of a cancellation, where there is nothing left to do + about a failure but log it. + + Args: + process: The child. + grace_seconds: How long to wait between the two. + """ + if process.poll() is None: + try: + process.terminate() + try: + process.wait(timeout=grace_seconds) + except subprocess.TimeoutExpired: + process.kill() + process.wait() + except OSError: # pragma: no cover - already gone between the poll and the signal + pass + # The pipes are this side's end of the child. Nothing will read a stopped + # child's, and one left open is a ResourceWarning at garbage collection + # inside whatever long-lived process runs the maintenance. + for stream in (process.stdin, process.stdout, process.stderr): + if stream is not None and not stream.closed: + with contextlib.suppress(OSError): + stream.close() + + +def run_hook_command( + command: Sequence[str], + payload: bytes, + *, + phase: HookPhase, + partition_name: str, + environment: Mapping[str, str], + timeout_seconds: float, +) -> bytes: + """Start, feed and finish one command in one blocking call. + + The sync mirror's whole path, and the aio mirror's when nothing cancels it. + See :func:`start_hook_command` and :func:`finish_hook_command` for what can + go wrong at each step. + """ + process = start_hook_command(command, phase=phase, partition_name=partition_name, environment=environment) + return finish_hook_command( + process, payload, phase=phase, partition_name=partition_name, timeout_seconds=timeout_seconds + ) + + +def tail(stream: bytes, limit: int = _OUTPUT_TAIL) -> str: + """The end of a command's output, which is where it says what went wrong.""" + text = stream.decode(errors="replace").strip() + return text if len(text) <= limit else f"…{text[-limit:]}" diff --git a/pg_partsmith/plan.py b/pg_partsmith/plan.py index aed8da4..44be1ff 100644 --- a/pg_partsmith/plan.py +++ b/pg_partsmith/plan.py @@ -16,14 +16,18 @@ from datetime import datetime from enum import StrEnum -from typing import Annotated, Any, Literal +from typing import TYPE_CHECKING, Annotated, Literal -from pydantic import BaseModel, ConfigDict, Field +from pydantic import BaseModel, ConfigDict, Field, computed_field +from .exceptions import PlanConfigMismatchError from .lifecycle import DetachMode from .topology import PartitionBounds, PartitionType from .types import NonNegativeInt, StrippedNonEmptyStr +if TYPE_CHECKING: + from .entities import TablePartitionConfig + __all__ = [ "AttachPartition", "CreatePartition", @@ -38,6 +42,7 @@ "PartitionBy", "Reason", "Severity", + "validate_plan_for_config", ] @@ -289,11 +294,17 @@ def kind(self) -> OperationKind: """The DDL family.""" raise NotImplementedError + # Serialized, not only computed: the lock an operation takes is what an + # operator reads before scheduling a window, and a plan written to a file + # is exactly the plan they read it off. Each subclass overrides the + # property; the dump takes the override. + @computed_field # type: ignore[prop-decorator] @property def capabilities(self) -> OperationCapabilities: """How the operation may be executed.""" raise NotImplementedError + @computed_field # type: ignore[prop-decorator] @property def is_destructive(self) -> bool: """True for operations that remove a partition from service.""" @@ -496,7 +507,13 @@ class MaintenancePlan(BaseModel): generated_at: The instant the plan was made; every policy was evaluated against it. cursors: Cursor of every integer axis the plan was made against, - keyed by leading column. + keyed by leading column. Integers, because only an integer axis + records one -- a time axis is cursored by ``generated_at`` -- so + the plan survives a round trip through JSON unchanged. + config_fingerprint: :attr:`~pg_partsmith.TablePartitionConfig.fingerprint` + of the configuration the plan was made from, so a plan read back + from a file can say whether that configuration still holds. None + on a plan built by hand. operations: What to do, in order. findings: What was deliberately left alone, and why. """ @@ -505,7 +522,8 @@ class MaintenancePlan(BaseModel): table_name: StrippedNonEmptyStr generated_at: datetime - cursors: dict[str, Any] = Field(default_factory=dict) + cursors: dict[str, int] = Field(default_factory=dict) + config_fingerprint: str | None = None operations: tuple[Operation, ...] = () findings: tuple[Finding, ...] = () @@ -578,6 +596,49 @@ def describe(self) -> str: return "\n".join(lines) +def validate_plan_for_config( + config: TablePartitionConfig, + plan: MaintenancePlan, + *, + allow_config_drift: bool = False, +) -> None: + """Refuse a plan that was not made from ``config``. + + Two questions the identity revalidation on each destructive operation does + not answer: whether this is the plan for this table, and whether it was + planned under the policy in force now. Both become reachable the moment a + plan is written to a file and applied by a later process -- against the + wrong table of a document describing several, or after the retention it + was planned under was edited. The plan would still be applied to exactly + the relations it named, for reasons that had stopped being true. + + A plan carrying no fingerprint -- built by hand, or by a version that did + not record one -- is checked for its table alone; there is nothing to + compare it against, and inventing a refusal from that would be guessing. + + Args: + config: The configuration the plan is about to be applied with. + plan: The plan. + allow_config_drift: Apply a plan whose fingerprint no longer matches + the configuration. + + Raises: + PlanConfigMismatchError: If the plan is for another table, or was made + under another configuration and ``allow_config_drift`` is not set. + """ + if plan.table_name != config.qualified_name: + raise PlanConfigMismatchError(plan.table_name, f"the configuration describes {config.qualified_name!r}") + if allow_config_drift or plan.config_fingerprint is None: + return + current = config.fingerprint + if plan.config_fingerprint != current: + msg = ( + f"the configuration changed after the plan was made ({plan.config_fingerprint} -> {current}); " + "plan again, or pass allow_config_drift=True to apply it as it stands" + ) + raise PlanConfigMismatchError(plan.table_name, msg) + + def _describe_operation(op: Operation, indent: int) -> list[str]: prefix = " " * indent line = f"{prefix}{op.describe()}" diff --git a/pg_partsmith/planner.py b/pg_partsmith/planner.py index c40644f..7ec8139 100644 --- a/pg_partsmith/planner.py +++ b/pg_partsmith/planner.py @@ -98,7 +98,7 @@ class PlanningContext(BaseModel): model_config = ConfigDict(frozen=True, arbitrary_types_allowed=True) now: datetime - cursors: dict[str, Any] = Field(default_factory=dict) + cursors: dict[str, int] = Field(default_factory=dict) mode: PlanMode = PlanMode.MAINTAIN explicit_windows: dict[str, tuple[Window, ...]] = Field(default_factory=dict) @@ -121,6 +121,7 @@ def plan_maintenance(config: TablePartitionConfig, actual: ActualTree, context: table_name=config.qualified_name, generated_at=context.now, cursors=dict(context.cursors), + config_fingerprint=config.fingerprint, operations=tuple(planner.creates + planner.attaches + planner.detaches + planner.drops), findings=tuple(planner.findings), ) diff --git a/pg_partsmith/python_hooks.py b/pg_partsmith/python_hooks.py new file mode 100644 index 0000000..9cff8c7 --- /dev/null +++ b/pg_partsmith/python_hooks.py @@ -0,0 +1,95 @@ +"""Lifecycle hooks written as Python in a configuration file, once, for both mirrors. + +The authentik model: a block of Python in the document, evaluated with a +prepared namespace when the moment comes. Expressive, no build step, and the +natural fit for the Python-adjacent audience -- a team that would rather write +five lines than ship a binary. + +Two things this module is careful about, and one it deliberately is not. + +It compiles every block when the document is read, not when the hook fires: a +``SyntaxError`` discovered at 03:00 by a CronJob, after some of the run's DDL +has committed, is the failure mode to design out. And it names each block +after its phase, so a traceback says ``before_drop`` and a line number rather +than ````. + +What it does not do is sandbox anything. ``exec`` with a filtered +``__builtins__`` is not a security boundary and is trivially escaped; claiming +one would be worse than having none. The block runs as the process runs, with +every credential the process holds, and the documentation says so. Isolation, +if wanted, is a command hook in a container of its own. +""" + +from __future__ import annotations + +import logging +from types import CodeType +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from .events import HookPhase, PartitionEvent + +__all__ = ["PythonHookError", "compile_hook_source", "run_hook_source"] + + +class PythonHookError(RuntimeError): + """A block refused the operation by raising, or could not be run. + + Raised so the executor treats it like any other hook failure: the operation + is abandoned and planned again next run, and under ``continue_on_error`` the + rest of the table is still maintained. The block's own exception is the + cause, so its traceback is not lost. + """ + + def __init__(self, phase: HookPhase, partition_name: str, detail: str) -> None: + super().__init__(f"{phase.value} hook for {partition_name!r} failed: {detail}") + self.phase = phase + self.partition_name = partition_name + self.detail = detail + + +def compile_hook_source(source: str, *, name: str) -> CodeType: + """Compile one block, so a mistake in it is found now and not at 03:00. + + Args: + source: The block, as the document gives it. + name: What tracebacks call it -- the phase, or the file it came from. + + Returns: + The code, ready for :func:`run_hook_source`. + + Raises: + SyntaxError: If the block does not parse. Left as it is rather than + wrapped, because its line and column are the whole message. + """ + return compile(source, name, "exec", dont_inherit=True) + + +def run_hook_source(code: CodeType, event: PartitionEvent, *, logger: logging.Logger) -> None: + """Run one compiled block with the namespace the documentation promises. + + The namespace is ``event`` -- the :class:`~pg_partsmith.events.PartitionEvent`, + exactly what a Python hook class is handed -- and ``log``, a logger named + for the phase. Nothing else is injected: a block that needs ``datetime`` + imports it, the way any Python does. + + Args: + code: What :func:`compile_hook_source` returned. + event: The event the hook is fired with. + logger: Where ``log`` writes. + + Raises: + PythonHookError: If the block raises. Raising is how a block refuses + the operation, so the error names the phase and the partition and + keeps the block's own exception as its cause. + """ + namespace: dict[str, Any] = { + "__name__": f"pg_partsmith.hook.{event.phase.value}", + "event": event, + "log": logger, + } + try: + exec(code, namespace) # noqa: S102 - the document is trusted code, and the docs say exactly that + except Exception as exc: + detail = f"{type(exc).__name__}: {exc}" if str(exc) else type(exc).__name__ + raise PythonHookError(event.phase, event.partition.name, detail) from exc diff --git a/pg_partsmith/settings.py b/pg_partsmith/settings.py index c42b1fa..2c1c6f1 100644 --- a/pg_partsmith/settings.py +++ b/pg_partsmith/settings.py @@ -18,11 +18,8 @@ class OutboxSettings(PartitionTableSettings): from __future__ import annotations -from datetime import UTC, tzinfo -from typing import Any - try: - from pydantic_settings import BaseSettings + from pydantic_settings import BaseSettings, SettingsConfigDict except ImportError as _err: _msg = ( "pydantic-settings is required for PartitionTableSettings. " @@ -30,18 +27,17 @@ class OutboxSettings(PartitionTableSettings): ) raise ImportError(_msg) from _err -from pydantic import Field - -from .constants import DEFAULT_CREATE_AHEAD_COUNT, DEFAULT_RETENTION_COUNT -from .entities import PartitionGranularity, PartitionStrategy, PartitionType, TablePartitionConfig -from .strategies import BasePeriodCalculator, get_period_calculator +from .document import PartitionTableSpec -class PartitionTableSettings(BaseSettings): - """Env-loadable base class that maps onto :class:`~pg_partsmith.TablePartitionConfig`. +class PartitionTableSettings(PartitionTableSpec, BaseSettings): + """One table's fields, read from the environment. - Subclass it, set ``model_config`` with your env prefix, then call - :meth:`to_config` to get a ready-to-use ``TablePartitionConfig``. + The same fields as :class:`~pg_partsmith.document.PartitionTableSpec` — the + entry a configuration file gives per table — with an environment as their + source instead of a document. Subclass it, set ``model_config`` with your + env prefix, then call :meth:`~pg_partsmith.document.PartitionTableSpec.to_config` + to get a ready-to-use ``TablePartitionConfig``. The flat fields describe the ordinary time-partitioned table; any other topology is given as ``scheme`` (JSON), which takes precedence over them; @@ -60,103 +56,9 @@ class OutboxSettings(PartitionTableSettings): config = settings.to_config() """ - schema_name: str | None = Field(default=None, description="PostgreSQL schema (omit for public)") - table_name: str = Field(..., description="Partitioned table name") - partition_type: PartitionType | None = Field( - default=None, description="Checked against the scheme: range, list, hash" - ) - partition_strategy: PartitionStrategy | None = Field( - default=None, - description="Checked against the scheme: time_based, numeric_based, value_based, hash_based", - ) - partition_column: str | None = Field(default=None, description="Leading column of a time-partitioned root") - trailing_partition_columns: tuple[str, ...] = Field( - default=(), - description='Rest of a composite partition key, as JSON: ["tenant_id"]', - ) - granularity: PartitionGranularity | None = Field( - default=None, - description="Time granularity: hour, day, week, month, quarter, year", - ) - tz: str = Field(default="UTC", description="IANA timezone the calendar is computed in") - boundary_codec: str | None = Field( - default=None, - description="Physical key encoding by name: uuidv7, epoch_seconds, epoch_milliseconds", - ) - create_ahead_count: int = Field( - default=DEFAULT_CREATE_AHEAD_COUNT, - ge=1, - description="Number of periods to ensure exist, including the current period", - ) - retention_count: int = Field( - default=DEFAULT_RETENTION_COUNT, - ge=1, - description="Number of newest periods to keep, current one included", - ) - scheme: dict[str, Any] | None = Field( - default=None, - description=( - "Any topology, as JSON: " - '{"method": "range", "key": "created_at", "boundaries": {"kind": "time", "granularity": "week"}, ' - '"child": {"method": "hash", "key": "tenant_id", "modulus": 4}}' - ), - ) - lifecycle: dict[str, Any] | None = Field( - default=None, - description='Lifecycle policy, as JSON: {"creation": {"kind": "create_ahead", "count": 3}, ...}', - ) - leaves: dict[str, Any] | None = Field( - default=None, - description=( - "Leaf backend, as JSON: " - '{"kind": "local", "tablespace": "fast", "storage_parameters": {"fillfactor": 70}} or ' - '{"kind": "foreign", "server": "archive", "options": {"table_name": "{relname}"}}' - ), - ) - - def to_config(self) -> TablePartitionConfig: - """Build a :class:`~pg_partsmith.TablePartitionConfig` from these settings.""" - fields: dict[str, Any] = {"schema": self.schema_name, "table_name": self.table_name} - if self.partition_type is not None: - fields["partition_type"] = self.partition_type - if self.partition_strategy is not None: - fields["partition_strategy"] = self.partition_strategy - - if self.scheme is not None: - fields["scheme"] = self.scheme - else: - fields.update( - partition_column=self.partition_column, - trailing_partition_columns=self.trailing_partition_columns, - granularity=self.granularity, - tz=self.tz, - boundary_codec=self.boundary_codec, - ) - - if self.lifecycle is not None: - fields["lifecycle"] = self.lifecycle - else: - fields.update(create_ahead_count=self.create_ahead_count, retention_count=self.retention_count) - if self.leaves is not None: - fields["leaves"] = self.leaves - - return TablePartitionConfig(**fields) - - def get_period_calculator(self, tz: tzinfo = UTC) -> BasePeriodCalculator: - """Return the period calculator matching :attr:`granularity`. - - Args: - tz: Timezone the calculator works in (``datetime.UTC`` or a keyed - :class:`zoneinfo.ZoneInfo`). HOUR accepts only UTC. - - Raises: - ValueError: If ``granularity`` is ``None`` or has no registered - calculator, or ``tz`` is unsupported for it. - """ - if self.granularity is None: - msg = "Cannot resolve a period calculator: granularity is not set" - raise ValueError(msg) - return get_period_calculator(self.granularity, tz=tz) + # Restated so the two bases agree on one config type; the values are the + # spec's, and a subclass adding ``env_prefix`` still merges into them. + model_config = SettingsConfigDict(extra="forbid", populate_by_name=True) __all__ = ["PartitionTableSettings"] diff --git a/pg_partsmith/sync/__init__.py b/pg_partsmith/sync/__init__.py index 91d7de1..08cc875 100644 --- a/pg_partsmith/sync/__init__.py +++ b/pg_partsmith/sync/__init__.py @@ -1,5 +1,6 @@ """Sync implementations for partition management.""" +from .command_hooks import CommandHookError, CommandHooks from .hooks import BasePartitionLifecycleHooks, PartitionLifecycleHooks from .lock import PostgresAdvisoryLockManager, RedisDistributedLockManager from .maintainer import PartitionMaintainer, maintain_partitions @@ -10,12 +11,16 @@ PartitionMetadataProvider, PartitionRepository, ) +from .python_hooks import PythonHookError, PythonHooks from .repositories import PostgresPartitionRepository from .service import PartitionLifecycleService from .services import PartitionInspector, PartitionValidationService, PlanExecutor +from .toolkit import PartitionToolkit __all__ = [ "BasePartitionLifecycleHooks", + "CommandHookError", + "CommandHooks", "LockManager", "PartitionInspector", "PartitionLifecycle", @@ -24,11 +29,14 @@ "PartitionMaintainer", "PartitionMetadataProvider", "PartitionRepository", + "PartitionToolkit", "PartitionValidationService", "PlanExecutor", "PostgresAdvisoryLockManager", "PostgresMetadataProvider", "PostgresPartitionRepository", + "PythonHookError", + "PythonHooks", "RedisDistributedLockManager", "maintain_partitions", ] diff --git a/pg_partsmith/sync/command_hooks.py b/pg_partsmith/sync/command_hooks.py new file mode 100644 index 0000000..cca2974 --- /dev/null +++ b/pg_partsmith/sync/command_hooks.py @@ -0,0 +1,114 @@ +"""Lifecycle hooks that run a command, for the stacks this library is not written in. + +A Go or Ruby team already owns an archiver; what they need is for it to be +invoked at the right moment with the right metadata. That is all this is: one +hook object that runs a configured command per phase, hands it the +:class:`~pg_partsmith.events.PartitionEvent` as JSON on stdin, and treats a +non-zero exit exactly as a raised exception -- the operation is aborted and +left for the next run. + +Nothing here needs a new context: the event is already a pydantic model, so the +payload the command reads is the same object a Python hook is handed, dumped +with ``by_alias=True``. + +Usage:: + + hooks = CommandHooks({HookPhase.BEFORE_DROP: ["/usr/local/bin/archive"]}) + service = PartitionLifecycleService(repo=repo, metadata=metadata, locks=locks, hooks=[hooks]) + +The command's stdout is logged. Its stderr is carried in the error when it +fails, which is the only place an operator will look at 03:00. +""" + +from __future__ import annotations + +import logging +from typing import TYPE_CHECKING + +from pg_partsmith.constants import DEFAULT_HOOK_TIMEOUT_SECONDS +from pg_partsmith.events import HookPhase, hook_environment +from pg_partsmith.hook_commands import CommandHookError, run_hook_command, tail + +from .hooks import BasePartitionLifecycleHooks + +if TYPE_CHECKING: + from collections.abc import Mapping, Sequence + + from pg_partsmith.events import PartitionEvent + +logger = logging.getLogger(__name__) + +__all__ = ["CommandHookError", "CommandHooks"] + + +class CommandHooks(BasePartitionLifecycleHooks): + """Runs one configured command per phase, with the event as JSON on stdin. + + Overrides :meth:`on_event` alone rather than one method per phase: the + phase is in the event, and a dispatch table reads better than eight + delegating methods that would each have to be added to again. The + per-phase methods come from the no-op base, which the executor calls after + this one. + """ + + def __init__( + self, + commands: Mapping[HookPhase, Sequence[str]], + *, + timeout_seconds: float = DEFAULT_HOOK_TIMEOUT_SECONDS, + ) -> None: + """Wire the commands. + + Args: + commands: The command to run at each phase, as an argument vector. + A vector rather than a string: nothing is passed through a + shell, so a partition name can never be read as syntax. + timeout_seconds: How long a command may take before it is killed and + the operation abandoned. A hook that hangs holds the table's + maintenance lock, so there is no "wait forever" option. + + Raises: + ValueError: If a command is empty, or its phase is not a hook phase. + """ + for phase, command in commands.items(): + if phase not in set(HookPhase): + msg = f"{phase!r} is not a hook phase; expected one of: {', '.join(p.value for p in HookPhase)}" + raise ValueError(msg) + if not command or not all(isinstance(part, str) for part in command): + msg = f"The {phase.value} command must be a non-empty list of strings" + raise ValueError(msg) + self._commands = {phase: tuple(command) for phase, command in commands.items()} + self._timeout = timeout_seconds + + @property + def phases(self) -> tuple[HookPhase, ...]: + """The phases a command is configured for, in declaration order.""" + return tuple(self._commands) + + def on_event(self, event: PartitionEvent) -> None: + """Run the command configured for this event's phase, if there is one. + + Raises: + CommandHookError: If the command exits non-zero, cannot be run, or + outlives its timeout. A ``before_*`` hook failing this way + abandons the operation; an ``after_*`` one abandons what is left + of it, and the next run plans it again. + """ + command = self._commands.get(event.phase) + if command is None: + return + stdout = run_hook_command( + command, + event.model_dump_json(by_alias=True).encode(), + phase=event.phase, + partition_name=event.partition.name, + environment=hook_environment(event), + timeout_seconds=self._timeout, + ) + if stdout: + logger.info( + "%s hook said: %s", + event.phase.value, + tail(stdout), + extra={"partition_name": event.partition.name, "table_name": event.table_name}, + ) diff --git a/pg_partsmith/sync/python_hooks.py b/pg_partsmith/sync/python_hooks.py new file mode 100644 index 0000000..ae56e5b --- /dev/null +++ b/pg_partsmith/sync/python_hooks.py @@ -0,0 +1,86 @@ +"""Lifecycle hooks written as Python blocks in a configuration file. + +One hook object holds one compiled block per phase and runs it with ``event`` +and ``log`` in scope when that phase fires. Every block is compiled when the +object is built, so a document with a typo in it is refused before any DDL +runs rather than after some of it has. + +Usage:: + + hooks = PythonHooks({HookPhase.BEFORE_DROP: "log.warning('dropping %s', event.partition.name)"}) + service = PartitionLifecycleService(repo=repo, metadata=metadata, locks=locks, hooks=[hooks]) + +The block runs inline, in the process that fires it. That is the same footing +as any hook written as a class, and the same responsibility: a block that +blocks, blocks maintenance. +""" + +from __future__ import annotations + +import logging +from typing import TYPE_CHECKING + +from pg_partsmith.events import HookPhase +from pg_partsmith.python_hooks import PythonHookError, compile_hook_source, run_hook_source + +from .hooks import BasePartitionLifecycleHooks + +if TYPE_CHECKING: + from collections.abc import Mapping + from types import CodeType + + from pg_partsmith.events import PartitionEvent + +__all__ = ["PythonHookError", "PythonHooks"] + + +class PythonHooks(BasePartitionLifecycleHooks): + """Runs one configured block of Python per phase. + + Overrides :meth:`on_event` alone; the phase is in the event, and the + per-phase methods come from the no-op base, which the executor calls after + this one. + """ + + def __init__(self, sources: Mapping[HookPhase, str], *, names: Mapping[HookPhase, str] | None = None) -> None: + """Compile every block now. + + Args: + sources: The block to run at each phase. + names: What tracebacks call each block -- the file it came from, + when it came from one. The phase by default. + + Raises: + SyntaxError: If a block does not parse. Its line and column are + the message, so it is not wrapped. + ValueError: If a phase is not a hook phase, or a block is empty. + """ + compiled: dict[HookPhase, CodeType] = {} + for phase, source in sources.items(): + if phase not in set(HookPhase): + msg = f"{phase!r} is not a hook phase; expected one of: {', '.join(p.value for p in HookPhase)}" + raise ValueError(msg) + if not source or not source.strip(): + msg = f"The {phase.value} block is empty" + raise ValueError(msg) + name = (names or {}).get(phase, f"") + compiled[phase] = compile_hook_source(source, name=name) + self._code = compiled + self._loggers = {phase: logging.getLogger(f"pg_partsmith.hook.{phase.value}") for phase in compiled} + + @property + def phases(self) -> tuple[HookPhase, ...]: + """The phases a block is configured for, in declaration order.""" + return tuple(self._code) + + def on_event(self, event: PartitionEvent) -> None: + """Run the block configured for this event's phase, if there is one. + + Raises: + PythonHookError: If the block raises, which is how it refuses the + operation. + """ + code = self._code.get(event.phase) + if code is None: + return + run_hook_source(code, event, logger=self._loggers[event.phase]) diff --git a/pg_partsmith/sync/service.py b/pg_partsmith/sync/service.py index f1a532d..eaf54f2 100644 --- a/pg_partsmith/sync/service.py +++ b/pg_partsmith/sync/service.py @@ -135,23 +135,32 @@ def apply( plan: MaintenancePlan, *, continue_on_error: bool = False, + allow_config_drift: bool = False, ) -> MaintenanceResult: """Execute a plan under the table's lock. Every destructive operation is revalidated against the catalog first: - a relation that no longer has the OID the plan saw is left alone. + a relation that no longer has the OID the plan saw is left alone, and + a plan made for another table, or under a configuration that has since + been edited, is refused before anything is executed. Args: config: The configuration the plan was made from. plan: The plan, possibly filtered. continue_on_error: Isolate operation failures into ``MaintenanceResult.issues`` instead of aborting. + allow_config_drift: Apply a plan whose fingerprint no longer + matches ``config`` -- it was planned under a policy that has + since changed, and its operations still carry the old reasons. Raises: LockAcquisitionError: If the table-level maintenance lock is unavailable. + PlanConfigMismatchError: If the plan was not made from ``config``. """ with self._locks.acquire_lock(config.qualified_name): - return self._executor.apply(config, plan, continue_on_error=continue_on_error) + return self._executor.apply( + config, plan, continue_on_error=continue_on_error, allow_config_drift=allow_config_drift + ) def maintain( self, diff --git a/pg_partsmith/sync/services/execution.py b/pg_partsmith/sync/services/execution.py index 40a2657..2b6d0d2 100644 --- a/pg_partsmith/sync/services/execution.py +++ b/pg_partsmith/sync/services/execution.py @@ -44,6 +44,7 @@ FindingReason, MaintenancePlan, Operation, + validate_plan_for_config, ) from pg_partsmith.planner import PlanMode, PlanningContext, plan_maintenance, to_maintenance_issue from pg_partsmith.scheme import ListPartitioning, RangePartitioning @@ -88,6 +89,7 @@ def apply( plan: MaintenancePlan, *, continue_on_error: bool = False, + allow_config_drift: bool = False, ) -> MaintenanceResult: """Execute every operation of ``plan`` in order. @@ -104,10 +106,16 @@ def apply( plan: The plan. continue_on_error: Isolate operation failures into ``MaintenanceResult.issues`` instead of aborting. + allow_config_drift: Execute a plan whose fingerprint no longer + matches ``config``. Returns: The counters, the issues, and the plan itself. + + Raises: + PlanConfigMismatchError: If the plan was not made from ``config``. """ + validate_plan_for_config(config, plan, allow_config_drift=allow_config_drift) tally = _Tally() issues: list[MaintenanceIssue] = [to_maintenance_issue(f) for f in plan.actionable_findings] detached: set[str] = set() diff --git a/pg_partsmith/sync/services/inspection.py b/pg_partsmith/sync/services/inspection.py index cc038ac..1cb5a58 100644 --- a/pg_partsmith/sync/services/inspection.py +++ b/pg_partsmith/sync/services/inspection.py @@ -3,7 +3,7 @@ from __future__ import annotations from datetime import UTC, datetime -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING from pg_partsmith.boundaries import Axis, CursorSource, Window from pg_partsmith.planner import PlanMode, PlanningContext, fact_targets @@ -67,7 +67,7 @@ def context( if instant.tzinfo is None: instant = instant.replace(tzinfo=UTC) - cursors: dict[str, Any] = {} + cursors: dict[str, int] = {} for level in config.levels: boundaries = level.progression if boundaries is None or boundaries.axis is not Axis.INTEGER: diff --git a/pg_partsmith/sync/toolkit.py b/pg_partsmith/sync/toolkit.py new file mode 100644 index 0000000..6cc93d9 --- /dev/null +++ b/pg_partsmith/sync/toolkit.py @@ -0,0 +1,182 @@ +"""One set of collaborators for a table's maintenance, wired so they agree. + +Three settings live on two objects and have to match. ``marker_prefix`` +stamps a detached partition and decides what counts as ours when dropping, +so a prefix given to the repository alone leaves the metadata provider +unable to see the orphans it made -- they are never dropped. +``ddl_timezone`` writes naive boundary literals and reads them back in +:meth:`is_partition_closed`, and the two objects do not even default to the +same value. ``boundary_codec`` must be the one the bounds were encoded with. + +:meth:`PartitionToolkit.from_engine` takes each of those once and hands them +to everything that needs them, and returns the parts by name rather than +just a maintainer -- code that calls ``metadata.is_partition_closed`` or +``locks.acquire_lock`` directly should not have to build a second set and +keep it consistent by hand. + +Usage:: + + kit = PartitionToolkit.from_engine(engine, hooks=[ExportHooks()]) + plan = kit.service.plan(config) + result = kit.maintainer.run_maintenance_safe(config) +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from pg_partsmith.constants import ( + DEFAULT_DDL_TIMEOUT_SECONDS, + DEFAULT_DDL_TIMEZONE, + DEFAULT_DROP_LOCK_TIMEOUT_MS, + DEFAULT_DROP_MAX_BACKOFF, + DEFAULT_DROP_MAX_RETRIES, + DEFAULT_DROP_RETRY_DELAY, + DEFAULT_LOCK_PREFIX, +) +from pg_partsmith.document import ToolkitOptions + +from .lock import PostgresAdvisoryLockManager +from .maintainer import PartitionMaintainer +from .metadata import PostgresMetadataProvider +from .repositories import PostgresPartitionRepository +from .service import PartitionLifecycleService + +if TYPE_CHECKING: + from sqlalchemy import Engine + + from pg_partsmith.boundaries import RangeBoundaryCodec + + from .hooks import PartitionLifecycleHooks + from .protocols import LockManager, PartitionMetadataProvider, PartitionRepository + + +@dataclass(frozen=True, slots=True) +class PartitionToolkit: + """The repository, provider, locks, service and maintainer of one wiring. + + Build it with :meth:`from_engine`, or construct it directly around parts + of your own -- a repository against another database, a Redis lock + manager -- when the defaults do not fit. + + Attributes: + repo: DDL operations on partitions. + metadata: Read-only catalog access. + locks: The lock one maintenance run at a time is taken under. + service: The three verbs: plan, apply, maintain. + maintainer: The service with timing, logging and error handling, which + is what a scheduled tick calls. + """ + + repo: PartitionRepository + metadata: PartitionMetadataProvider + locks: LockManager + service: PartitionLifecycleService + maintainer: PartitionMaintainer + + @classmethod + def from_engine( + cls, + engine: Engine, + *, + hooks: list[PartitionLifecycleHooks] | None = None, + locks: LockManager | None = None, + marker_prefix: str | None = None, + ddl_timezone: str | None = DEFAULT_DDL_TIMEZONE, + ddl_timeout_seconds: float = DEFAULT_DDL_TIMEOUT_SECONDS, + boundary_codec: RangeBoundaryCodec | None = None, + lock_prefix: str = DEFAULT_LOCK_PREFIX, + lock_min_interval_seconds: float = 0.0, + drop_allow_unmanaged: bool = False, + drop_lock_timeout_ms: int = DEFAULT_DROP_LOCK_TIMEOUT_MS, + drop_max_retries: int = DEFAULT_DROP_MAX_RETRIES, + drop_retry_delay: float = DEFAULT_DROP_RETRY_DELAY, + drop_max_backoff: float = DEFAULT_DROP_MAX_BACKOFF, + ) -> PartitionToolkit: + """Wire every part around one engine, with the shared settings given once. + + Args: + engine: The engine every part works through. + hooks: Lifecycle hooks, handed to the service. + locks: A lock manager of your own -- Redis, or an advisory manager + with a different ID derivation. A PostgreSQL advisory manager + on ``engine`` by default. + marker_prefix: Orphan marker prefix, given to the repository that + writes it and the provider that looks for it. + ddl_timezone: Session timezone naive boundary literals are written + and read in, given to both for the same reason. + ddl_timeout_seconds: Statement timeout for DDL. + boundary_codec: Codec ``is_partition_closed`` reads encoded bounds + with; only needed when the key is an encoded identifier. + lock_prefix: Prefix of the default advisory lock manager's keys. + lock_min_interval_seconds: Minimum seconds between acquire attempts + per table; 0 disables the rate limit. + drop_allow_unmanaged: Let the repository drop a relation carrying no + ownership marker. + drop_lock_timeout_ms: ``lock_timeout`` a drop attempt runs under. + drop_max_retries: Attempts a drop makes before giving up. + drop_retry_delay: Delay before the second attempt; it backs off. + drop_max_backoff: Ceiling on that backoff. + + Returns: + The parts, wired consistently. + """ + repo = PostgresPartitionRepository( + engine, + ddl_timezone=ddl_timezone, + ddl_timeout_seconds=ddl_timeout_seconds, + marker_prefix=marker_prefix, + drop_allow_unmanaged=drop_allow_unmanaged, + drop_lock_timeout_ms=drop_lock_timeout_ms, + drop_max_retries=drop_max_retries, + drop_retry_delay=drop_retry_delay, + drop_max_backoff=drop_max_backoff, + ) + metadata = PostgresMetadataProvider( + engine, + marker_prefix=marker_prefix, + boundary_codec=boundary_codec, + ddl_timezone=ddl_timezone, + ) + lock_manager = ( + locks + if locks is not None + else PostgresAdvisoryLockManager( + engine, prefix=lock_prefix, acquire_min_interval_seconds=lock_min_interval_seconds + ) + ) + service = PartitionLifecycleService(repo=repo, metadata=metadata, locks=lock_manager, hooks=hooks) + return cls( + repo=repo, + metadata=metadata, + locks=lock_manager, + service=service, + maintainer=PartitionMaintainer(service), + ) + + @classmethod + def from_options( + cls, + engine: Engine, + options: ToolkitOptions, + *, + hooks: list[PartitionLifecycleHooks] | None = None, + locks: LockManager | None = None, + ) -> PartitionToolkit: + """Wire every part from the ``runtime`` section of a document. + + Args: + engine: The engine every part works through. + options: The wiring, as a file writes it -- one field per keyword + of :meth:`from_engine`, with ``boundary_codec`` as a name. + hooks: Lifecycle hooks, handed to the service. + locks: A lock manager of your own, as in :meth:`from_engine`. + + Returns: + The parts, wired consistently. + + Raises: + ValueError: If ``options.boundary_codec`` names no known codec. + """ + return cls.from_engine(engine, hooks=hooks, locks=locks, **options.to_kwargs()) diff --git a/pyproject.toml b/pyproject.toml index 81fb4d4..ae7a566 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -16,12 +16,13 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", "Topic :: Database", "Topic :: Software Development :: Libraries :: Python Modules", "Typing :: Typed", ] dependencies = [ - "pydantic>=2.0.0,<3.0.0", + "pydantic>=2.6.0,<3.0.0", "python-dateutil>=2.7.0,<3.0.0", "sqlalchemy[asyncio]>=2.0.0,<3.0.0", ] @@ -32,9 +33,13 @@ Documentation = "https://bedrock-python.github.io/pg-partsmith/" Changelog = "https://github.com/bedrock-python/pg-partsmith/blob/master/CHANGELOG.md" "Bug Tracker" = "https://github.com/bedrock-python/pg-partsmith/issues" +[project.scripts] +pg-partsmith = "pg_partsmith.console:main" + [project.optional-dependencies] redis-locks = ["redis>=4.2.0"] pydantic-settings = ["pydantic-settings>=2.0.0,<3.0.0"] +cli = ["pyyaml>=6.0,<7.0", "asyncpg>=0.29.0", "typer>=0.17,<1.0"] [dependency-groups] test = [ @@ -47,6 +52,10 @@ test = [ "tzdata>=2024.1", "psycopg2-binary>=2.9.11", "types-python-dateutil~=2.9.0", + "pyyaml>=6.0,<7.0", + "types-pyyaml>=6.0", + "pydantic-settings>=2.0.0,<3.0.0", + "typer>=0.17,<1.0", ] docs = [ "zensical>=0.0.37", @@ -63,6 +72,11 @@ dev = [ [tool.uv] link-mode = "copy" +[tool.check-wheel-contents] +# W002, duplicate files: the sync package mirrors the aio one file for file, +# and a package marker that says nothing is the same bytes in both. +ignore = ["W002"] + [tool.hatch.version] path = "pg_partsmith/__version__.py" @@ -96,6 +110,7 @@ warn_unreachable = true [tool.ruff] line-length = 120 target-version = "py311" +extend-exclude = ["examples"] [tool.ruff.lint] select = ["F", "E", "W", "I", "B", "N", "S", "C4", "DTZ", "SIM", "TRY", "PERF", "RUF", "UP", "ANN", "T20", "PTH", "PLC", "PLE", "PLW"] @@ -121,6 +136,14 @@ addopts = [ markers = [ "unit: mark a test as a unit test.", "integration: mark a test as an integration test.", + "e2e: mark a test as an end-to-end test of the container image; needs PG_PARTSMITH_E2E_IMAGE.", +] +# A warning is a deprecation notice with a date on it; the suite fails on the +# day it appears rather than on the day the removal ships. The one ignored is +# testcontainers deprecating a decorator it still uses itself. +filterwarnings = [ + "error", + "ignore:The @wait_container_is_ready decorator is deprecated:DeprecationWarning", ] [tool.coverage.run] diff --git a/scripts/k8s_manifests.py b/scripts/k8s_manifests.py new file mode 100644 index 0000000..e681961 --- /dev/null +++ b/scripts/k8s_manifests.py @@ -0,0 +1,48 @@ +"""Copy the Kubernetes manifests out of a guide, one file per fenced block, for kubeconform. + +Usage: python scripts/k8s_manifests.py docs/guide/running.md manifests/ + +A fenced ``yaml`` block is a manifest when its first document carries an +``apiVersion`` and a ``kind``; the guide's fragments -- a container spec to +paste, a lone ``args`` line -- have neither and are left where they are. Blocks +are written verbatim, several documents and comments included, so a line +number kubeconform reports is a line in the guide's block. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +import yaml + +FENCE = re.compile(r"^```yaml\n(.*?)^```\n", re.MULTILINE | re.DOTALL) + + +def manifests(markdown: str) -> list[str]: + """The fenced YAML blocks of ``markdown`` whose first document is a Kubernetes object.""" + found: list[str] = [] + for block in FENCE.findall(markdown): + first = next(iter(yaml.safe_load_all(block)), None) + if isinstance(first, dict) and "apiVersion" in first and "kind" in first: + found.append(block) + return found + + +def main(argv: list[str]) -> int: + if len(argv) != 3: + sys.stderr.write(__doc__ or "") + return 64 + guide, target = Path(argv[1]), Path(argv[2]) + target.mkdir(parents=True, exist_ok=True) + blocks = manifests(guide.read_text(encoding="utf-8")) + for index, block in enumerate(blocks, start=1): + kinds = "-".join(str(doc["kind"]).lower() for doc in yaml.safe_load_all(block) if isinstance(doc, dict)) + (target / f"{index:02d}-{kinds}.yaml").write_text(block, encoding="utf-8") + sys.stdout.write(f"{len(blocks)} manifest blocks from {guide} in {target}\n") + return 0 if blocks else 1 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv)) diff --git a/scripts/sync_mirror.py b/scripts/sync_mirror.py index eeb77aa..c42f261 100644 --- a/scripts/sync_mirror.py +++ b/scripts/sync_mirror.py @@ -8,7 +8,8 @@ uv run python scripts/sync_mirror.py uv run ruff check --fix pg_partsmith/sync && uv run ruff format pg_partsmith/sync -Hand-maintained (not mirrored): ``lock/``, ``maintainer.py`` and +Hand-maintained (not mirrored): ``lock/``, ``maintainer.py``, +``command_hooks.py``, ``python_hooks.py`` and ``repositories/{resolver,fk_manager,timeouts,pin}.py``. """ @@ -36,6 +37,7 @@ "repositories/creator.py", "repositories/remover.py", "repositories/repository.py", + "toolkit.py", ] RULES: list[tuple[str, str]] = [ diff --git a/tests/conftest.py b/tests/conftest.py index 4fb86ce..a7c733e 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -3,13 +3,17 @@ from __future__ import annotations import asyncio +import contextlib import os import sys # required for platform check below +import warnings from collections.abc import AsyncGenerator, Generator from pathlib import Path +from urllib.parse import unquote, urlparse from uuid import uuid4 import docker +import freezegun import pytest import pytest_asyncio from sqlalchemy import Engine, create_engine, text @@ -21,9 +25,22 @@ from tests.integration.aio.builder import PartitioningScenarioBuilder from tests.integration.sync.builder import PartitioningScenarioBuilder as SyncPartitioningScenarioBuilder -# Set event loop policy for Windows as early as possible +# freeze_time walks every loaded module's attributes to find the datetimes to +# patch. testcontainers' config module answers a module-level __getattr__ for +# its deprecated names by asking the Docker daemon for its socket path -- so a +# frozen clock in a unit test opened a docker client, and on a machine without +# Docker the SDK leaves the failed socket unclosed, which the garbage collector +# then reports in whatever test happens to be running. Neither module holds a +# clock worth freezing. +freezegun.configure(extend_ignore_list=["testcontainers", "docker"]) + +# Set event loop policy for Windows as early as possible. Python 3.14 +# deprecates policies for removal in 3.16; until then the selector loop is +# what the drivers need here, and the notice is not this suite's to fail on. if sys.platform == "win32": - asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) @pytest.fixture(scope="session", autouse=True) @@ -73,28 +90,72 @@ def pytest_collection_modifyitems(config: pytest.Config, items: list[pytest.Item @pytest.fixture(scope="session") -def postgres_container() -> Generator[PostgresContainer, None, None]: - """Start a PostgreSQL container for the test session.""" +def postgres_container() -> Generator[PostgresContainer | ExternalPostgres, None, None]: + """The session's PostgreSQL: a container, or the server ``PG_PARTSMITH_TEST_DSN`` names. + + A runner without Docker -- Windows, macOS -- brings a server of its own and + points here at it; the few tests that reach into the container itself skip + there. ``PG_PARTSMITH_TEST_PG_TZ`` starts the container with that zone as the + server's default, so the suite also runs against a clock far from UTC. + """ + dsn = os.environ.get("PG_PARTSMITH_TEST_DSN") + if dsn: + yield ExternalPostgres(dsn) + return if not _docker_is_available(): pytest.skip("Docker is required for integration tests (testcontainers)") - image = os.environ.get("PG_PARTSMITH_TEST_PG_IMAGE", "postgres:17-alpine") - with PostgresContainer(image) as postgres: + image = os.environ.get("PG_PARTSMITH_TEST_PG_IMAGE") or "postgres:17-alpine" + container = PostgresContainer(image) + zone = os.environ.get("PG_PARTSMITH_TEST_PG_TZ") + if zone: + container = container.with_env("TZ", zone).with_env("PGTZ", zone) + with container as postgres: yield postgres +class ExternalPostgres: + """A server the runner brought, wearing the parts of ``PostgresContainer`` the tests use.""" + + def __init__(self, dsn: str) -> None: + parts = urlparse(dsn) + self.username = unquote(parts.username or "postgres") + self.password = unquote(parts.password or "") + self.dbname = parts.path.lstrip("/") or "postgres" + self.port = parts.port or 5432 + self._dsn = dsn + + def get_connection_url(self) -> str: + return self._dsn + + def exec(self, command: object) -> None: + pytest.skip(f"cannot run {command!r}: this server is not a container") + + def _docker_is_available() -> bool: try: client = docker.from_env() - client.ping() except Exception: return False - else: - return True + # Closed, not dropped: the answer keeps a connection in its pool otherwise. + with contextlib.closing(client): + try: + client.ping() + except Exception: + return False + return True @pytest.fixture(scope="session") def redis_container() -> Generator[RedisContainer, None, None]: - """Start a Redis container for the test session.""" + """Start a Redis container for the test session. + + A runner that brought its own PostgreSQL (``PG_PARTSMITH_TEST_DSN``) has no + Linux containers to offer whatever ``docker`` answers there -- a Windows + runner has a daemon that cannot run one -- so Redis is the server + ``PG_PARTSMITH_TEST_REDIS_URL`` names, or the lock tests skip. + """ + if os.environ.get("PG_PARTSMITH_TEST_DSN"): + pytest.skip("no container runtime here; PG_PARTSMITH_TEST_REDIS_URL names a Redis, or the lock tests skip") if not _docker_is_available(): pytest.skip("Docker is required for integration tests (testcontainers)") with RedisContainer("redis:7-alpine") as container: @@ -102,10 +163,14 @@ def redis_container() -> Generator[RedisContainer, None, None]: @pytest.fixture(scope="session") -def redis_url(redis_container: RedisContainer) -> str: - """``redis://host:port/0`` of the session's Redis container.""" - host = redis_container.get_container_host_ip() - port = redis_container.get_exposed_port(redis_container.port) +def redis_url(request: pytest.FixtureRequest) -> str: + """``redis://host:port/0``: the server named in the environment, or the session's container.""" + named = os.environ.get("PG_PARTSMITH_TEST_REDIS_URL") + if named: + return named + container: RedisContainer = request.getfixturevalue("redis_container") + host = container.get_container_host_ip() + port = container.get_exposed_port(container.port) return f"redis://{host}:{port}/0" diff --git a/tests/e2e/__init__.py b/tests/e2e/__init__.py new file mode 100644 index 0000000..cdf5162 --- /dev/null +++ b/tests/e2e/__init__.py @@ -0,0 +1 @@ +"""The container image, end to end: run as a container, against a database of its own.""" diff --git a/tests/e2e/conftest.py b/tests/e2e/conftest.py new file mode 100644 index 0000000..3d4b99a --- /dev/null +++ b/tests/e2e/conftest.py @@ -0,0 +1,78 @@ +"""Fixtures for running the image end to end. + +``PG_PARTSMITH_E2E_IMAGE`` names the image under test -- ``docker build -t +pg-partsmith:local .`` -- and without it every test here skips. CI builds the +image and points this suite at it, on both architectures. The database is a +container on a network of its own, reachable from the image by alias, and the +commands the tests run are the ones the guides show. +""" + +from __future__ import annotations + +import contextlib +import os +from typing import TYPE_CHECKING + +import docker +import pytest +from testcontainers.core.network import Network +from testcontainers.postgres import PostgresContainer + +from tests.e2e.support import DB_ALIAS, DB_NAME, DB_PASSWORD, DB_USER, Image + +if TYPE_CHECKING: + from collections.abc import Iterator + +IMAGE_ENV_VAR = "PG_PARTSMITH_E2E_IMAGE" + + +@pytest.fixture(scope="session") +def docker_client() -> Iterator[docker.DockerClient]: + try: + client = docker.from_env() + except Exception: # whatever the SDK raises, there is no daemon to talk to + pytest.skip("Docker is required to run the image") + with contextlib.closing(client): + try: + client.ping() + except Exception: + pytest.skip("Docker is required to run the image") + yield client + + +@pytest.fixture(scope="session") +def image_name(docker_client: docker.DockerClient) -> str: + """The image under test. Not set: skip. Set to something that is not here: an error.""" + name = os.environ.get(IMAGE_ENV_VAR) + if not name: + pytest.skip(f"set {IMAGE_ENV_VAR} to the image under test (docker build -t pg-partsmith:local .)") + docker_client.images.get(name) + return name + + +@pytest.fixture(scope="session") +def postgres_image() -> str: + return os.environ.get("PG_PARTSMITH_TEST_PG_IMAGE") or "postgres:17-alpine" + + +@pytest.fixture(scope="session") +def network(image_name: str) -> Iterator[Network]: + """A network of the session's own: the image dials the database by alias on it.""" + with Network() as created: + yield created + + +@pytest.fixture(scope="session") +def postgres(network: Network, postgres_image: str) -> Iterator[PostgresContainer]: + container = ( + PostgresContainer(postgres_image, username=DB_USER, password=DB_PASSWORD, dbname=DB_NAME) + .with_network(network) + .with_network_aliases(DB_ALIAS) + ) + with container as running: + yield running + + +@pytest.fixture(scope="session") +def image(docker_client: docker.DockerClient, image_name: str, network: Network) -> Image: + return Image(docker_client, image_name, network.name) diff --git a/tests/e2e/support.py b/tests/e2e/support.py new file mode 100644 index 0000000..d0c8b53 --- /dev/null +++ b/tests/e2e/support.py @@ -0,0 +1,227 @@ +"""Running the image the way the guides say to, and reading back what it did.""" + +from __future__ import annotations + +import json +import shlex +import time +import uuid +from contextlib import contextmanager +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any + +import pytest + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator, Mapping + from pathlib import Path + + import docker + from docker.models.containers import Container + from testcontainers.postgres import PostgresContainer + +DB_USER = "partsmith" +DB_PASSWORD = "partsmith" +DB_NAME = "partsmith" +DB_ALIAS = "db" +# What a container on the same network dials: the alias, not a mapped port. +INTERNAL_DSN = f"postgresql://{DB_USER}:{DB_PASSWORD}@{DB_ALIAS}:5432/{DB_NAME}" +DOCUMENT_PATH = "/etc/partitions.json" + +# A hook that holds the run -- and the table's lock -- for as long as a test +# needs it held. The image has no `sleep`; it has the interpreter. +SLEEPING_HOOK = ["/opt/venv/bin/python", "-c", "import time; time.sleep(120)"] + + +@dataclass(frozen=True) +class Outcome: + """What one run of the image came back with, the two streams kept apart.""" + + code: int + stdout: str + stderr: str + + +class Image: + """The image under test, run as the container guide says to run it. + + Every run gets a read-only root filesystem, no capabilities and no + privilege escalation -- the ``securityContext`` the Kubernetes page shows + -- and the document is mounted read-only. A test that needs the root + filesystem writable says so. + """ + + def __init__(self, client: docker.DockerClient, name: str, network: str) -> None: + self.client = client + self.name = name + self.network = network + + def start( + self, + *args: str, + env: Mapping[str, str] | None = None, + mounts: Mapping[str, str] | None = None, + read_only: bool = True, + entrypoint: str | None = None, + image: str | None = None, + ) -> Container: + """Start a container and hand it back running; ``finish`` collects it. + + ``mounts`` maps a host path or a volume name to ``"/target"`` or + ``"/target:ro"``. + """ + volumes: dict[str, dict[str, str]] = {} + for source, target in (mounts or {}).items(): + bind, _, mode = target.partition(":") + volumes[str(source)] = {"bind": bind, "mode": mode or "rw"} + return self.client.containers.run( + image or self.name, + command=list(args), + entrypoint=entrypoint, + environment=dict(env or {}), + network=self.network, + volumes=volumes, + read_only=read_only, + cap_drop=["ALL"], + security_opt=["no-new-privileges"], + detach=True, + ) + + def run( + self, + *args: str, + env: Mapping[str, str] | None = None, + mounts: Mapping[str, str] | None = None, + read_only: bool = True, + entrypoint: str | None = None, + image: str | None = None, + timeout: float = 120, + ) -> Outcome: + """Run to completion, and remove the container whatever happened.""" + container = self.start(*args, env=env, mounts=mounts, read_only=read_only, entrypoint=entrypoint, image=image) + try: + return finish(container, timeout=timeout) + finally: + container.remove(force=True) + + +def finish(container: Container, *, timeout: float = 120) -> Outcome: + """Wait for the container to exit, then read its exit code and its two streams.""" + try: + status = container.wait(timeout=timeout) + except Exception: # the SDK raises its transport's timeout; any of them means "still running" + container.kill() + pytest.fail(f"the container was still running after {timeout}s") + return Outcome( + code=int(status["StatusCode"]), + stdout=container.logs(stdout=True, stderr=False).decode("utf-8", errors="replace"), + stderr=container.logs(stdout=False, stderr=True).decode("utf-8", errors="replace"), + ) + + +def sql(postgres: PostgresContainer, statement: str) -> str: + """One statement through ``psql`` inside the database container; the rows, one per line.""" + code, output = postgres.exec(["psql", "-U", DB_USER, "-d", DB_NAME, "-v", "ON_ERROR_STOP=1", "-Atc", statement]) + text = output.decode("utf-8", errors="replace") + assert code == 0, text + return text.strip() + + +def partitioned_table(postgres: PostgresContainer) -> str: + """A fresh range-partitioned table with no partitions, under a name of its own.""" + name = f"e2e_{uuid.uuid4().hex[:8]}" + sql( + postgres, + f'CREATE TABLE "{name}" (id bigserial, created_at timestamptz NOT NULL) PARTITION BY RANGE (created_at)', + ) + return name + + +def expired_partition(postgres: PostgresContainer, table: str) -> str: + """A partition long past any retention, attached by hand the way a legacy one would be.""" + name = f"{table}__2020_01" + sql( + postgres, + f'CREATE TABLE "{name}" PARTITION OF "{table}" ' + "FOR VALUES FROM ('2020-01-01 00:00:00+00') TO ('2020-02-01 00:00:00+00')", + ) + return name + + +def holds_advisory_lock(postgres: PostgresContainer) -> bool: + """Whether some session holds the advisory lock a maintenance run takes.""" + return sql(postgres, "SELECT count(*) FROM pg_locks WHERE locktype = 'advisory'") != "0" + + +def wait_until(condition: Callable[[], bool], *, what: str, timeout: float = 30.0) -> None: + """Poll until ``condition`` holds, or fail the test naming what did not happen.""" + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if condition(): + return + time.sleep(0.2) + pytest.fail(f"{what} did not happen within {timeout:.0f}s") + + +def write_document( + path: Path, + *, + table: str, + retention: int = 12, + dsn: str | None = None, + hooks: Mapping[str, Any] | None = None, +) -> Path: + """One table, monthly, two partitions ahead: the document the guides start from, as JSON.""" + payload: dict[str, Any] = { + "tables": [ + { + "table_name": table, + "partition_column": "created_at", + "granularity": "month", + "create_ahead_count": 2, + "retention_count": retention, + } + ] + } + if dsn is not None: + payload["dsn"] = dsn + if hooks is not None: + payload["hooks"] = dict(hooks) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(payload), encoding="utf-8") + return path + + +def writable_dir(path: Path) -> Path: + """A directory UID 65532 can write when it is bind-mounted from a Linux host.""" + path.mkdir(parents=True, exist_ok=True) + path.chmod(0o777) # a test's scratch directory, shared with a container running as another user + return path + + +@contextmanager +def root_owned_volume( + client: docker.DockerClient, helper_image: str, *, secrets: Mapping[str, str] | None = None +) -> Iterator[str]: + """A named volume whose contents belong to root, as a hostPath or a secret mount would. + + Filled through an image that has a shell, since the image under test has + none; each secret is a file only root can read, the way a ``defaultMode`` + of ``0400`` arrives. + """ + volume = client.volumes.create(f"pg-partsmith-e2e-{uuid.uuid4().hex[:8]}") + try: + if secrets: + script = " && ".join( + f"printf %s {shlex.quote(text)} > /v/{name} && chmod 600 /v/{name}" for name, text in secrets.items() + ) + client.containers.run( + helper_image, + entrypoint="sh", + command=["-c", script], + volumes={volume.name: {"bind": "/v", "mode": "rw"}}, + remove=True, + ) + yield volume.name + finally: + volume.remove(force=True) diff --git a/tests/e2e/test_compose.py b/tests/e2e/test_compose.py new file mode 100644 index 0000000..39ee2f3 --- /dev/null +++ b/tests/e2e/test_compose.py @@ -0,0 +1,106 @@ +"""The Compose shape from the guide -- partitions before the application -- run as written.""" + +from __future__ import annotations + +import shutil +import subprocess +import uuid +from typing import TYPE_CHECKING + +import pytest + +from tests.e2e.support import DB_ALIAS, DB_NAME, DB_PASSWORD, DB_USER, DOCUMENT_PATH, write_document + +if TYPE_CHECKING: + from pathlib import Path + +pytestmark = pytest.mark.e2e + +# The guide's "Before the application starts", with the securityContext the +# Kubernetes page gives the same container, and the image standing in for the +# application: `--version` is the shortest program that proves it was started. +COMPOSE = """\ +services: + db: + image: @POSTGRES_IMAGE@ + environment: { POSTGRES_USER: @USER@, POSTGRES_PASSWORD: @PASSWORD@, POSTGRES_DB: @DB@ } + volumes: ["./init.sql:/docker-entrypoint-initdb.d/init.sql:ro"] + healthcheck: + test: ["CMD-SHELL", "pg_isready -h localhost -U @USER@ -d @DB@"] + interval: 1s + timeout: 3s + retries: 30 + + partitions: + image: @IMAGE@ + command: ["apply", "-c", "@DOCUMENT@"] # creations only + environment: { PG_PARTSMITH_DSN_FILE: /run/secrets/pg_dsn } + secrets: [pg_dsn] + volumes: ["./partitions.json:@DOCUMENT@:ro"] + read_only: true + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] + depends_on: + db: { condition: service_healthy } + + app: + image: @IMAGE@ + command: ["--version"] + depends_on: + partitions: { condition: service_completed_successfully } + +secrets: + pg_dsn: + file: ./pg_dsn +""" + + +@pytest.fixture(scope="module") +def compose() -> list[str]: + """The Compose plugin, or a skip: the suite is about the image, not about Compose being installed.""" + command = ["docker", "compose"] + if shutil.which("docker") is None or _run([*command, "version"]).returncode != 0: + pytest.skip("docker compose is not available here") + return command + + +def _run(command: list[str]) -> subprocess.CompletedProcess[str]: + return subprocess.run(command, capture_output=True, text=True, check=False) # noqa: S603 - our own arguments, no shell + + +def test__before_the_application_starts__the_app_runs_only_once_partitions_exist( + image_name: str, postgres_image: str, compose: list[str], tmp_path: Path +) -> None: + (tmp_path / "init.sql").write_text( + "CREATE TABLE events (id bigserial, created_at timestamptz NOT NULL) PARTITION BY RANGE (created_at);\n", + encoding="utf-8", + ) + write_document(tmp_path / "partitions.json", table="events") + dsn = f"postgresql://{DB_USER}:{DB_PASSWORD}@{DB_ALIAS}:5432/{DB_NAME}" + (tmp_path / "pg_dsn").write_text(dsn, encoding="utf-8") + text = COMPOSE + for placeholder, value in { + "@POSTGRES_IMAGE@": postgres_image, + "@IMAGE@": image_name, + "@DOCUMENT@": DOCUMENT_PATH, + "@USER@": DB_USER, + "@PASSWORD@": DB_PASSWORD, + "@DB@": DB_NAME, + }.items(): + text = text.replace(placeholder, value) + (tmp_path / "compose.yaml").write_text(text, encoding="utf-8") + project = [*compose, "-p", f"pg-partsmith-e2e-{uuid.uuid4().hex[:8]}", "-f", str(tmp_path / "compose.yaml")] + + try: + # `run app` starts what app depends on first: the database until healthy, + # then partitions until it has exited 0. Only then does app run. + app = _run([*project, "run", "--rm", "app"]) + assert app.returncode == 0, app.stdout + app.stderr + assert app.stdout.startswith("pg-partsmith ") + + # "A service you run, not one that runs": the same file, one command by hand. + check = _run([*project, "run", "--rm", "partitions", "plan", "-c", DOCUMENT_PATH, "--check"]) + assert check.returncode == 0, check.stdout + check.stderr + assert "nothing to do" in check.stdout + finally: + _run([*project, "down", "--volumes", "--remove-orphans", "--timeout", "5"]) diff --git a/tests/e2e/test_image.py b/tests/e2e/test_image.py new file mode 100644 index 0000000..420948a --- /dev/null +++ b/tests/e2e/test_image.py @@ -0,0 +1,74 @@ +"""What the image is, before it reaches a database.""" + +from __future__ import annotations + +import json +from typing import TYPE_CHECKING + +import pytest + +import pg_partsmith + +if TYPE_CHECKING: + import docker + + from tests.e2e.support import Image + +pytestmark = pytest.mark.e2e + +REPOSITORY = "https://github.com/bedrock-python/pg-partsmith" + +# The shell step CI used to run, as a test: every extension module the image +# keeps loads, and the base holds what they need at runtime. +CLOSURE = """ +import bz2, hashlib, lzma, os, ssl, uuid, zlib, zoneinfo +import asyncpg, greenlet, pydantic_core, sqlalchemy, typer, yaml +assert os.getuid() == 65532, os.getuid() +assert not os.path.exists("/bin/sh"), "a shell got in" +assert ssl.create_default_context().cert_store_stats()["x509_ca"] > 0, "no CA certificates" +zoneinfo.ZoneInfo("Pacific/Kiritimati") +print("closure ok") +""" + + +def test__the_image__is_the_command_as_a_fixed_non_root_user( + docker_client: docker.DockerClient, image_name: str +) -> None: + config = docker_client.images.get(image_name).attrs["Config"] + + # A number, not a name: runAsNonRoot is checked by number, and a name fails it. + assert config["User"] == "65532:65532" + # Exec form: the command is PID 1 and gets the signals; a shell in between would keep them. + assert config["Entrypoint"] == ["/opt/venv/bin/python", "-m", "pg_partsmith.cli"] + assert config["Cmd"] == ["--help"] + assert config["Labels"]["org.opencontainers.image.source"] == REPOSITORY + assert config["Labels"]["org.opencontainers.image.version"] + + +def test__version__is_the_library_s_own_number(image: Image) -> None: + outcome = image.run("--version") + + assert outcome.code == 0, outcome.stderr + assert outcome.stdout.strip() == f"pg-partsmith {pg_partsmith.__version__}" + + +def test__schema__is_json_on_stdout_and_nothing_on_stderr(image: Image) -> None: + outcome = image.run("schema") + + assert outcome.code == 0, outcome.stderr + assert outcome.stderr == "" + assert "properties" in json.loads(outcome.stdout) + + +def test__a_usage_error__is_64_and_not_the_2_that_means_drift(image: Image) -> None: + outcome = image.run("plan", "--no-such-flag") + + assert outcome.code == 64 + assert "--no-such-flag" in outcome.stderr + + +def test__the_runtime__has_the_closure_and_neither_a_shell_nor_root(image: Image) -> None: + outcome = image.run("-c", CLOSURE, entrypoint="/opt/venv/bin/python") + + assert outcome.code == 0, outcome.stderr + assert outcome.stdout.strip() == "closure ok" diff --git a/tests/e2e/test_run.py b/tests/e2e/test_run.py new file mode 100644 index 0000000..93d7e93 --- /dev/null +++ b/tests/e2e/test_run.py @@ -0,0 +1,313 @@ +"""The image against a database: the commands the guides show, with the codes they promise.""" + +from __future__ import annotations + +import json +import subprocess +import time +import uuid +from typing import TYPE_CHECKING + +import pytest + +from tests.e2e.support import ( + DB_PASSWORD, + DOCUMENT_PATH, + INTERNAL_DSN, + SLEEPING_HOOK, + expired_partition, + finish, + holds_advisory_lock, + partitioned_table, + root_owned_volume, + wait_until, + writable_dir, + write_document, +) + +if TYPE_CHECKING: + from pathlib import Path + + import docker + from testcontainers.postgres import PostgresContainer + + from tests.e2e.support import Image + +pytestmark = pytest.mark.e2e + +ENV = {"PG_PARTSMITH_DSN": INTERNAL_DSN} + + +@pytest.fixture +def table(postgres: PostgresContainer) -> str: + return partitioned_table(postgres) + + +@pytest.fixture +def document(tmp_path: Path, table: str) -> Path: + return write_document(tmp_path / "partitions.json", table=table) + + +def _mounted(document: Path) -> dict[str, str]: + """The document where the guides mount it, read-only.""" + return {str(document): f"{DOCUMENT_PATH}:ro"} + + +# ── The ordinary run ────────────────────────────────────────────────────────── + + +def test__a_fresh_table__drifts_and_apply_converges_it(image: Image, document: Path, table: str) -> None: + drift = image.run("plan", "-c", DOCUMENT_PATH, "--check", env=ENV, mounts=_mounted(document)) + assert drift.code == 2, drift.stderr + assert f"CREATE public.{table}__" in drift.stdout + + applied = image.run("apply", "-c", DOCUMENT_PATH, env=ENV, mounts=_mounted(document)) + assert applied.code == 0, applied.stderr + assert "created 2" in applied.stdout + # Human output carries an em dash; PID 1's stdout is a pipe, and it survives. + assert "—" in applied.stdout + + converged = image.run("plan", "-c", DOCUMENT_PATH, "--check", env=ENV, mounts=_mounted(document)) + assert converged.code == 0, converged.stderr + assert "nothing to do" in converged.stdout + + +def test__output_json__is_the_envelope_alone_on_stdout(image: Image, document: Path) -> None: + outcome = image.run("plan", "-c", DOCUMENT_PATH, "--output", "json", env=ENV, mounts=_mounted(document)) + + assert outcome.code == 0, outcome.stderr + assert outcome.stderr == "" + envelope = json.loads(outcome.stdout) + assert envelope["command"] == "plan" + assert envelope["tables"][0]["plan"]["config_fingerprint"] + + +def test__write__lands_the_textfile_in_a_volume_and_keeps_stdout_empty( + image: Image, document: Path, tmp_path: Path +) -> None: + textfile = writable_dir(tmp_path / "textfile") + + outcome = image.run( + "plan", "-c", DOCUMENT_PATH, "--check", "--output", "metrics", "--write", "/textfile/partsmith.prom", + env=ENV, + mounts={**_mounted(document), str(textfile): "/textfile"}, + ) # fmt: skip + + # Drift is still the answer; the file is only where the output went. + assert outcome.code == 2, outcome.stderr + assert outcome.stdout == "" + written = (textfile / "partsmith.prom").read_text(encoding="utf-8") + assert written.startswith("# HELP pg_partsmith_run_timestamp_seconds") + assert "pg_partsmith_pending_operations" in written + # Written beside the target and renamed: nothing half-done is left for a collector to find. + assert [p.name for p in textfile.iterdir()] == ["partsmith.prom"] + + +def test__write__a_directory_the_user_cannot_write__is_exit_4_with_the_path( + image: Image, document: Path, docker_client: docker.DockerClient, postgres_image: str +) -> None: + # A hostPath directory on a node is root's, and this container is not root. + with root_owned_volume(docker_client, postgres_image) as volume: + outcome = image.run( + "plan", "-c", DOCUMENT_PATH, "--output", "metrics", "--write", "/textfile/partsmith.prom", + env=ENV, + mounts={**_mounted(document), volume: "/textfile"}, + ) # fmt: skip + + assert outcome.code == 4 + assert outcome.stderr.startswith("pg-partsmith: Cannot write /textfile/partsmith.prom") + assert "Traceback" not in outcome.stderr + + +def test__save__a_directory_the_user_cannot_write__is_exit_4_and_not_a_database_error( + image: Image, document: Path, docker_client: docker.DockerClient, postgres_image: str +) -> None: + with root_owned_volume(docker_client, postgres_image) as volume: + outcome = image.run( + "plan", "-c", DOCUMENT_PATH, "--save", "/work/plan.json", + env=ENV, + mounts={**_mounted(document), volume: "/work"}, + ) # fmt: skip + + assert outcome.code == 4 + assert outcome.stderr.startswith("pg-partsmith: Cannot write the plan to /work/plan.json") + + +# ── Where the connection string comes from ──────────────────────────────────── + + +def test__dsn_file__reads_a_mounted_secret(image: Image, document: Path, tmp_path: Path, table: str) -> None: + secret = tmp_path / "pg_dsn" + secret.write_text(INTERNAL_DSN, encoding="utf-8") + + outcome = image.run( + "validate", "-c", DOCUMENT_PATH, + env={"PG_PARTSMITH_DSN_FILE": "/run/secrets/pg_dsn"}, + mounts={**_mounted(document), str(secret): "/run/secrets/pg_dsn:ro"}, + ) # fmt: skip + + assert outcome.code == 0, outcome.stderr + assert f"{table} — ok" in outcome.stdout + + +def test__dsn_file__a_secret_only_root_can_read__is_exit_4_and_a_sentence( + image: Image, document: Path, docker_client: docker.DockerClient, postgres_image: str +) -> None: + # A Secret mounted with defaultMode 0400 and no fsGroup arrives exactly like this. + with root_owned_volume(docker_client, postgres_image, secrets={"pg_dsn": INTERNAL_DSN}) as volume: + outcome = image.run( + "validate", "-c", DOCUMENT_PATH, + env={"PG_PARTSMITH_DSN_FILE": "/run/secrets/pg_dsn"}, + mounts={**_mounted(document), volume: "/run/secrets:ro"}, + ) # fmt: skip + + assert outcome.code == 4 + assert outcome.stderr.startswith("pg-partsmith: Cannot read the DSN from /run/secrets/pg_dsn") + + +def test__a_password_the_server_rejects__is_exit_5_and_not_a_traceback(image: Image, document: Path) -> None: + rejected = {"PG_PARTSMITH_DSN": INTERNAL_DSN.replace(f":{DB_PASSWORD}@", ":wrong@")} + + outcome = image.run("validate", "-c", DOCUMENT_PATH, env=rejected, mounts=_mounted(document)) + + assert outcome.code == 5 + assert "password authentication failed" in outcome.stderr + assert "Traceback" not in outcome.stderr + + +# ── Hooks, stops and overlapping runs ───────────────────────────────────────── + + +def test__hooks_declared__without_allow_hooks__is_refused_before_connecting( + image: Image, tmp_path: Path, table: str +) -> None: + document = write_document(tmp_path / "partitions.json", table=table, hooks={"before_create": SLEEPING_HOOK}) + nowhere = {"PG_PARTSMITH_DSN": "postgresql://nobody:nobody@nowhere.invalid/none"} + + outcome = image.run("apply", "-c", DOCUMENT_PATH, env=nowhere, mounts=_mounted(document)) + + assert outcome.code == 4 + assert "--allow-hooks" in outcome.stderr + + +def test__sigterm__cancels_the_run_releases_the_lock_and_exits_143( + image: Image, postgres: PostgresContainer, tmp_path: Path, table: str +) -> None: + # A command hook that holds the run: what an archiver mid-export looks like + # when a pod's deadline arrives. + document = write_document(tmp_path / "partitions.json", table=table, hooks={"before_create": SLEEPING_HOOK}) + container = image.start("apply", "-c", DOCUMENT_PATH, "--allow-hooks", env=ENV, mounts=_mounted(document)) + try: + wait_until(lambda: holds_advisory_lock(postgres), what="the run taking its lock") + started = time.monotonic() + container.stop(timeout=20) # what `docker stop` and a kubelet do: SIGTERM, then SIGKILL after the grace + elapsed = time.monotonic() - started + outcome = finish(container) + finally: + container.remove(force=True) + + assert outcome.code == 143, outcome.stderr + assert outcome.stderr.rstrip().endswith("pg-partsmith: terminated") + assert elapsed < 15, f"stopping took {elapsed:.1f}s: the grace period was used up" + # The lock went with the run, and nothing was created under a hook that never finished. + after = image.run("plan", "-c", DOCUMENT_PATH, "--check", env=ENV, mounts=_mounted(document)) + assert after.code == 2, after.stderr + + +def test__an_overlapping_run__stands_aside_with_6_or_with_0_when_told_to( + image: Image, postgres: PostgresContainer, tmp_path: Path, table: str +) -> None: + document = write_document(tmp_path / "partitions.json", table=table, hooks={"before_create": SLEEPING_HOOK}) + holder = image.start("apply", "-c", DOCUMENT_PATH, "--allow-hooks", env=ENV, mounts=_mounted(document)) + try: + wait_until(lambda: holds_advisory_lock(postgres), what="the first run taking its lock") + second = image.run("apply", "-c", DOCUMENT_PATH, "--allow-hooks", env=ENV, mounts=_mounted(document)) + # An init container restarts on anything non-zero, and a held lock is not a failure there. + init = image.run( + "apply", "-c", DOCUMENT_PATH, "--allow-hooks", "--ok-if-locked", env=ENV, mounts=_mounted(document) + ) + finally: + holder.stop(timeout=20) + holder.remove(force=True) + + assert second.code == 6, second.stderr + assert "lock" in second.stderr + assert init.code == 0, init.stderr + + +# ── The artifact between plan and apply, and a hook inside the image ────────── + + +def test__plan_save_then_apply_plan__is_the_artifact_between_two_containers( + image: Image, document: Path, tmp_path: Path, table: str +) -> None: + work = writable_dir(tmp_path / "work") + mounts = {**_mounted(document), str(work): "/work"} + + planned = image.run("plan", "-c", DOCUMENT_PATH, "--save", "/work/plan.json", "--locks", env=ENV, mounts=mounts) + assert planned.code == 0, planned.stderr + saved = json.loads((work / "plan.json").read_text(encoding="utf-8")) + assert saved["tables"][0]["plan"]["config_fingerprint"] + + applied = image.run("apply", "-c", DOCUMENT_PATH, "--plan", "/work/plan.json", env=ENV, mounts=mounts) + assert applied.code == 0, applied.stderr + assert "created 2" in applied.stdout + + # The ConfigMap edited between the two: the plan no longer answers for it. + edited = write_document(tmp_path / "edited" / "partitions.json", table=table, retention=3) + refused = image.run( + "apply", "-c", DOCUMENT_PATH, "--plan", "/work/plan.json", + env=ENV, + mounts={**_mounted(edited), str(work): "/work"}, + ) # fmt: skip + assert refused.code == 4, refused.stderr + assert "Traceback" not in refused.stderr + + +def test__a_derived_image__runs_a_python_file_hook_from_inside( + image: Image, docker_client: docker.DockerClient, postgres: PostgresContainer, tmp_path: Path, table: str +) -> None: + # The guide's recipe for a hook in a cluster: one FROM, one COPY. + context = tmp_path / "derived" + context.mkdir() + (context / "archive.py").write_text( + "import pathlib, sys\npathlib.Path('/work/archived.json').write_text(sys.stdin.read(), encoding='utf-8')\n", + encoding="utf-8", + ) + (context / "Dockerfile").write_text( + f"FROM {image.name}\nCOPY --chmod=755 archive.py /opt/hooks/archive.py\n", encoding="utf-8" + ) + derived = f"pg-partsmith-e2e-derived:{uuid.uuid4().hex[:8]}" + build = subprocess.run( # noqa: S603 - our own arguments, no shell + ["docker", "build", "--quiet", "-t", derived, str(context)], capture_output=True, text=True, check=False + ) + assert build.returncode == 0, build.stderr + + try: + # A table maintained once, then a partition long past any retention. + plain = write_document(tmp_path / "plain.json", table=table) + assert image.run("apply", "-c", DOCUMENT_PATH, env=ENV, mounts=_mounted(plain), image=derived).code == 0 + expired = expired_partition(postgres, table) + hooked = write_document( + tmp_path / "hooked.json", + table=table, + retention=1, + hooks={"before_drop": ["/opt/venv/bin/python", "/opt/hooks/archive.py"]}, + ) + work = writable_dir(tmp_path / "work") + + outcome = image.run( + "apply", "-c", DOCUMENT_PATH, "--allow-destructive", "--allow-hooks", + env=ENV, + mounts={**_mounted(hooked), str(work): "/work"}, + image=derived, + ) # fmt: skip + finally: + docker_client.images.remove(derived, force=True) + + # It ran, inside the image, and was told which partition and why. + assert outcome.code == 0, outcome.stderr + event = json.loads((work / "archived.json").read_text(encoding="utf-8")) + assert event["phase"] == "before_drop" + assert event["partition"]["name"].endswith(expired) + assert event["operation"]["reason"] in {"grace_elapsed", "follows_detach"} diff --git a/tests/integration/aio/support.py b/tests/integration/aio/support.py index 46e4758..dfe1a48 100644 --- a/tests/integration/aio/support.py +++ b/tests/integration/aio/support.py @@ -147,7 +147,10 @@ async def child_count(engine: AsyncEngine, parent: str) -> int: async def _child_bounds(engine: AsyncEngine, parent: str) -> list[Any]: - async with engine.connect() as conn: + # Bounds are rendered in the session time zone. Read in UTC whatever the + # server defaults to, so a bound is one string in every test environment. + async with engine.begin() as conn: + await conn.execute(text("SET LOCAL TIME ZONE 'UTC'")) result = await conn.execute(text(CHILD_BOUNDS_SQL), {"parent": quote_identifier(parent)}) return list(result.fetchall()) diff --git a/tests/integration/aio/test_cli.py b/tests/integration/aio/test_cli.py new file mode 100644 index 0000000..40dd27d --- /dev/null +++ b/tests/integration/aio/test_cli.py @@ -0,0 +1,363 @@ +"""The CLI end to end: a document, a real database, and the codes it exits with.""" + +from __future__ import annotations + +import asyncio +import json +import sys +from typing import TYPE_CHECKING, Any + +import pytest +import pytest_asyncio +from sqlalchemy import text + +from pg_partsmith.cli import ExitCode, main +from tests.integration.aio.support import exec_sql, make_service, make_table +from tests.integration.nested_support import MONTHLY_TABLE_DDL, monthly_config + +if TYPE_CHECKING: + from collections.abc import AsyncGenerator + from pathlib import Path + + from sqlalchemy.ext.asyncio import AsyncEngine + +pytestmark = pytest.mark.integration + + +@pytest_asyncio.fixture +async def table(db_engine: AsyncEngine) -> AsyncGenerator[str, None]: + async for name in make_table(db_engine, MONTHLY_TABLE_DDL, prefix="cli"): + yield name + + +async def _run_cli(*args: str) -> int: + """Drive the CLI from a worker thread: it owns an event loop of its own.""" + return await asyncio.to_thread(main, list(args)) + + +def _document(tmp_path: Path, table: str, dsn: str, *, retention: int = 12, hooks: dict[str, Any] | None = None) -> str: + """A document describing that one table, written where the CLI will read it.""" + schema, _, relname = table.rpartition(".") + payload = { + "dsn": dsn, + "tables": [ + { + "table_name": relname, + "schema": schema or None, + "partition_column": "created_at", + "granularity": "month", + "create_ahead_count": 2, + "retention_count": retention, + } + ], + } + if hooks is not None: + payload["hooks"] = hooks + tmp_path.mkdir(parents=True, exist_ok=True) + path = tmp_path / "partitions.json" + path.write_text(json.dumps(payload), encoding="utf-8") + return str(path) + + +def _dsn(db_engine: AsyncEngine) -> str: + return db_engine.url.render_as_string(hide_password=False) + + +async def _with_an_expired_partition(db_engine: AsyncEngine, table: str) -> None: + """Two live windows, and one long past any retention.""" + await make_service(db_engine).maintain(monthly_config(table, create_ahead=2, retention=12)) + await exec_sql( + db_engine, + f'CREATE TABLE "{table}__2020_01" PARTITION OF "{table}" ' + "FOR VALUES FROM ('2020-01-01 00:00:00+00') TO ('2020-02-01 00:00:00+00')", + ) + + +async def test__validate__a_table_the_document_matches__exits_ok( + db_engine: AsyncEngine, table: str, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + # Arrange + config = _document(tmp_path, table, _dsn(db_engine)) + + # Act + code = await _run_cli("validate", "-c", config) + + # Assert + assert code == ExitCode.OK + assert "ok" in capsys.readouterr().out + + +async def test__validate__a_table_that_is_not_partitioned__exits_config(db_engine: AsyncEngine, tmp_path: Path) -> None: + # Arrange: a table the document describes and PostgreSQL does not have + config = _document(tmp_path, "public.no_such_table", _dsn(db_engine)) + + # Act / Assert + assert await _run_cli("validate", "-c", config) == ExitCode.CONFIG + + +async def test__plan__a_fresh_table__reports_drift_under_check_and_issues_no_ddl( + db_engine: AsyncEngine, table: str, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + # Arrange + config = _document(tmp_path, table, _dsn(db_engine)) + + # Act + code = await _run_cli("plan", "-c", config, "--check", "--output", "json") + payload = json.loads(capsys.readouterr().out) + + # Assert: this is what "maintenance has not been running" looks like + assert code == ExitCode.DRIFT + assert payload["command"] == "plan" + assert [op["kind"] for op in payload["tables"][0]["plan"]["operations"]] == ["create", "create"] + + # And nothing was created by asking + assert await _run_cli("inspect", "-c", config, "--output", "json") == ExitCode.OK + tree = json.loads(capsys.readouterr().out)["tables"][0]["tree"] + assert tree["root"]["children"] == [] + + +async def test__plan__after_maintenance__is_converged_and_exits_ok( + db_engine: AsyncEngine, table: str, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + # Arrange + # The CLI plans against the real clock, so this tick must run on it too. + await make_service(db_engine).maintain(monthly_config(table, create_ahead=2, retention=12)) + config = _document(tmp_path, table, _dsn(db_engine)) + + # Act + code = await _run_cli("plan", "-c", config, "--check") + + # Assert + assert code == ExitCode.OK + assert "nothing to do" in capsys.readouterr().out + + +async def test__inspect__a_maintained_table__prints_the_tree_that_exists( + db_engine: AsyncEngine, table: str, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + # Arrange + # The CLI plans against the real clock, so this tick must run on it too. + await make_service(db_engine).maintain(monthly_config(table, create_ahead=2, retention=12)) + config = _document(tmp_path, table, _dsn(db_engine)) + + # Act + code = await _run_cli("inspect", "-c", config) + printed = capsys.readouterr().out + + # Assert + assert code == ExitCode.OK + assert table in printed + assert "FOR VALUES FROM" in printed + + +async def test__table__narrows_the_run_to_one_table_of_the_document( + db_engine: AsyncEngine, table: str, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + # Arrange + _, _, relname = table.rpartition(".") + config = _document(tmp_path, table, _dsn(db_engine)) + + # Act + code = await _run_cli("plan", "-c", config, "--table", relname, "--output", "json") + + # Assert + assert code == ExitCode.OK + assert len(json.loads(capsys.readouterr().out)["tables"]) == 1 + + +async def test__dsn__a_database_that_is_not_there__exits_connection(tmp_path: Path) -> None: + # Arrange + config = _document(tmp_path, "public.events", "postgresql://nobody@127.0.0.1:1/none") + + # Act / Assert: a connection failure is its own code, not a generic failure + assert await _run_cli("validate", "-c", config) == ExitCode.CONNECTION + + +async def test__apply__by_default__creates_and_retires_nothing( + db_engine: AsyncEngine, table: str, tmp_path: Path +) -> None: + # Arrange: two live windows and one that retention has long expired + await _with_an_expired_partition(db_engine, table) + config = _document(tmp_path, table, _dsn(db_engine), retention=1) + + # Act: the safe mode is the default one + code = await _run_cli("apply", "-c", config) + + # Assert: the expired partition is still attached + assert code == ExitCode.OK + async with db_engine.begin() as conn: + attached = await conn.execute( + text("SELECT count(*) FROM pg_inherits i JOIN pg_class p ON p.oid = i.inhparent WHERE p.relname = :table"), + {"table": table}, + ) + assert attached.scalar_one() == 3 + + +async def test__apply__allow_destructive__retires_what_retention_expired( + db_engine: AsyncEngine, table: str, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + # Arrange + await _with_an_expired_partition(db_engine, table) + config = _document(tmp_path, table, _dsn(db_engine), retention=1) + + # Act + code = await _run_cli("apply", "-c", config, "--allow-destructive", "--output", "json") + payload = json.loads(capsys.readouterr().out) + + # Assert + assert code == ExitCode.OK + assert payload["tables"][0]["result"]["detached_count"] == 1 + + +async def test__plan_save__then_apply__is_the_artifact_between_the_two( + db_engine: AsyncEngine, table: str, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + # Arrange + config = _document(tmp_path, table, _dsn(db_engine)) + saved = tmp_path / "plan.json" + + # Act: plan it, read it, then apply exactly that + assert await _run_cli("plan", "-c", config, "--save", str(saved)) == ExitCode.OK + written = json.loads(saved.read_text(encoding="utf-8")) + capsys.readouterr() + code = await _run_cli("apply", "-c", config, "--plan", str(saved)) + + # Assert + assert written["tables"][0]["plan"]["config_fingerprint"] + assert code == ExitCode.OK + assert "created 2" in capsys.readouterr().out + + +async def test__apply__a_plan_made_under_another_configuration__is_refused( + db_engine: AsyncEngine, table: str, tmp_path: Path +) -> None: + # Arrange: plan under one retention, then edit the document + planned_under = _document(tmp_path, table, _dsn(db_engine), retention=12) + saved = tmp_path / "plan.json" + assert await _run_cli("plan", "-c", planned_under, "--save", str(saved)) == ExitCode.OK + edited = _document(tmp_path / "edited", table, _dsn(db_engine), retention=3) + + # Act / Assert: the operations still name the right relations, for reasons + # that stopped being true + assert await _run_cli("apply", "-c", edited, "--plan", str(saved)) == ExitCode.CONFIG + assert await _run_cli("apply", "-c", edited, "--plan", str(saved), "--allow-config-drift") == ExitCode.OK + + +async def test__apply__a_command_hook__runs_around_the_real_drop( + db_engine: AsyncEngine, table: str, tmp_path: Path +) -> None: + # Arrange: the export-before-destroy case, as a non-Python team would write it + await _with_an_expired_partition(db_engine, table) + marker = tmp_path / "archived.json" + body = f"import sys, pathlib; pathlib.Path({str(marker)!r}).write_text(sys.stdin.read(), encoding='utf-8')" + config = _document( + tmp_path, + table, + _dsn(db_engine), + retention=1, + hooks={"before_drop": [sys.executable, "-c", body]}, + ) + + # Act + code = await _run_cli("apply", "-c", config, "--allow-destructive", "--allow-hooks") + + # Assert: it ran, and it was told which partition and why + assert code == ExitCode.OK + payload = json.loads(marker.read_text(encoding="utf-8")) + assert payload["phase"] == "before_drop" + assert payload["partition"]["name"].endswith(f"{table}__2020_01") + assert payload["operation"]["reason"] in {"grace_elapsed", "follows_detach"} + + +async def test__apply__a_hook_that_refuses__leaves_the_partition_alone( + db_engine: AsyncEngine, table: str, tmp_path: Path +) -> None: + # Arrange: an archiver that says "not yet" + await _with_an_expired_partition(db_engine, table) + config = _document( + tmp_path, + table, + _dsn(db_engine), + retention=1, + hooks={"before_drop": [sys.executable, "-c", "import sys; sys.exit(1)"]}, + ) + + # Act + code = await _run_cli("apply", "-c", config, "--allow-destructive", "--allow-hooks", "--continue-on-error") + + # Assert: detached, and still there to be dropped once the archiver agrees + assert code == ExitCode.FINDINGS + async with db_engine.begin() as conn: + exists = await conn.execute(text("SELECT to_regclass(:name) IS NOT NULL"), {"name": f"{table}__2020_01"}) + assert exists.scalar_one() is True + + +async def test__apply__hooks_declared_but_not_allowed__refuses_before_connecting( + db_engine: AsyncEngine, table: str, tmp_path: Path +) -> None: + # Arrange + config = _document(tmp_path, table, _dsn(db_engine), hooks={"before_drop": [sys.executable, "-c", "pass"]}) + + # Act / Assert + assert await _run_cli("apply", "-c", config) == ExitCode.CONFIG + + +async def test__output_metrics__a_real_run__is_a_textfile_a_collector_can_serve( + db_engine: AsyncEngine, table: str, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + # Arrange + config = _document(tmp_path, table, _dsn(db_engine)) + + # Act + code = await _run_cli("plan", "-c", config, "--check", "--output", "metrics") + printed = capsys.readouterr().out + + # Assert: the drift the same run reports on its exit code, as a number + assert code == ExitCode.DRIFT + assert "# TYPE pg_partsmith_pending_operations gauge" in printed + assert f'pg_partsmith_pending_operations{{table="{table}",kind="create"}} 2' in printed + assert f'pg_partsmith_pending_operations{{table="{table}",kind="drop"}} 0' in printed + + +async def test__apply__a_python_hook__runs_around_the_real_drop( + db_engine: AsyncEngine, table: str, tmp_path: Path +) -> None: + # Arrange: the same export-before-destroy case, written as a block rather than a binary + await _with_an_expired_partition(db_engine, table) + marker = tmp_path / "archived.txt" + block = f""" +import pathlib +pathlib.Path({str(marker)!r}).write_text(f"{{event.phase.value}} {{event.partition.name}}", encoding="utf-8") +""" + config = _document(tmp_path, table, _dsn(db_engine), retention=1, hooks={"before_drop": {"python": block}}) + + # Act + code = await _run_cli("apply", "-c", config, "--allow-destructive", "--allow-hooks") + + # Assert + assert code == ExitCode.OK + assert marker.read_text(encoding="utf-8").endswith(f"{table}__2020_01") + assert marker.read_text(encoding="utf-8").startswith("before_drop") + + +async def test__apply__a_python_hook_that_raises__leaves_the_partition_alone( + db_engine: AsyncEngine, table: str, tmp_path: Path +) -> None: + # Arrange: raising is how a block says "not yet" + await _with_an_expired_partition(db_engine, table) + config = _document( + tmp_path, + table, + _dsn(db_engine), + retention=1, + hooks={"before_drop": {"python": "raise RuntimeError('archive first')"}}, + ) + + # Act + code = await _run_cli("apply", "-c", config, "--allow-destructive", "--allow-hooks", "--continue-on-error") + + # Assert: detached, and still there to be dropped once the block agrees + assert code == ExitCode.FINDINGS + async with db_engine.begin() as conn: + exists = await conn.execute(text("SELECT to_regclass(:name) IS NOT NULL"), {"name": f"{table}__2020_01"}) + assert exists.scalar_one() is True diff --git a/tests/integration/aio/test_planning.py b/tests/integration/aio/test_planning.py index 0f8c95a..bd54e30 100644 --- a/tests/integration/aio/test_planning.py +++ b/tests/integration/aio/test_planning.py @@ -417,8 +417,8 @@ async def foreign_leaf( metrics_table, postgres_container, suffix="__2025_01", - bounds=("2025-01-01", "2025-02-01"), - row_ts="2025-01-15", + bounds=("2025-01-01 00:00:00+00", "2025-02-01 00:00:00+00"), + row_ts="2025-01-15 00:00:00+00", ): yield name @@ -433,8 +433,8 @@ async def foreign_leaf_now( metrics_table, postgres_container, suffix="__2026_08", - bounds=("2026-08-01", "2026-09-01"), - row_ts="2026-08-15", + bounds=("2026-08-01 00:00:00+00", "2026-09-01 00:00:00+00"), + row_ts="2026-08-15 00:00:00+00", ): yield name diff --git a/tests/integration/nested_support.py b/tests/integration/nested_support.py index 41af708..442d481 100644 --- a/tests/integration/nested_support.py +++ b/tests/integration/nested_support.py @@ -34,8 +34,8 @@ WEEK_SUFFIX = "__2026_w35" NEXT_WEEK_SUFFIX = "__2026_w36" PREVIOUS_WEEK_SUFFIX = "__2026_w34" -WEEK_BOUNDS = ("2026-08-24", "2026-08-31") -PREVIOUS_WEEK_BOUNDS = ("2026-08-17", "2026-08-24") +WEEK_BOUNDS = ("2026-08-24 00:00:00+00", "2026-08-31 00:00:00+00") +PREVIOUS_WEEK_BOUNDS = ("2026-08-17 00:00:00+00", "2026-08-24 00:00:00+00") # Timestamp-keyed root. The primary key carries tenant_id because PostgreSQL # requires every unique constraint on a partitioned table to include all of its diff --git a/tests/integration/sync/support.py b/tests/integration/sync/support.py index 2b5635e..e13b438 100644 --- a/tests/integration/sync/support.py +++ b/tests/integration/sync/support.py @@ -147,7 +147,10 @@ def child_count(engine: Engine, parent: str) -> int: def _child_bounds(engine: Engine, parent: str) -> list[Any]: - with engine.connect() as conn: + # Bounds are rendered in the session time zone. Read in UTC whatever the + # server defaults to, so a bound is one string in every test environment. + with engine.begin() as conn: + conn.execute(text("SET LOCAL TIME ZONE 'UTC'")) result = conn.execute(text(CHILD_BOUNDS_SQL), {"parent": quote_identifier(parent)}) return list(result.fetchall()) diff --git a/tests/integration/sync/test_planning.py b/tests/integration/sync/test_planning.py index 9251fcb..74a7ffa 100644 --- a/tests/integration/sync/test_planning.py +++ b/tests/integration/sync/test_planning.py @@ -412,8 +412,8 @@ def foreign_leaf( metrics_table, postgres_container, suffix="__2025_01", - bounds=("2025-01-01", "2025-02-01"), - row_ts="2025-01-15", + bounds=("2025-01-01 00:00:00+00", "2025-02-01 00:00:00+00"), + row_ts="2025-01-15 00:00:00+00", ) @@ -427,8 +427,8 @@ def foreign_leaf_now( metrics_table, postgres_container, suffix="__2026_08", - bounds=("2026-08-01", "2026-09-01"), - row_ts="2026-08-15", + bounds=("2026-08-01 00:00:00+00", "2026-09-01 00:00:00+00"), + row_ts="2026-08-15 00:00:00+00", ) diff --git a/tests/unit/sync/test_execution.py b/tests/unit/sync/test_execution.py index a563669..6e8ed59 100644 --- a/tests/unit/sync/test_execution.py +++ b/tests/unit/sync/test_execution.py @@ -30,6 +30,7 @@ PartitionError, PartitionReferencedError, PartitionTopologyError, + PlanConfigMismatchError, PlanStaleError, RowMoveRefusedError, ) @@ -169,8 +170,8 @@ def _hash_root_config() -> TablePartitionConfig: ) -def _plan(*operations: Operation, findings: tuple[Finding, ...] = ()) -> MaintenancePlan: - return MaintenancePlan(table_name="events", generated_at=NOW, operations=tuple(operations), findings=findings) +def _plan(*operations: Operation, findings: tuple[Finding, ...] = (), table_name: str = "events") -> MaintenancePlan: + return MaintenancePlan(table_name=table_name, generated_at=NOW, operations=tuple(operations), findings=findings) def _create_op( @@ -1855,7 +1856,7 @@ def test__apply__plain_local_leaves__create_is_spelled_as_it_always_was( ) -> None: # Arrange / Act op = _create_op("public.events__2024_04", parent="public.events") - executor.apply(_leaves_config(LocalLeaves()), _plan(op)) + executor.apply(_leaves_config(LocalLeaves()), _plan(op, table_name="public.events")) # Assert repo.create_table_like.assert_called_once_with("public.events", "public.events__2024_04", None) @@ -1869,7 +1870,7 @@ def test__apply__customised_local_leaves__physical_spec_reaches_the_repository( leaves = LocalLeaves(tablespace="fast", storage_parameters={"fillfactor": 70}) # Act - executor.apply(_leaves_config(leaves), _plan(_create_op())) + executor.apply(_leaves_config(leaves), _plan(_create_op(), table_name="public.events")) # Assert repo.create_table_like.assert_called_once_with("events", "events__2024_04", None, physical=leaves) @@ -1883,7 +1884,7 @@ def test__apply__foreign_leaves__leaf_is_a_foreign_table_with_rendered_options( op = _create_op("public.events__2024_04", parent="public.events") # Act - result = executor.apply(_leaves_config(leaves), _plan(op)) + result = executor.apply(_leaves_config(leaves), _plan(op, table_name="public.events")) # Assert repo.create_foreign_table_like.assert_called_once_with( @@ -1906,7 +1907,7 @@ def test__apply__foreign_leaves__branch_stays_local_and_its_buckets_are_foreign( leaves = ForeignLeaves(server="archive", options={"table_name": "{parent}_{relname}"}) # Act - executor.apply(_leaves_config(leaves, nested=True), _plan(_branch_op())) + executor.apply(_leaves_config(leaves, nested=True), _plan(_branch_op(), table_name="public.events")) # Assert repo.create_table_like.assert_called_once_with("events", "events__2024_04", _branch_op().partition_by) @@ -2172,3 +2173,16 @@ def test__attach_partition__branch_orphan__its_children_carry_the_planned_parent bucket = repo.attach_partition.call_args_list[0] assert bucket.args[0] == "events__2024_04" assert bucket.kwargs["expected_parent_oid"] == 77 + + +def test__apply__a_plan_made_for_another_table__is_refused_before_any_ddl( + executor: PlanExecutor, repo: MagicMock +) -> None: + # Arrange: the plan names relations that exist, under a configuration that + # describes a different table -- reachable once a plan is an artifact. + plan = _plan(_create_op(), table_name="public.audit") + + # Act / Assert + with pytest.raises(PlanConfigMismatchError): + executor.apply(_config(), plan) + repo.create_table_like.assert_not_called() diff --git a/tests/unit/sync/test_service.py b/tests/unit/sync/test_service.py index af4eebd..e3b9a1c 100644 --- a/tests/unit/sync/test_service.py +++ b/tests/unit/sync/test_service.py @@ -488,7 +488,7 @@ def _apply(*args: object, **kwargs: object) -> MaintenanceResult: assert result is expected locks.acquire_lock.assert_called_once_with("events") assert events == ["acquire", "apply", "release"] - service._executor.apply.assert_called_once_with(config, plan, continue_on_error=True) + service._executor.apply.assert_called_once_with(config, plan, continue_on_error=True, allow_config_drift=False) def test__apply__executor_fails__lock_is_still_released( diff --git a/tests/unit/sync/test_toolkit.py b/tests/unit/sync/test_toolkit.py new file mode 100644 index 0000000..7daeefa --- /dev/null +++ b/tests/unit/sync/test_toolkit.py @@ -0,0 +1,143 @@ +"""``PartitionToolkit``: one engine in, a set of collaborators that agree out.""" + +from __future__ import annotations + +from dataclasses import FrozenInstanceError +from unittest.mock import MagicMock + +import pytest + +from pg_partsmith.boundaries import UUIDv7BoundaryCodec +from pg_partsmith.document import ToolkitOptions +from pg_partsmith.sync import ( + BasePartitionLifecycleHooks, + PartitionLifecycleService, + PartitionMaintainer, + PartitionToolkit, + PostgresAdvisoryLockManager, + PostgresMetadataProvider, + PostgresPartitionRepository, +) + + +@pytest.fixture +def engine() -> MagicMock: + return MagicMock() + + +def test__from_engine__builds_every_part_around_the_one_engine(engine: MagicMock) -> None: + # Arrange / Act + kit = PartitionToolkit.from_engine(engine) + + # Assert + assert isinstance(kit.repo, PostgresPartitionRepository) + assert isinstance(kit.metadata, PostgresMetadataProvider) + assert isinstance(kit.locks, PostgresAdvisoryLockManager) + assert isinstance(kit.service, PartitionLifecycleService) + assert isinstance(kit.maintainer, PartitionMaintainer) + + +def test__from_engine__marker_prefix__reaches_the_writer_and_the_reader(engine: MagicMock) -> None: + # Arrange / Act: the prefix given to one of the two only is the failure this + # exists to prevent -- partitions detached under it are invisible to the + # other, so they are never dropped. + kit = PartitionToolkit.from_engine(engine, marker_prefix="acme") + + # Assert + assert kit.repo.marker_prefix == kit.metadata.marker_prefix + assert kit.repo.marker_prefix != PartitionToolkit.from_engine(engine).repo.marker_prefix + + +def test__from_engine__ddl_timezone__is_given_to_both_sides_of_the_boundary(engine: MagicMock) -> None: + # Arrange / Act + kit = PartitionToolkit.from_engine(engine, ddl_timezone="Europe/Berlin") + + # Assert: one writes naive bounds in it, the other reads them back in it + assert kit.repo.ddl_timezone == "Europe/Berlin" + assert kit.metadata._ddl_timezone == "Europe/Berlin" + + +def test__from_engine__nothing_passed__leaves_no_disagreement_to_default_into(engine: MagicMock) -> None: + # The two constructors default differently -- "UTC" on the repository, None + # on the provider -- so a caller who passed neither used to get a reader on + # a timezone the writer never used. + kit = PartitionToolkit.from_engine(engine) + + assert kit.repo.ddl_timezone == "UTC" + assert kit.metadata._ddl_timezone == "UTC" + + +def test__from_engine__a_lock_manager_of_your_own__is_used_as_given(engine: MagicMock) -> None: + # Arrange + locks = MagicMock() + + # Act + kit = PartitionToolkit.from_engine(engine, locks=locks) + + # Assert + assert kit.locks is locks + assert kit.service._locks is locks + + +def test__from_engine__the_service_holds_the_very_parts_that_are_returned(engine: MagicMock) -> None: + # Arrange / Act: the point of returning parts rather than a maintainer is + # that calling metadata or locks directly needs no second wiring. + kit = PartitionToolkit.from_engine(engine) + + # Assert + assert kit.service._repo is kit.repo + assert kit.service._metadata is kit.metadata + assert kit.maintainer._service is kit.service + + +def test__from_engine__hooks__reach_the_executor_that_fires_them(engine: MagicMock) -> None: + # Arrange + hooks = BasePartitionLifecycleHooks() + + # Act + kit = PartitionToolkit.from_engine(engine, hooks=[hooks]) + + # Assert + assert kit.service._executor._hooks == [hooks] + + +def test__toolkit__is_frozen(engine: MagicMock) -> None: + # Arrange + kit = PartitionToolkit.from_engine(engine) + + # Act / Assert + with pytest.raises(FrozenInstanceError): + kit.repo = MagicMock() # type: ignore[misc] + + +def test__from_options__the_runtime_section_of_a_document__is_the_wiring(engine: MagicMock) -> None: + # Arrange: what a file says, in the words a file says it in + options = ToolkitOptions(marker_prefix="acme", ddl_timezone="Europe/Berlin", boundary_codec="uuidv7") + + # Act + kit = PartitionToolkit.from_options(engine, options) + + # Assert + assert kit.repo.marker_prefix == kit.metadata.marker_prefix + assert kit.repo.ddl_timezone == "Europe/Berlin" + assert kit.metadata._ddl_timezone == "Europe/Berlin" + assert isinstance(kit.metadata._boundary_codec, UUIDv7BoundaryCodec) + + +def test__from_options__hooks_and_a_lock_manager__are_passed_through(engine: MagicMock) -> None: + # Arrange + hooks = BasePartitionLifecycleHooks() + locks = MagicMock() + + # Act + kit = PartitionToolkit.from_options(engine, ToolkitOptions(), hooks=[hooks], locks=locks) + + # Assert + assert kit.locks is locks + assert kit.service._executor._hooks == [hooks] + + +def test__from_options__a_codec_name_nothing_answers_to__is_refused(engine: MagicMock) -> None: + # Act / Assert: the file is wrong, and says so before any connection is opened + with pytest.raises(ValueError, match="uuidv8"): + PartitionToolkit.from_options(engine, ToolkitOptions(boundary_codec="uuidv8")) diff --git a/tests/unit/test_cli.py b/tests/unit/test_cli.py new file mode 100644 index 0000000..f5127bd --- /dev/null +++ b/tests/unit/test_cli.py @@ -0,0 +1,1076 @@ +"""The command line: reading a document, choosing a connection, and what it exits with.""" + +from __future__ import annotations + +import asyncio +import importlib +import io +import json +import re +import signal +import sys +from datetime import UTC, datetime +from pathlib import Path +from typing import TYPE_CHECKING, Any +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from pg_partsmith import console +from pg_partsmith.__version__ import __version__ +from pg_partsmith.aio.command_hooks import CommandHooks +from pg_partsmith.cli import ExitCode, main +from pg_partsmith.cli.commands import CommandResult, run_apply, run_plan, run_validate +from pg_partsmith.cli.loader import ( + DSN_ENV_VAR, + DSN_FILE_ENV_VAR, + ConfigError, + async_url, + load_document, + load_plans, + load_python_hooks, + resolve_dsn, + select_configs, +) +from pg_partsmith.cli.main import _hooks as _cli_hooks +from pg_partsmith.cli.render import describe_locks, envelope, plan_entry +from pg_partsmith.document import PartitionsDocument +from pg_partsmith.entities import MaintenanceIssue, MaintenanceIssueStep, MaintenanceResult +from pg_partsmith.events import HookPhase +from pg_partsmith.exceptions import InvalidPartitionConfigError, LockAcquisitionError +from pg_partsmith.hook_commands import CommandHookError +from pg_partsmith.lifecycle import DetachMode +from pg_partsmith.plan import ( + CreatePartition, + DetachPartition, + DropPartition, + Finding, + FindingReason, + MaintenancePlan, + Reason, + Severity, +) +from pg_partsmith.topology import RangeBounds + +if TYPE_CHECKING: + from collections.abc import Sequence + +NOW = datetime(2026, 8, 28, tzinfo=UTC) + +# The package re-exports a function called main, which shadows the submodule on +# attribute access; importlib reaches the module itself. +cli = importlib.import_module("pg_partsmith.cli.main") + +DOCUMENT: dict[str, Any] = { + "defaults": {"schema": "public", "granularity": "month"}, + "tables": [ + {"table_name": "events", "partition_column": "created_at"}, + {"table_name": "audit", "partition_column": "logged_at"}, + ], +} + + +def _write(tmp_path: Path, name: str, text: str) -> Path: + path = tmp_path / name + path.write_text(text, encoding="utf-8") + return path + + +def _plan(*, noop: bool = False, findings: tuple[Finding, ...] = ()) -> MaintenancePlan: + operations = ( + () + if noop + else ( + CreatePartition( + target="public.events__2026_09", + parent_name="public.events", + bounds=RangeBounds(from_value="2026-09-01", to_value="2026-10-01"), + reason=Reason.CREATE_AHEAD, + ), + ) + ) + return MaintenancePlan(table_name="public.events", generated_at=NOW, operations=operations, findings=findings) + + +def _kit(plan: MaintenancePlan) -> MagicMock: + kit = MagicMock() + kit.service.plan = AsyncMock(return_value=plan) + return kit + + +def _configs() -> Sequence[Any]: + return PartitionsDocument.model_validate(DOCUMENT).configs()[:1] + + +# ── Reading the document ──────────────────────────────────────────────────────── + + +def test__load_document__json__is_read_without_pyyaml(tmp_path: Path) -> None: + # Arrange + path = _write(tmp_path, "partitions.json", json.dumps(DOCUMENT)) + + # Act + document = load_document(path) + + # Assert + assert [config.qualified_name for config in document.configs()] == ["public.events", "public.audit"] + + +def test__load_document__yaml__is_read_by_the_safe_loader(tmp_path: Path) -> None: + # Arrange + yaml = pytest.importorskip("yaml") + path = _write(tmp_path, "partitions.yaml", yaml.safe_dump(DOCUMENT)) + + # Act / Assert + assert load_document(path).configs()[0].qualified_name == "public.events" + + +def test__load_document__an_extension_it_does_not_read__says_which_it_does(tmp_path: Path) -> None: + # Arrange + path = _write(tmp_path, "partitions.ini", "[events]\n") + + # Act / Assert + with pytest.raises(ConfigError, match=r"\.json"): + load_document(path) + + +def test__load_document__a_file_that_is_not_there__is_a_configuration_error(tmp_path: Path) -> None: + # Arrange / Act / Assert + with pytest.raises(ConfigError, match="Cannot read"): + load_document(tmp_path / "absent.json") + + +def test__load_document__a_document_that_does_not_validate__names_the_file(tmp_path: Path) -> None: + # Arrange + path = _write(tmp_path, "partitions.json", json.dumps({"tables": [{"table_name": "events", "granulaity": "x"}]})) + + # Act / Assert + with pytest.raises(ConfigError, match=re.escape("partitions.json")): + load_document(path) + + +def test__load_document__a_top_level_that_is_not_a_mapping__is_refused(tmp_path: Path) -> None: + # Arrange + path = _write(tmp_path, "partitions.json", json.dumps([{"table_name": "events"}])) + + # Act / Assert + with pytest.raises(ConfigError, match="not a document"): + load_document(path) + + +# ── Choosing a connection ─────────────────────────────────────────────────────── + + +def test__resolve_dsn__the_flag_outranks_the_environment_and_the_file(monkeypatch: pytest.MonkeyPatch) -> None: + # Arrange + monkeypatch.setenv(DSN_ENV_VAR, "postgresql://env/db") + document = PartitionsDocument.model_validate({**DOCUMENT, "dsn": "postgresql://file/db"}) + + # Act / Assert + assert resolve_dsn(document, override="postgresql://flag/db") == "postgresql://flag/db" + assert resolve_dsn(document) == "postgresql://env/db" + monkeypatch.delenv(DSN_ENV_VAR) + assert resolve_dsn(document) == "postgresql://file/db" + + +def test__resolve_dsn__a_secret_file__is_read_after_the_variable_and_before_the_document( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + # Arrange: the Docker and Swarm secrets convention, a file under /run/secrets + secret = _write(tmp_path, "dsn", "postgresql://secret@host/db\n") + monkeypatch.delenv(DSN_ENV_VAR, raising=False) + monkeypatch.setenv(DSN_FILE_ENV_VAR, str(secret)) + document = PartitionsDocument.model_validate({**DOCUMENT, "dsn": "postgresql://file/db"}) + + # Act / Assert: stripped of its newline, and outranked only by the variable and the flag + assert resolve_dsn(document) == "postgresql://secret@host/db" + monkeypatch.setenv(DSN_ENV_VAR, "postgresql://env/db") + assert resolve_dsn(document) == "postgresql://env/db" + + +def test__resolve_dsn__a_secret_file_that_cannot_be_read__is_a_configuration_error( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + # Arrange + monkeypatch.delenv(DSN_ENV_VAR, raising=False) + monkeypatch.setenv(DSN_FILE_ENV_VAR, str(tmp_path / "absent")) + + # Act / Assert + with pytest.raises(ConfigError, match=DSN_FILE_ENV_VAR): + resolve_dsn(PartitionsDocument.model_validate(DOCUMENT)) + + +def test__resolve_dsn__nowhere_to_connect__says_all_three_places(monkeypatch: pytest.MonkeyPatch) -> None: + # Arrange + monkeypatch.delenv(DSN_ENV_VAR, raising=False) + + # Act / Assert + with pytest.raises(ConfigError, match="--dsn"): + resolve_dsn(PartitionsDocument.model_validate(DOCUMENT)) + + +def test__async_url__a_dsn_naming_no_driver__is_given_the_async_one() -> None: + # Arrange / Act / Assert + assert async_url("postgresql://app@host/db") == "postgresql+asyncpg://app@host/db" + assert async_url("postgres://app@host/db") == "postgresql+asyncpg://app@host/db" + + +def test__async_url__a_dsn_naming_its_driver__is_left_exactly_as_it_is() -> None: + # Whoever wrote +psycopg installed psycopg on purpose. + assert async_url("postgresql+psycopg://app@host/db") == "postgresql+psycopg://app@host/db" + assert async_url("not a url") == "not a url" + + +# ── Narrowing to tables ───────────────────────────────────────────────────────── + + +def test__select_configs__no_table_named__is_every_table_in_document_order() -> None: + # Arrange + document = PartitionsDocument.model_validate(DOCUMENT) + + # Act / Assert + assert [c.table_name for c in select_configs(document, ())] == ["events", "audit"] + + +def test__select_configs__a_bare_name__finds_the_qualified_table() -> None: + # Arrange + document = PartitionsDocument.model_validate(DOCUMENT) + + # Act / Assert + assert [c.qualified_name for c in select_configs(document, ("audit",))] == ["public.audit"] + assert [c.qualified_name for c in select_configs(document, ("public.audit",))] == ["public.audit"] + + +def test__select_configs__a_name_the_document_does_not_have__lists_the_ones_it_does() -> None: + # Arrange + document = PartitionsDocument.model_validate(DOCUMENT) + + # Act / Assert + with pytest.raises(ConfigError, match=re.escape("public.events, public.audit")): + select_configs(document, ("orders",)) + + +# ── Exit codes ────────────────────────────────────────────────────────────────── + + +async def test__plan__a_converged_table__exits_ok_even_under_check() -> None: + # Arrange / Act + result = await run_plan(_kit(_plan(noop=True)), _configs(), check=True) + + # Assert + assert result.code is ExitCode.OK + + +async def test__plan__pending_operations__are_drift_only_when_asked_to_check() -> None: + # Arrange + kit = _kit(_plan()) + + # Act / Assert: a plan is a report by default; --check is what alerts + assert (await run_plan(kit, _configs(), check=False)).code is ExitCode.OK + assert (await run_plan(kit, _configs(), check=True)).code is ExitCode.DRIFT + + +async def test__plan__an_actionable_finding__outranks_drift() -> None: + # Arrange: drift is what a run fixes; a finding is what it cannot. + finding = Finding( + partition_name="public.events__2026_08", + reason=FindingReason.RANGE_OVERLAP, + detail="overlaps a partition that is not this window", + severity=Severity.WARNING, + ) + + # Act + result = await run_plan(_kit(_plan(findings=(finding,))), _configs(), check=True) + + # Assert + assert result.code is ExitCode.FINDINGS + + +async def test__plan__json__is_the_model_dump_under_a_versioned_envelope() -> None: + # Arrange / Act + result = await run_plan(_kit(_plan()), _configs(), check=False) + payload = json.loads(result.render(output="json")) + + # Assert: the vocabulary a configuration file is written in, not one of ours + assert payload["version"] == 1 + assert payload["command"] == "plan" + assert payload["tables"][0]["table"] == "public.events" + assert payload["tables"][0]["plan"]["operations"][0]["kind"] == "create" + + +def _validation(monkeypatch: pytest.MonkeyPatch, *, error: Exception | None = None) -> None: + """Point the command at a validation service that answers as told.""" + service = MagicMock(validate_config=AsyncMock(side_effect=error)) + monkeypatch.setattr("pg_partsmith.cli.commands.PartitionValidationService", MagicMock(return_value=service)) + + +async def test__validate__a_table_the_catalog_disagrees_with__exits_config(monkeypatch: pytest.MonkeyPatch) -> None: + # Arrange + _validation(monkeypatch, error=InvalidPartitionConfigError("Table 'public.events' is not partitioned")) + + # Act + result = await run_validate(MagicMock(), _configs()) + + # Assert + assert result.code is ExitCode.CONFIG + assert json.loads(result.render(output="json"))["tables"][0]["ok"] is False + + +async def test__validate__a_table_the_catalog_agrees_with__exits_ok(monkeypatch: pytest.MonkeyPatch) -> None: + # Arrange + _validation(monkeypatch) + + # Act + result = await run_validate(MagicMock(), _configs()) + + # Assert + assert result.code is ExitCode.OK + assert json.loads(result.render(output="json"))["tables"][0] == { + "table": "public.events", + "ok": True, + "error": None, + } + + +def test__main__a_document_that_is_not_there__exits_config_without_connecting(tmp_path: Path) -> None: + # Arrange / Act / Assert: no DSN is even resolved, so this is 4 and not 5 + assert main(["plan", "-c", str(tmp_path / "absent.yaml")]) == ExitCode.CONFIG + + +def test__main__version__exits_zero(capsys: pytest.CaptureFixture[str]) -> None: + # Act / Assert: one number for the library, the CLI and the image + assert main(["--version"]) == ExitCode.OK + assert __version__ in capsys.readouterr().out + + +def test__main__a_misspelled_flag__is_a_usage_error_and_not_drift(capsys: pytest.CaptureFixture[str]) -> None: + # A CronJob alerting on exit 2 must not page over a typo. + assert main(["plan", "--bogus", "-c", "partitions.yaml"]) == ExitCode.USAGE + assert "--bogus" in capsys.readouterr().err + + +def test__main__no_command__is_a_usage_error_that_shows_the_help(capsys: pytest.CaptureFixture[str]) -> None: + # Arrange / Act + code = main([]) + captured = capsys.readouterr() + + # Assert: the help explains itself; the code says it was not a run + assert code == ExitCode.USAGE + assert "inspect" in captured.out + assert captured.err == "" + + +def test__main__help__exits_zero_and_names_every_command(capsys: pytest.CaptureFixture[str]) -> None: + # Arrange / Act + code = main(["--help"]) + printed = capsys.readouterr().out + + # Assert + assert code == ExitCode.OK + assert all(command in printed for command in ("inspect", "plan", "validate", "apply")) + + +# ── Rendering ─────────────────────────────────────────────────────────────────── + + +def test__envelope__carries_its_own_version_and_the_command_that_made_it() -> None: + # Arrange / Act + payload = envelope("inspect", [{"table": "public.events"}]) + + # Assert + assert payload["version"] == 1 + assert payload["command"] == "inspect" + assert payload["tables"] == [{"table": "public.events"}] + + +def test__plan_entry__names_the_table_beside_the_plan() -> None: + # Arrange / Act + entry = plan_entry(_plan()) + + # Assert + assert entry["table"] == "public.events" + assert entry["plan"]["table_name"] == "public.events" + + +# ── Applying ──────────────────────────────────────────────────────────────────── + + +def _applying_kit(result: MaintenanceResult | None = None) -> MagicMock: + kit = MagicMock() + answer = result if result is not None else MaintenanceResult(created_count=1) + kit.service.apply = AsyncMock(return_value=answer) + kit.service.maintain = AsyncMock(return_value=answer) + return kit + + +def _destructive_plan() -> MaintenancePlan: + return MaintenancePlan( + table_name="public.events", + generated_at=NOW, + operations=( + CreatePartition( + target="public.events__2026_09", + parent_name="public.events", + bounds=RangeBounds(from_value="2026-09-01", to_value="2026-10-01"), + reason=Reason.CREATE_AHEAD, + ), + DropPartition(target="public.events__2025_08", reason=Reason.GRACE_ELAPSED, oid=7), + ), + ) + + +async def test__apply__by_default__withholds_every_destructive_operation() -> None: + # Arrange: the safe mode is the default one, not a second mode to remember + kit = _applying_kit() + + # Act + result = await run_apply(kit, _configs(), plans={"public.events": _destructive_plan()}) + + # Assert + applied = kit.service.apply.await_args.args[1] + assert [op.kind.value for op in applied.operations] == ["create"] + assert "--allow-destructive" in result.render(output="human") + + +async def test__apply__allow_destructive__carries_the_drop_out_too() -> None: + # Arrange + kit = _applying_kit() + + # Act + await run_apply(kit, _configs(), plans={"public.events": _destructive_plan()}, allow_destructive=True) + + # Assert + applied = kit.service.apply.await_args.args[1] + assert [op.kind.value for op in applied.operations] == ["create", "drop"] + + +async def test__apply__without_a_plan_file__plans_and_applies_under_one_lock() -> None: + # Arrange: that is what maintain() is for, and it finalizes a detach that + # was interrupted before deciding the rest of the run. + kit = _applying_kit() + + # Act + await run_apply(kit, _configs()) + + # Assert + kit.service.apply.assert_not_awaited() + assert kit.service.maintain.await_args.kwargs == { + "skip_detach": True, + "skip_drop": True, + "continue_on_error": False, + } + + +async def test__apply__a_plan_file_with_nothing_for_the_table__says_what_it_holds() -> None: + # Arrange / Act / Assert + with pytest.raises(ConfigError, match=re.escape("public.audit")): + await run_apply(_applying_kit(), _configs(), plans={"public.audit": _plan()}) + + +async def test__apply__issues_reported_by_the_run__exit_findings() -> None: + # Arrange + issue = MaintenanceIssue(step=MaintenanceIssueStep.DROP, partition_name="public.events__2025_08", error="refused") + kit = _applying_kit(MaintenanceResult(created_count=1, issues=(issue,))) + + # Act + result = await run_apply(kit, _configs()) + + # Assert + assert result.code is ExitCode.FINDINGS + assert "refused" in result.render(output="human") + + +async def test__apply__json__carries_the_plan_beside_the_result() -> None: + # The result excludes its plan from serialization, so an audit log would + # otherwise get counters with nothing saying what they counted. + kit = _applying_kit() + + # Act + result = await run_apply(kit, _configs(), plans={"public.events": _plan()}) + payload = json.loads(result.render(output="json")) + + # Assert + entry = payload["tables"][0] + assert entry["result"]["created_count"] == 1 + assert entry["plan"]["operations"][0]["kind"] == "create" + + +def test__load_plans__a_file_plan_save_wrote__reads_back_as_the_plan(tmp_path: Path) -> None: + # Arrange + saved = envelope("plan", [plan_entry(_plan())]) + path = tmp_path / "plan.json" + path.write_text(json.dumps(saved), encoding="utf-8") + + # Act + plans = load_plans(path) + + # Assert + assert plans["public.events"] == _plan() + + +def test__load_plans__a_version_this_does_not_read__is_refused(tmp_path: Path) -> None: + # Arrange + saved = {**envelope("plan", [plan_entry(_plan())]), "version": 99} + path = tmp_path / "plan.json" + path.write_text(json.dumps(saved), encoding="utf-8") + + # Act / Assert: half-reading a future format is worse than refusing it + with pytest.raises(ConfigError, match="version 99"): + load_plans(path) + + +def test__load_plans__something_that_is_not_a_saved_plan__is_refused(tmp_path: Path) -> None: + # Arrange + path = tmp_path / "plan.json" + path.write_text(json.dumps({"version": 1, "command": "plan"}), encoding="utf-8") + + # Act / Assert + with pytest.raises(ConfigError, match="no 'tables'"): + load_plans(path) + + +# ── Hooks are code, and run only when asked for ───────────────────────────────── + + +def _hooks_document(tmp_path: Path) -> str: + payload = {**DOCUMENT, "dsn": "postgresql://app@localhost/app", "hooks": {"before_drop": ["/bin/archive"]}} + return str(_write(tmp_path, "partitions.json", json.dumps(payload))) + + +def test__apply__a_document_that_runs_commands__is_refused_unless_asked_for(tmp_path: Path) -> None: + # Arrange: ignoring a configured before_drop silently would be the worst + # outcome available -- an operator reads the file and believes it ran. + config = _hooks_document(tmp_path) + + # Act + code = main(["apply", "-c", config]) + + # Assert: refused as configuration, before any connection is made + assert code == ExitCode.CONFIG + + +def test__plan__a_document_that_runs_commands__needs_no_permission(tmp_path: Path) -> None: + # Hooks fire during apply alone, so planning one is not running one. This + # gets as far as connecting, which is a different failure entirely. + config = _hooks_document(tmp_path) + + # Act / Assert + assert main(["plan", "-c", config]) == ExitCode.CONNECTION + + +def test__hooks__allowed__are_built_from_the_document(tmp_path: Path) -> None: + # Arrange + document = load_document(Path(_hooks_document(tmp_path))) + + # Act + hooks = _cli_hooks(document, command="apply", config=tmp_path / "partitions.json", allow_hooks=True) + + # Assert + assert hooks is not None + assert isinstance(hooks[0], CommandHooks) + assert hooks[0].phases == (HookPhase.BEFORE_DROP,) + + +# ── What a plan will lock ─────────────────────────────────────────────────────── + + +def test__describe_locks__names_the_heaviest_lock_of_every_top_level_operation() -> None: + # Arrange + plan = _destructive_plan() + + # Act + lines = describe_locks(plan).splitlines() + + # Assert: one header line per operation, its lock on the next + assert lines[0] == "locks:" + assert lines[1].startswith(" CREATE public.events__2026_09") + assert "SHARE UPDATE EXCLUSIVE on the parent" in lines[2] + assert lines[3].startswith(" DROP public.events__2025_08") + assert "ACCESS EXCLUSIVE on the dropped table only" in lines[4] + + +def test__describe_locks__an_operation_that_cannot_run_in_a_transaction__says_so() -> None: + # The one a crash leaves half-done, which is worth knowing before a window. + plan = MaintenancePlan( + table_name="public.events", + generated_at=NOW, + operations=( + DetachPartition( + target="public.events__2025_08", + parent_name="public.events", + reason=Reason.RETENTION_EXPIRED, + mode=DetachMode.CONCURRENT, + ), + ), + ) + + # Act / Assert + assert "(outside a transaction block)" in describe_locks(plan).splitlines()[1] + + +def test__describe_locks__a_converged_table__has_nothing_to_lock() -> None: + # Arrange / Act / Assert + assert describe_locks(_plan(noop=True)) == "locks: none, nothing to do" + + +async def test__plan__locks__are_printed_after_the_operations_only_when_asked() -> None: + # Arrange + kit = _kit(_plan()) + + # Act + without = (await run_plan(kit, _configs(), check=False)).render(output="human") + with_locks = (await run_plan(kit, _configs(), check=False, locks=True)).render(output="human") + + # Assert + assert "locks:" not in without + assert "locks:" in with_locks + assert "SHARE UPDATE EXCLUSIVE" in with_locks + + +# ── Python in the document ────────────────────────────────────────────────────── + + +def test__hooks__a_python_block__is_built_alongside_the_commands(tmp_path: Path) -> None: + # Arrange + payload = { + **DOCUMENT, + "dsn": "postgresql://app@localhost/app", + "hooks": {"after_create": ["/bin/notify"], "before_drop": {"python": "log.info('x')"}}, + } + document = load_document(_write(tmp_path, "partitions.json", json.dumps(payload))) + + # Act + hooks = _cli_hooks(document, command="apply", config=tmp_path / "partitions.json", allow_hooks=True) + + # Assert: one object per kind, each knowing its own phases + assert hooks is not None + assert [type(hook).__name__ for hook in hooks] == ["CommandHooks", "PythonHooks"] + + +def test__hooks__a_python_file__is_read_relative_to_the_document(tmp_path: Path) -> None: + # Arrange + (tmp_path / "hooks").mkdir() + (tmp_path / "hooks" / "export.py").write_text("log.info('exporting %s', event.partition.name)", encoding="utf-8") + payload = {**DOCUMENT, "dsn": "x", "hooks": {"before_drop": {"python_file": "hooks/export.py"}}} + document = load_document(_write(tmp_path, "partitions.json", json.dumps(payload))) + + # Act + sources, names = load_python_hooks(document.hooks, tmp_path) # type: ignore[arg-type] + + # Assert + assert sources[HookPhase.BEFORE_DROP].startswith("log.info") + assert names[HookPhase.BEFORE_DROP].endswith("export.py") + + +def test__hooks__a_python_file_that_does_not_parse__fails_validate_by_name(tmp_path: Path) -> None: + # Arrange: validate is the command that should find this, not apply at 03:00 + (tmp_path / "export.py").write_text("def broken(:", encoding="utf-8") + payload = {**DOCUMENT, "dsn": "x", "hooks": {"before_drop": {"python_file": "export.py"}}} + config = _write(tmp_path, "partitions.json", json.dumps(payload)) + + # Act / Assert: refused before any connection is attempted + assert main(["validate", "-c", str(config)]) == ExitCode.CONFIG + + +def test__hooks__a_python_file_that_is_missing__fails_validate_by_name(tmp_path: Path) -> None: + # Arrange + payload = {**DOCUMENT, "dsn": "x", "hooks": {"before_drop": {"python_file": "absent.py"}}} + config = _write(tmp_path, "partitions.json", json.dumps(payload)) + + # Act / Assert + assert main(["validate", "-c", str(config)]) == ExitCode.CONFIG + + +# ── Being stopped ─────────────────────────────────────────────────────────────── + + +class _Recording: + """An engine that remembers being disposed, and is otherwise the real one.""" + + def __init__(self, engine: Any) -> None: + self._engine = engine + self.disposed = False + + def __getattr__(self, name: str) -> Any: + return getattr(self._engine, name) + + async def dispose(self) -> None: + self.disposed = True + await self._engine.dispose() + + +def _stoppable(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, signum: int) -> tuple[str, list[_Recording]]: + """A document that connects nowhere, and a plan that raises ``signum`` mid-run.""" + payload = {**DOCUMENT, "dsn": "postgresql+asyncpg://nobody@127.0.0.1:1/none"} + config = _write(tmp_path, "partitions.json", json.dumps(payload)) + engines: list[_Recording] = [] + + def recording(url: str) -> _Recording: + engine = _Recording(cli.create_async_engine.__wrapped__(url)) # type: ignore[attr-defined] + engines.append(engine) + return engine + + real = cli.create_async_engine + recording.__wrapped__ = real # type: ignore[attr-defined] + monkeypatch.setattr(cli, "create_async_engine", recording) + + async def stopped_mid_run(kit: Any, configs: Any, *, check: bool, locks: bool = False) -> Any: + signal.raise_signal(signum) # what the terminal, or the kubelet, does + await asyncio.sleep(5) # the statement the run was in the middle of + raise AssertionError("never reached") + + monkeypatch.setattr(cli, "run_plan", stopped_mid_run) + return str(config), engines + + +def test__main__ctrl_c_mid_run__cleans_up_and_says_so( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + # Arrange + config, engines = _stoppable(monkeypatch, tmp_path, signal.SIGINT) + + # Act + code = main(["plan", "-c", config]) + + # Assert: 128 + 2, the engine disposed on the way out, one line saying why + assert code == ExitCode.INTERRUPTED + assert engines and engines[0].disposed + assert "interrupted" in capsys.readouterr().err + + +@pytest.mark.skipif(sys.platform == "win32", reason="an event loop takes no signal handlers on Windows") +def test__main__sigterm_mid_run__cleans_up_and_exits_143( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + # Arrange: what a pod is sent at its deadline + config, engines = _stoppable(monkeypatch, tmp_path, signal.SIGTERM) + + # Act + code = main(["plan", "-c", config]) + + # Assert + assert code == ExitCode.TERMINATED + assert engines and engines[0].disposed + assert "terminated" in capsys.readouterr().err + + +def test__main__schema__prints_the_document_schema_and_needs_no_database(capsys: pytest.CaptureFixture[str]) -> None: + # Arrange / Act + code = main(["schema"]) + printed = json.loads(capsys.readouterr().out) + + # Assert: the vocabulary an editor validates against is the model's own + assert code == ExitCode.OK + assert set(printed["properties"]) >= {"tables", "defaults", "runtime", "hooks", "dsn", "version"} + + +# ── The corners of reading files ──────────────────────────────────────────────── + + +def test__load_document__json_that_does_not_parse__names_the_file(tmp_path: Path) -> None: + # Arrange + path = _write(tmp_path, "partitions.json", "{not json") + + # Act / Assert + with pytest.raises(ConfigError, match="not valid JSON"): + load_document(path) + + +def test__load_document__yaml_that_does_not_parse__names_the_file(tmp_path: Path) -> None: + # Arrange + pytest.importorskip("yaml") + path = _write(tmp_path, "partitions.yaml", "tables: [unclosed") + + # Act / Assert + with pytest.raises(ConfigError, match="not valid YAML"): + load_document(path) + + +def test__async_url__a_scheme_that_is_not_postgres__is_left_alone() -> None: + # Arrange / Act / Assert: not ours to rewrite + assert async_url("mysql://app@host/db") == "mysql://app@host/db" + + +def test__load_plans__a_file_that_is_not_there__is_a_configuration_error(tmp_path: Path) -> None: + # Arrange / Act / Assert + with pytest.raises(ConfigError, match="Cannot read"): + load_plans(tmp_path / "absent.json") + + +def test__load_plans__a_file_that_is_not_json__is_a_configuration_error(tmp_path: Path) -> None: + # Arrange + path = _write(tmp_path, "plan.json", "{") + + # Act / Assert + with pytest.raises(ConfigError, match="not valid JSON"): + load_plans(path) + + +def test__load_plans__an_entry_with_no_plan__is_refused(tmp_path: Path) -> None: + # Arrange + path = _write(tmp_path, "plan.json", json.dumps({"version": 1, "tables": [{"table": "public.events"}]})) + + # Act / Assert + with pytest.raises(ConfigError, match="no plan"): + load_plans(path) + + +def test__load_plans__a_plan_this_version_cannot_read__is_refused(tmp_path: Path) -> None: + # Arrange: a plan with an instant no plan could have + saved = {"version": 1, "tables": [{"table": "public.events", "plan": {"table_name": "x", "generated_at": "no"}}]} + path = _write(tmp_path, "plan.json", json.dumps(saved)) + + # Act / Assert + with pytest.raises(ConfigError, match="cannot read"): + load_plans(path) + + +def test__load_plans__a_file_naming_no_table__is_refused(tmp_path: Path) -> None: + # Arrange + path = _write(tmp_path, "plan.json", json.dumps({"version": 1, "tables": []})) + + # Act / Assert + with pytest.raises(ConfigError, match="names no table"): + load_plans(path) + + +def test__as_code__turns_what_the_app_returns_into_an_exit_code() -> None: + # Arrange / Act / Assert: a command's own code, click's 0 for --help, an + # integer that is no code of ours, and nothing at all + assert cli._as_code(ExitCode.DRIFT) is ExitCode.DRIFT + assert cli._as_code(0) is ExitCode.OK + assert cli._as_code(99) is ExitCode.FAILED + assert cli._as_code(None) is ExitCode.OK + + +def test__plan_save__writes_the_envelope_where_apply_can_read_it( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + # Arrange: no database is reached; the plan is handed back by a fake + payload = {**DOCUMENT, "dsn": "postgresql+asyncpg://nobody@127.0.0.1:1/none"} + config = _write(tmp_path, "partitions.json", json.dumps(payload)) + + async def planned(kit: Any, configs: Any, *, check: bool, locks: bool = False) -> Any: + return CommandResult(code=ExitCode.OK, lines=["planned"], payload=envelope("plan", [plan_entry(_plan())])) + + monkeypatch.setattr(cli, "run_plan", planned) + saved = tmp_path / "plan.json" + + # Act + code = main(["plan", "-c", str(config), "--save", str(saved)]) + + # Assert: the file is the artifact, whatever the terminal was shown + assert code == ExitCode.OK + assert load_plans(saved)["public.events"] == _plan() + + +# ── What a shell wrapper used to be for ───────────────────────────────────────── + + +def test__write__puts_the_output_in_a_file_and_nothing_on_stdout( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + # Arrange: a textfile collector reads the file; the log should not get a copy + payload = {**DOCUMENT, "dsn": "postgresql+asyncpg://nobody@127.0.0.1:1/none"} + config = _write(tmp_path, "partitions.json", json.dumps(payload)) + + async def planned(kit: Any, configs: Any, *, check: bool, locks: bool = False) -> Any: + return CommandResult(code=ExitCode.OK, lines=["planned"], payload=envelope("plan", [plan_entry(_plan())])) + + monkeypatch.setattr(cli, "run_plan", planned) + target = tmp_path / "textfile" / "partsmith.prom" + target.parent.mkdir() + + # Act + code = main(["plan", "-c", str(config), "--output", "metrics", "--write", str(target)]) + + # Assert: written whole, under its final name, and no temporary left beside it + assert code == ExitCode.OK + assert "# TYPE pg_partsmith_pending_operations gauge" in target.read_text(encoding="utf-8") + assert capsys.readouterr().out == "" + assert [p.name for p in target.parent.iterdir()] == ["partsmith.prom"] + + +def test__write__a_path_that_cannot_be_written__is_exit_4_and_a_sentence( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + # Arrange: the textfile directory a hostPath names is root's and the + # container is not root; here, the nearest thing on every platform -- a + # directory that is not there at all + payload = {**DOCUMENT, "dsn": "postgresql+asyncpg://nobody@127.0.0.1:1/none"} + config = _write(tmp_path, "partitions.json", json.dumps(payload)) + + async def planned(kit: Any, configs: Any, *, check: bool, locks: bool = False) -> Any: + return CommandResult(code=ExitCode.OK, lines=["planned"], payload=envelope("plan", [plan_entry(_plan())])) + + monkeypatch.setattr(cli, "run_plan", planned) + target = tmp_path / "missing" / "partsmith.prom" + + # Act + code = main(["plan", "-c", str(config), "--output", "metrics", "--write", str(target)]) + + # Assert: the path and the reason, not a traceback, and nothing on stdout + assert code == ExitCode.CONFIG + captured = capsys.readouterr() + assert captured.out == "" + assert captured.err.startswith("pg-partsmith: Cannot write ") + assert "partsmith.prom" in captured.err + assert "Traceback" not in captured.err + + +def test__plan_save__a_path_that_cannot_be_written__is_exit_4_and_a_sentence( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + # Arrange + payload = {**DOCUMENT, "dsn": "postgresql+asyncpg://nobody@127.0.0.1:1/none"} + config = _write(tmp_path, "partitions.json", json.dumps(payload)) + + async def planned(kit: Any, configs: Any, *, check: bool, locks: bool = False) -> Any: + return CommandResult(code=ExitCode.OK, lines=["planned"], payload=envelope("plan", [plan_entry(_plan())])) + + monkeypatch.setattr(cli, "run_plan", planned) + saved = tmp_path / "missing" / "plan.json" + + # Act + code = main(["plan", "-c", str(config), "--save", str(saved)]) + + # Assert: it used to come out as a database error, which it is not + assert code == ExitCode.CONFIG + assert capsys.readouterr().err.startswith("pg-partsmith: Cannot write the plan to ") + + +# ── What the run itself refuses, and what the document refuses first ───────────── + + +def test__apply__a_hook_that_refuses_without_continue_on_error__is_exit_3_and_a_sentence( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + # Arrange: the archiver said no, and the run stopped there, as it should + payload = {**DOCUMENT, "dsn": "postgresql+asyncpg://nobody@127.0.0.1:1/none"} + config = _write(tmp_path, "partitions.json", json.dumps(payload)) + refused = CommandHookError(HookPhase.BEFORE_DROP, "events__2020_01", "exit status 1") + monkeypatch.setattr(cli, "run_apply", AsyncMock(side_effect=refused)) + + # Act + code = main(["apply", "-c", str(config), "--allow-destructive"]) + + # Assert: a finding for a person, the way --continue-on-error would have recorded it + assert code == ExitCode.FINDINGS + assert capsys.readouterr().err == "pg-partsmith: before_drop hook for 'events__2020_01' failed: exit status 1\n" + + +def test__dsn__a_string_that_is_no_url__is_exit_4_before_any_database( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + config = _write(tmp_path, "partitions.json", json.dumps(DOCUMENT)) + + # Act + code = main(["plan", "-c", str(config), "--dsn", "not a connection string"]) + + # Assert: the deployment's mistake, not the database's + assert code == ExitCode.CONFIG + err = capsys.readouterr().err + assert err.startswith("pg-partsmith: the connection string is not usable: ") + assert "Traceback" not in err + + +def test__runtime_boundary_codec__that_nothing_resolves__is_refused_by_validate( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + # Arrange: a typo in the wiring section, which used to surface as a bare ValueError at apply + payload = {**DOCUMENT, "runtime": {"boundary_codec": "uuid7"}} + config = _write(tmp_path, "partitions.json", json.dumps(payload)) + + # Act + code = main(["validate", "-c", str(config), "--dsn", "postgresql://nobody@127.0.0.1:1/none"]) + + # Assert: named where it is written, before any connection + assert code == ExitCode.CONFIG + err = capsys.readouterr().err + assert "boundary_codec" in err + assert "uuid7" in err + + +def test__hooks__an_empty_command__is_refused_where_it_is_written( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + payload = {**DOCUMENT, "hooks": {"before_drop": []}} + config = _write(tmp_path, "partitions.json", json.dumps(payload)) + + # Act + code = main(["validate", "-c", str(config), "--dsn", "postgresql://nobody@127.0.0.1:1/none"]) + + # Assert + assert code == ExitCode.CONFIG + assert "before_drop" in capsys.readouterr().err + + +def test__console_script__without_the_cli_extra__is_a_sentence_and_exit_64( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + # Arrange: typer is what the extra brings; without it the package cannot + # import, and the console script is on PATH all the same + monkeypatch.setitem(sys.modules, "typer", None) + for name in ("pg_partsmith.cli", "pg_partsmith.cli.main"): + monkeypatch.delitem(sys.modules, name, raising=False) + + # Act + code = console.main(["--version"]) + + # Assert + assert code == ExitCode.USAGE + assert capsys.readouterr().err.startswith('pg-partsmith needs the cli extra: pip install "pg-partsmith[cli]"') + + +def test__console_script__with_the_extra__is_the_command_line() -> None: + assert console.main(["--version"]) == ExitCode.OK + + +def test__plan__a_password_the_server_rejects__is_exit_5_and_not_a_traceback( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + # The driver raises its own error for a rejected password, before + # SQLAlchemy has a DBAPI error to wrap it in; it is still the database. + asyncpg = pytest.importorskip("asyncpg") + config = _write(tmp_path, "partitions.json", json.dumps(DOCUMENT)) + rejected = asyncpg.InvalidPasswordError('password authentication failed for user "app"') + monkeypatch.setattr(cli, "run_plan", AsyncMock(side_effect=rejected)) + + # Act / Assert + assert main(["plan", "-c", str(config), "--dsn", "postgresql://app:wrong@localhost/app"]) == ExitCode.CONNECTION + + +def test__ok_if_locked__turns_a_held_lock_into_success(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + # Arrange: an init container restarts on anything non-zero, and ten replicas + # starting at once means nine of them find the lock held + payload = {**DOCUMENT, "dsn": "postgresql+asyncpg://nobody@127.0.0.1:1/none"} + config = _write(tmp_path, "partitions.json", json.dumps(payload)) + + async def locked(kit: Any, configs: Any, **kwargs: Any) -> Any: + raise LockAcquisitionError("public.events", "held by another maintainer") + + monkeypatch.setattr(cli, "run_apply", locked) + + # Act / Assert + assert main(["apply", "-c", str(config)]) == ExitCode.LOCKED + assert main(["apply", "-c", str(config), "--ok-if-locked"]) == ExitCode.OK + + +# ── The console's encoding ────────────────────────────────────────────────────── + + +def test__main__survives_a_console_that_cannot_show_an_em_dash(monkeypatch: pytest.MonkeyPatch) -> None: + """A Windows pipe or a bare POSIX locale may be ASCII, and human output has an em dash in it.""" + # Arrange: an ASCII-only stdout, as strict as a redirected stream is opened + raw = io.BytesIO() + monkeypatch.setattr(sys, "stdout", io.TextIOWrapper(raw, encoding="ascii", errors="strict")) + + # Act + code = main(["--version"]) + sys.stdout.write("events — ok\n") + sys.stdout.flush() + + # Assert + assert code == ExitCode.OK + assert sys.stdout.errors == "backslashreplace" + assert b"events \\u2014 ok" in raw.getvalue() diff --git a/tests/unit/test_cli_render.py b/tests/unit/test_cli_render.py new file mode 100644 index 0000000..23458a5 --- /dev/null +++ b/tests/unit/test_cli_render.py @@ -0,0 +1,159 @@ +"""What ``inspect`` prints: a tree the way a person reads one, and the JSON beside it.""" + +from __future__ import annotations + +from datetime import UTC, datetime +from typing import Any +from unittest.mock import AsyncMock, MagicMock + +from pg_partsmith.cli import ExitCode +from pg_partsmith.cli.commands import CommandResult, run_inspect +from pg_partsmith.cli.render import describe_tree, tree_entry +from pg_partsmith.document import PartitionsDocument +from pg_partsmith.topology import ActualTree, DetachedPartition, PartitionNode, PartitionType, RangeBounds, RelationKind + +ROOT = "public.events" + + +def _tree(*, orphans: bool = True) -> ActualTree: + august = PartitionNode( + name=f"{ROOT}__2026_08", + oid=11, + parent_name=ROOT, + level=1, + bounds=RangeBounds(from_value="2026-08-01", to_value="2026-09-01"), + bounds_expr="FOR VALUES FROM ('2026-08-01') TO ('2026-09-01')", + partition_type=PartitionType.HASH, + partition_columns=("tenant_id",), + children=( + PartitionNode( + name=f"{ROOT}__2026_08__h0", + oid=12, + parent_name=f"{ROOT}__2026_08", + level=2, + bounds_expr="FOR VALUES WITH (modulus 2, remainder 0)", + relkind=RelationKind.FOREIGN, + ), + ), + ) + september = PartitionNode( + name=f"{ROOT}__2026_09", + oid=13, + parent_name=ROOT, + level=1, + bounds_expr="FOR VALUES FROM ('2026-09-01') TO ('2026-10-01')", + detach_pending=True, + has_unaddressable_children=True, + ) + root = PartitionNode( + name=ROOT, + oid=10, + partition_type=PartitionType.RANGE, + partition_columns=("created_at",), + children=(august, september), + ) + detached = ( + ( + DetachedPartition( + name=f"{ROOT}__2026_01", oid=5, parent_name=ROOT, detached_at=datetime(2026, 8, 1, tzinfo=UTC) + ), + DetachedPartition(name=f"{ROOT}__2026_02", oid=6, parent_name=ROOT), + ) + if orphans + else () + ) + return ActualTree(root=root, orphans=detached) + + +def test__describe_tree__indents_by_level_and_shows_the_bound_as_postgresql_spells_it() -> None: + # Act + lines = describe_tree(_tree()).splitlines() + + # Assert: the root names its method; each child its bound, one level deeper + assert lines[0] == f"{ROOT} — partitioned by RANGE (created_at)" + assert lines[1] == " events__2026_08 — FOR VALUES FROM ('2026-08-01') TO ('2026-09-01')" + assert lines[2] == " events__2026_08__h0 — FOR VALUES WITH (modulus 2, remainder 0), foreign" + assert lines[3] == ( + " events__2026_09 — FOR VALUES FROM ('2026-09-01') TO ('2026-10-01'), " + "detach pending, children omitted: unaddressable names" + ) + + +def test__describe_tree__lists_the_orphans_with_when_they_were_detached() -> None: + # Act + printed = describe_tree(_tree()) + + # Assert: one has an instant, the other was marked by an older version + assert "detached, ours to clean up:" in printed + assert f"{ROOT}__2026_01 detached 2026-08-01T00:00:00+00:00" in printed + assert printed.splitlines()[-1] == f" {ROOT}__2026_02" + + +def test__describe_tree__no_orphans__says_nothing_about_cleanup() -> None: + # Act / Assert + assert "detached" not in describe_tree(_tree(orphans=False)) + + +def test__tree_entry__a_table_that_is_not_partitioned__is_null_rather_than_absent() -> None: + # Arrange / Act + entry = tree_entry(ROOT, None) + + # Assert + assert entry == {"table": ROOT, "tree": None} + + +def test__tree_entry__dumps_the_model_in_the_documented_vocabulary() -> None: + # Arrange / Act + entry = tree_entry(ROOT, _tree()) + + # Assert + assert entry["tree"]["root"]["name"] == ROOT + assert entry["tree"]["orphans"][0]["name"] == f"{ROOT}__2026_01" + + +async def test__run_inspect__prints_every_tree_and_exits_ok() -> None: + # Arrange + kit = MagicMock() + kit.service.inspect = AsyncMock(return_value=_tree()) + configs = PartitionsDocument.model_validate( + { + "tables": [ + {"table_name": "events", "schema": "public", "partition_column": "created_at", "granularity": "month"} + ] + } + ).configs() + + # Act + result = await run_inspect(kit, configs) + + # Assert + assert result.code is ExitCode.OK + assert ROOT in result.render(output="human") + assert result.payload is not None and result.payload["command"] == "inspect" + + +async def test__run_inspect__a_table_that_is_not_partitioned__is_a_configuration_error() -> None: + # Arrange: the document describes something that is not there + kit = MagicMock() + kit.service.inspect = AsyncMock(return_value=None) + configs = PartitionsDocument.model_validate( + {"tables": [{"table_name": "events", "partition_column": "created_at", "granularity": "month"}]} + ).configs() + + # Act + result = await run_inspect(kit, configs) + + # Assert + assert result.code is ExitCode.CONFIG + assert "not a partitioned table" in result.render(output="human") + + +def test__command_result__renders_metrics_and_falls_back_to_lines_without_a_payload() -> None: + # Arrange + payload: dict[str, Any] = {"version": 1, "command": "validate", "generated_at": "x", "tables": []} + with_payload = CommandResult(code=ExitCode.OK, lines=["a", "b"], payload=payload) + without = CommandResult(code=ExitCode.OK, lines=["a", "b"]) + + # Act / Assert + assert with_payload.render(output="metrics").startswith("# HELP pg_partsmith_run_timestamp_seconds") + assert without.render(output="json") == "a" + chr(10) + chr(10) + "b" diff --git a/tests/unit/test_command_hooks.py b/tests/unit/test_command_hooks.py new file mode 100644 index 0000000..5899b04 --- /dev/null +++ b/tests/unit/test_command_hooks.py @@ -0,0 +1,307 @@ +"""``CommandHooks``: a lifecycle hook that runs somebody else's program.""" + +from __future__ import annotations + +import asyncio +import json +import logging +import subprocess +import sys +import time +from datetime import UTC, datetime +from pathlib import Path +from typing import Any +from unittest.mock import MagicMock + +import pytest + +from pg_partsmith.aio.command_hooks import CommandHookError, CommandHooks +from pg_partsmith.boundaries import Window +from pg_partsmith.entities import PartitionGranularity, PartitionInfo, TablePartitionConfig +from pg_partsmith.events import HookPhase, PartitionEvent, hook_environment +from pg_partsmith.hook_commands import finish_hook_command, stop_hook_command +from pg_partsmith.plan import DropPartition, Reason +from pg_partsmith.sync.command_hooks import CommandHooks as SyncCommandHooks +from pg_partsmith.topology import RangeBounds + +CONFIG = TablePartitionConfig( + schema="public", + table_name="events", + partition_column="created_at", + granularity=PartitionGranularity.MONTH, +) + + +def _event(phase: HookPhase = HookPhase.BEFORE_DROP) -> PartitionEvent: + info = PartitionInfo( + name="events__2025_08", + schema_name="public", + partition_type="range", + is_attached=False, + bounds=RangeBounds(from_value="2025-08-01", to_value="2025-09-01"), + ) + operation = DropPartition(target="public.events__2025_08", reason=Reason.GRACE_ELAPSED, oid=42) + return PartitionEvent.build(phase, CONFIG, info, operation) + + +def _script(body: str) -> list[str]: + """A command that is a Python one-liner, so the test runs anywhere pytest does.""" + return [sys.executable, "-c", body] + + +READ_STDIN = "import sys, json; d = json.load(sys.stdin); open(sys.argv[1] if len(sys.argv) > 1 else 'x', 'w')" + + +async def test__on_event__the_phase_it_was_configured_for__runs_the_command(tmp_path: Path) -> None: + # Arrange + marker = tmp_path / "ran.json" + body = f"import sys, pathlib; pathlib.Path({str(marker)!r}).write_text(sys.stdin.read(), encoding='utf-8')" + hooks = CommandHooks({HookPhase.BEFORE_DROP: _script(body)}) + + # Act + await hooks.on_event(_event()) + + # Assert: the whole event, in the vocabulary a document is written in + payload: dict[str, Any] = json.loads(marker.read_text(encoding="utf-8")) + assert payload["phase"] == "before_drop" + assert payload["partition"]["name"] == "events__2025_08" + assert payload["operation"]["kind"] == "drop" + assert payload["operation"]["reason"] == "grace_elapsed" + assert payload["window"]["start"].startswith("2025-08-01") + + +async def test__on_event__another_phase__runs_nothing(tmp_path: Path) -> None: + # Arrange + marker = tmp_path / "ran" + body = f"import pathlib; pathlib.Path({str(marker)!r}).write_text('ran', encoding='utf-8')" + hooks = CommandHooks({HookPhase.BEFORE_DROP: _script(body)}) + + # Act + await hooks.on_event(_event(HookPhase.AFTER_CREATE)) + + # Assert + assert not marker.exists() + + +async def test__on_event__a_command_that_refuses__aborts_the_operation() -> None: + # Arrange: a non-zero exit is a refusal, exactly as a raised exception is + hooks = CommandHooks({HookPhase.BEFORE_DROP: _script("import sys; sys.stderr.write('still needed'); sys.exit(3)")}) + + # Act / Assert + with pytest.raises(CommandHookError, match="still needed") as exc: + await hooks.on_event(_event()) + assert exc.value.phase is HookPhase.BEFORE_DROP + assert exc.value.partition_name == "events__2025_08" + + +async def test__on_event__a_command_that_hangs__is_killed_and_the_operation_abandoned() -> None: + # A hook that never returns holds the table's maintenance lock, so there is + # no "wait forever" option. + hooks = CommandHooks({HookPhase.BEFORE_DROP: _script("import time; time.sleep(30)")}, timeout_seconds=0.5) + + # Act / Assert + with pytest.raises(CommandHookError, match="did not finish"): + await hooks.on_event(_event()) + + +async def test__on_event__a_command_that_is_not_there__says_so_by_name() -> None: + # Arrange + hooks = CommandHooks({HookPhase.BEFORE_DROP: ["/nonexistent/archive-partition"]}) + + # Act / Assert + with pytest.raises(CommandHookError, match="archive-partition"): + await hooks.on_event(_event()) + + +async def test__on_event__the_environment__names_the_phase_the_table_and_the_partition(tmp_path: Path) -> None: + # Arrange: the three facts a shell script reaches for, without parsing JSON + marker = tmp_path / "env.json" + body = ( + "import os, json, pathlib; " + f"pathlib.Path({str(marker)!r}).write_text(json.dumps(" + "{k: v for k, v in os.environ.items() if k.startswith('PG_PARTSMITH_')}), encoding='utf-8')" + ) + hooks = CommandHooks({HookPhase.BEFORE_DROP: _script(body)}) + + # Act + await hooks.on_event(_event()) + + # Assert + environment = json.loads(marker.read_text(encoding="utf-8")) + assert environment["PG_PARTSMITH_PHASE"] == "before_drop" + assert environment["PG_PARTSMITH_TABLE"] == "public.events" + assert environment["PG_PARTSMITH_PARTITION"] == "events__2025_08" + assert environment["PG_PARTSMITH_WINDOW_START"].startswith("2025-08-01") + + +def test__command_hooks__an_empty_command__is_refused() -> None: + # Arrange / Act / Assert + with pytest.raises(ValueError, match="before_drop"): + CommandHooks({HookPhase.BEFORE_DROP: []}) + + +def test__command_hooks__implements_every_phase_method_the_executor_calls() -> None: + # The executor calls the method named for the phase after on_event, so a + # hook missing one would abort the operation with an AttributeError. + hooks = CommandHooks({HookPhase.BEFORE_DROP: ["/bin/true"]}) + + # Act / Assert + assert all(callable(getattr(hooks, phase.value, None)) for phase in HookPhase) + assert hooks.phases == (HookPhase.BEFORE_DROP,) + + +def test__sync_command_hooks__runs_the_same_way(tmp_path: Path) -> None: + # Arrange: the mirrors differ in how they wait, not in what they do + marker = tmp_path / "ran.json" + body = f"import sys, pathlib; pathlib.Path({str(marker)!r}).write_text(sys.stdin.read(), encoding='utf-8')" + hooks = SyncCommandHooks({HookPhase.BEFORE_DROP: _script(body)}) + + # Act + hooks.on_event(_event()) + + # Assert + assert json.loads(marker.read_text(encoding="utf-8"))["phase"] == "before_drop" + + +def test__sync_command_hooks__a_command_that_refuses__aborts_the_operation() -> None: + # Arrange + hooks = SyncCommandHooks({HookPhase.BEFORE_DROP: _script("import sys; sys.exit(2)")}) + + # Act / Assert + with pytest.raises(CommandHookError, match="exited 2"): + hooks.on_event(_event()) + + +def test__hook_event__is_built_at_the_moment_the_test_says_it_is() -> None: + # Guards the fixture rather than the code: a stale clock here would make + # the window assertions above pass for the wrong reason. + assert datetime.now(UTC).year >= 2024 + + +async def test__on_event__cancelled_while_the_command_runs__stops_the_child_and_returns_promptly() -> None: + # A run being stopped -- Ctrl+C, a pod's SIGTERM -- must not wait out a + # five-minute archiver, and must not leave it running unwatched either. + hooks = CommandHooks({HookPhase.BEFORE_DROP: _script("import time; time.sleep(60)")}, timeout_seconds=60) + task = asyncio.create_task(hooks.on_event(_event())) + await asyncio.sleep(0.5) + + # Act + started = time.monotonic() + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + + # Assert: seconds, not the minute the child had left + assert time.monotonic() - started < 15 + + +def test__stop_hook_command__a_child_that_ignores_nothing__is_terminated_then_gone() -> None: + # Arrange + process = subprocess.Popen(_script("import time; time.sleep(60)"), stdin=subprocess.PIPE) # noqa: S603 + + # Act + stop_hook_command(process, grace_seconds=5) + + # Assert + assert process.poll() is not None + + +def test__stop_hook_command__a_child_already_gone__is_left_alone() -> None: + # Arrange + process = subprocess.Popen(_script("pass")) # noqa: S603 + process.wait() + + # Act / Assert: nothing to do, and nothing raised + stop_hook_command(process) + assert process.returncode == 0 + + +def test__command_hooks__a_phase_that_is_not_one__is_refused() -> None: + # Arrange / Act / Assert + with pytest.raises(ValueError, match="not a hook phase"): + CommandHooks({"before_lunch": ["/bin/true"]}) # type: ignore[dict-item] + + +async def test__on_event__what_the_command_prints__is_logged(caplog: pytest.LogCaptureFixture) -> None: + # Arrange + hooks = CommandHooks({HookPhase.BEFORE_DROP: _script("print('archived 4096 bytes')")}) + + # Act + with caplog.at_level(logging.INFO, logger="pg_partsmith.aio.command_hooks"): + await hooks.on_event(_event()) + + # Assert + assert "archived 4096 bytes" in caplog.text + + +def test__sync_command_hooks__the_same_refusals_and_the_same_phases() -> None: + # Arrange / Act / Assert + with pytest.raises(ValueError, match="not a hook phase"): + SyncCommandHooks({"before_lunch": ["/bin/true"]}) # type: ignore[dict-item] + with pytest.raises(ValueError, match="non-empty"): + SyncCommandHooks({HookPhase.BEFORE_DROP: []}) + assert SyncCommandHooks({HookPhase.AFTER_CREATE: ["/bin/true"]}).phases == (HookPhase.AFTER_CREATE,) + + +def test__sync_command_hooks__another_phase__runs_nothing(tmp_path: Path) -> None: + # Arrange + marker = tmp_path / "ran" + body = f"import pathlib; pathlib.Path({str(marker)!r}).write_text('x')" + hooks = SyncCommandHooks({HookPhase.BEFORE_DROP: _script(body)}) + + # Act + hooks.on_event(_event(HookPhase.AFTER_CREATE)) + + # Assert + assert not marker.exists() + + +def test__sync_command_hooks__what_the_command_prints__is_logged(caplog: pytest.LogCaptureFixture) -> None: + # Arrange + hooks = SyncCommandHooks({HookPhase.BEFORE_DROP: _script("print('archived')")}) + + # Act + with caplog.at_level(logging.INFO, logger="pg_partsmith.sync.command_hooks"): + hooks.on_event(_event()) + + # Assert + assert "archived" in caplog.text + + +def test__finish_hook_command__interrupted_while_waiting__stops_the_child_and_re_raises() -> None: + # Arrange: what Ctrl+C in the sync mirror looks like from inside the wait + process = MagicMock() + process.args = ["archive"] + process.communicate.side_effect = KeyboardInterrupt + process.poll.return_value = None + + # Act / Assert + with pytest.raises(KeyboardInterrupt): + finish_hook_command(process, b"{}", phase=HookPhase.BEFORE_DROP, partition_name="p", timeout_seconds=5) + process.terminate.assert_called_once() + + +@pytest.mark.skipif(sys.platform == "win32", reason="terminate and kill are the same signal on Windows") +def test__stop_hook_command__a_child_that_ignores_terminate__is_killed_after_the_grace() -> None: + # Arrange: a child that shrugs off SIGTERM + body = "import signal, time; signal.signal(signal.SIGTERM, signal.SIG_IGN); time.sleep(60)" + process = subprocess.Popen(_script(body)) # noqa: S603 + time.sleep(0.5) + + # Act + stop_hook_command(process, grace_seconds=0.5) + + # Assert + assert process.poll() is not None + + +def test__hook_environment__an_integer_axis__hands_the_window_over_as_numbers() -> None: + # Arrange: a table partitioned on a sequence, whose window edges are ids, not moments + event = _event().model_copy(update={"window": Window(start=1000, end=2000)}) + + # Act + environment = hook_environment(event) + + # Assert + assert environment["PG_PARTSMITH_WINDOW_START"] == "1000" + assert environment["PG_PARTSMITH_WINDOW_END"] == "2000" diff --git a/tests/unit/test_document.py b/tests/unit/test_document.py new file mode 100644 index 0000000..ec8772d --- /dev/null +++ b/tests/unit/test_document.py @@ -0,0 +1,293 @@ +"""The document: several tables, shared defaults, and the wiring they run through.""" + +from __future__ import annotations + +import re +from typing import Any + +import pytest +from pydantic import ValidationError + +from pg_partsmith.boundaries import UUIDv7BoundaryCodec +from pg_partsmith.document import PartitionsDocument, PartitionTableSpec, ToolkitOptions +from pg_partsmith.entities import PartitionGranularity +from pg_partsmith.events import HookPhase + + +def _document(**overrides: Any) -> dict[str, Any]: + document: dict[str, Any] = { + "tables": [ + {"table_name": "events", "partition_column": "created_at", "granularity": "month"}, + {"table_name": "audit", "partition_column": "logged_at", "granularity": "day"}, + ] + } + document.update(overrides) + return document + + +# ── Tables ────────────────────────────────────────────────────────────────────── + + +def test__document__tables__become_configurations_in_document_order() -> None: + # Arrange / Act + document = PartitionsDocument.model_validate(_document()) + + # Assert + assert [config.table_name for config in document.configs()] == ["events", "audit"] + assert document.configs()[1].granularity is PartitionGranularity.DAY + + +def test__document__no_tables__is_refused() -> None: + # A document maintaining nothing is a configuration error, not a no-op run. + with pytest.raises(ValidationError): + PartitionsDocument.model_validate({"tables": []}) + + +def test__document__one_relation_described_twice__is_refused() -> None: + # Arrange: two entries, one relation -- maintained under two policies, in an + # order nothing in the file makes visible. + payload = _document( + tables=[ + {"table_name": "events", "partition_column": "created_at", "granularity": "month", "schema": "public"}, + {"table_name": "events", "partition_column": "created_at", "granularity": "day", "schema": "public"}, + ] + ) + + # Act / Assert + with pytest.raises(ValidationError, match="described twice"): + PartitionsDocument.model_validate(payload) + + +def test__document__config_for__finds_a_table_by_the_name_postgresql_knows_it_as() -> None: + # Arrange + document = PartitionsDocument.model_validate(_document(defaults={"schema": "public"})) + + # Act / Assert + assert document.config_for("public.audit").partition_column == "logged_at" + with pytest.raises(KeyError, match=re.escape("public.events, public.audit")): + document.config_for("public.missing") + + +# ── Defaults ──────────────────────────────────────────────────────────────────── + + +def test__defaults__are_the_starting_point_of_every_table() -> None: + # Arrange / Act + document = PartitionsDocument.model_validate(_document(defaults={"schema": "analytics", "retention_count": 6})) + + # Assert + assert [config.schema_name for config in document.configs()] == ["analytics", "analytics"] + assert all(config.lifecycle.retention.count == 6 for config in document.configs()) + + +def test__defaults__a_table_naming_the_key__owns_it() -> None: + # Arrange / Act + document = PartitionsDocument.model_validate( + _document( + defaults={"retention_count": 6}, + tables=[ + {"table_name": "events", "partition_column": "created_at", "granularity": "month"}, + { + "table_name": "audit", + "partition_column": "logged_at", + "granularity": "day", + "retention_count": 400, + }, + ], + ) + ) + + # Assert + assert [config.lifecycle.retention.count for config in document.configs()] == [6, 400] + + +def test__defaults__a_field_no_table_has__is_refused_where_it_is_written() -> None: + # A typo in defaults would otherwise reach every table at once, or nothing. + with pytest.raises(ValidationError, match="granuality"): + PartitionsDocument.model_validate(_document(defaults={"granuality": "month"})) + + +def test__table__an_unknown_key__is_refused() -> None: + # Arrange / Act / Assert + with pytest.raises(ValidationError): + PartitionTableSpec.model_validate({"table_name": "events", "retenton_count": 3}) + + +def test__table__schema__is_accepted_as_the_configuration_spells_it() -> None: + # Arrange / Act + spec = PartitionTableSpec.model_validate( + {"table_name": "events", "schema": "public", "partition_column": "created_at", "granularity": "month"} + ) + + # Assert + assert spec.schema_name == "public" + assert spec.to_config().qualified_name == "public.events" + + +def test__document__version__is_the_one_this_release_reads() -> None: + # Arrange / Act / Assert + assert PartitionsDocument.model_validate(_document()).version == 1 + with pytest.raises(ValidationError): + PartitionsDocument.model_validate(_document(version=2)) + + +# ── Runtime ───────────────────────────────────────────────────────────────────── + + +def test__runtime__omitted__is_the_library_default_wiring() -> None: + # Arrange / Act + document = PartitionsDocument.model_validate(_document()) + + # Assert + assert document.runtime == ToolkitOptions() + assert document.runtime.ddl_timezone == "UTC" + + +def test__to_kwargs__names_the_keywords_from_engine_takes__with_the_codec_resolved() -> None: + # Arrange + options = ToolkitOptions(boundary_codec="uuidv7", ddl_timezone="Europe/Berlin", marker_prefix="acme") + + # Act + kwargs = options.to_kwargs() + + # Assert + assert isinstance(kwargs["boundary_codec"], UUIDv7BoundaryCodec) + assert kwargs["ddl_timezone"] == "Europe/Berlin" + assert kwargs["marker_prefix"] == "acme" + + +def test__to_kwargs__an_unknown_codec_name__is_refused_by_name() -> None: + # Arrange / Act / Assert + with pytest.raises(ValueError, match="uuidv8"): + ToolkitOptions(boundary_codec="uuidv8").to_kwargs() + + +def test__runtime__an_unknown_key__is_refused() -> None: + # Arrange / Act / Assert + with pytest.raises(ValidationError): + PartitionsDocument.model_validate(_document(runtime={"ddl_timezome": "UTC"})) + + +def test__document__round_trips_through_its_own_dump() -> None: + # Arrange: what a `validate` command reads is what an operator wrote + document = PartitionsDocument.model_validate( + _document(defaults={"schema": "public"}, dsn="postgresql://app@localhost/app", runtime={"marker_prefix": "x"}) + ) + + # Act / Assert + assert PartitionsDocument.model_validate_json(document.model_dump_json(by_alias=True)) == document + + +# ── Hooks ─────────────────────────────────────────────────────────────────────── + + +def test__hooks__commands__come_back_in_lifecycle_order() -> None: + # Arrange / Act + document = PartitionsDocument.model_validate( + _document(hooks={"after_create": ["/bin/notify"], "before_drop": ["/bin/archive", "--to", "s3"]}) + ) + + # Assert: declaration order in the file does not decide when they run + assert document.hooks is not None + assert [phase.value for phase in document.hooks.commands()] == ["after_create", "before_drop"] + assert document.hooks.commands()[HookPhase.BEFORE_DROP] == ("/bin/archive", "--to", "s3") + + +def test__hooks__a_misspelled_phase__is_refused_where_it_is_written() -> None: + # Silently never running the command that exports data before a DROP is the + # difference between an archive and no archive. + with pytest.raises(ValidationError): + PartitionsDocument.model_validate(_document(hooks={"befor_drop": ["/bin/archive"]})) + + +def test__hooks__omitted__is_no_hooks_at_all() -> None: + # Arrange / Act + document = PartitionsDocument.model_validate(_document()) + + # Assert + assert document.hooks is None + + +def test__hooks__a_section_naming_no_command__knows_it_is_empty() -> None: + # Arrange / Act + document = PartitionsDocument.model_validate(_document(hooks={"timeout_seconds": 30})) + + # Assert + assert document.hooks is not None + assert document.hooks.is_empty + assert document.hooks.timeout_seconds == 30 + + +def test__hooks__a_block_of_python__is_compiled_where_it_is_written() -> None: + # Arrange / Act + document = PartitionsDocument.model_validate( + _document(hooks={"before_drop": {"python": "log.info('dropping %s', event.partition.name)"}}) + ) + + # Assert + assert document.hooks is not None + assert document.hooks.commands() == {} + assert [phase.value for phase in document.hooks.python_blocks()] == ["before_drop"] + assert not document.hooks.is_empty + + +def test__hooks__a_block_that_does_not_parse__is_a_validation_error_with_a_line_number() -> None: + # A SyntaxError found at 03:00 by a CronJob is the failure mode to design out. + broken = "if event.partition.name\n pass" + with pytest.raises(ValidationError, match="line 1"): + PartitionsDocument.model_validate(_document(hooks={"before_drop": {"python": broken}})) + + +def test__hooks__a_block_naming_both_a_source_and_a_file__is_refused() -> None: + # Arrange / Act / Assert + with pytest.raises(ValidationError, match="not both"): + PartitionsDocument.model_validate( + _document(hooks={"before_drop": {"python": "pass", "python_file": "hooks/export.py"}}) + ) + + +def test__hooks__a_file_reference__is_kept_for_the_reader_to_resolve() -> None: + # Only the reader knows where the document lives, so the path stays a path. + document = PartitionsDocument.model_validate(_document(hooks={"before_drop": {"python_file": "hooks/export.py"}})) + + # Assert + assert document.hooks is not None + block = document.hooks.python_blocks()[HookPhase.BEFORE_DROP] + assert block.python is None + assert block.python_file == "hooks/export.py" + + +def test__hooks__commands_and_blocks__mix_across_phases() -> None: + # Arrange / Act + document = PartitionsDocument.model_validate( + _document(hooks={"after_create": ["/bin/notify"], "before_drop": {"python": "pass"}}) + ) + + # Assert + assert document.hooks is not None + assert list(document.hooks.commands()) == [HookPhase.AFTER_CREATE] + assert list(document.hooks.python_blocks()) == [HookPhase.BEFORE_DROP] + + +def test__hooks__an_empty_python_block__is_refused() -> None: + # Arrange / Act / Assert + with pytest.raises(ValidationError, match="empty"): + PartitionsDocument.model_validate(_document(hooks={"before_drop": {"python": " "}})) + + +def test__defaults__that_are_not_a_mapping__are_refused_by_the_field() -> None: + # Arrange / Act / Assert: the merge steps aside and the field's own validation speaks + with pytest.raises(ValidationError): + PartitionsDocument.model_validate(_document(defaults="month")) + + +def test__tables__that_are_not_a_list__are_refused_by_the_field() -> None: + # Arrange / Act / Assert + with pytest.raises(ValidationError): + PartitionsDocument.model_validate({"defaults": {"schema": "public"}, "tables": {"table_name": "events"}}) + + +def test__document__something_that_is_not_a_mapping_at_all__is_refused() -> None: + # Arrange / Act / Assert: the defaults merge steps aside; validation says what it is + with pytest.raises(ValidationError): + PartitionsDocument.model_validate("tables: events") diff --git a/tests/unit/test_entities.py b/tests/unit/test_entities.py index a90a9fb..5316e40 100644 --- a/tests/unit/test_entities.py +++ b/tests/unit/test_entities.py @@ -998,3 +998,22 @@ def test__config__misspelled_field__refused_not_ignored() -> None: granularity=PartitionGranularity.MONTH, retention_cout=12, # type: ignore[call-arg] ) + + +def test__fingerprint__is_stable_across_a_round_trip_and_moves_with_the_policy() -> None: + # Arrange + config = TablePartitionConfig( + schema="public", + table_name="events", + partition_column="created_at", + granularity=PartitionGranularity.MONTH, + retention_count=12, + ) + read_back = TablePartitionConfig.model_validate_json(config.model_dump_json(by_alias=True)) + edited = config.model_copy( + update={"lifecycle": config.lifecycle.model_copy(update={"retention": KeepNewest(count=3)})} + ) + + # Assert: a plan can be told what it was planned under, and told when that changed + assert read_back.fingerprint == config.fingerprint + assert edited.fingerprint != config.fingerprint diff --git a/tests/unit/test_examples.py b/tests/unit/test_examples.py new file mode 100644 index 0000000..00f3689 --- /dev/null +++ b/tests/unit/test_examples.py @@ -0,0 +1,89 @@ +"""The shipped examples: every document validates, every hook compiles, the schema is current.""" + +from __future__ import annotations + +import json +import shutil +import subprocess +from pathlib import Path + +import pydantic +import pytest + +from pg_partsmith.cli.loader import load_document, load_python_hooks +from pg_partsmith.document import PartitionsDocument +from pg_partsmith.events import HookPhase + +EXAMPLES = Path(__file__).resolve().parents[2] / "examples" +DOCUMENTS = sorted(EXAMPLES.glob("partitions*.yaml")) +SCRIPTS = sorted((EXAMPLES / "hooks").glob("*.sh")) + + +@pytest.mark.parametrize("path", DOCUMENTS, ids=lambda p: p.name) +def test__example_document__validates_and_names_every_table(path: Path) -> None: + # An example that does not validate teaches the wrong vocabulary. + document = load_document(path) + + # Assert: every entry becomes a configuration, and none is repeated + names = [config.qualified_name for config in document.configs()] + assert names + assert len(names) == len(set(names)) + + +def test__the_full_example__spells_every_kind_of_thing_a_document_can_hold() -> None: + # Arrange: the one people copy from + document = load_document(EXAMPLES / "partitions.yaml") + configs = {config.table_name: config for config in document.configs()} + + # Assert: a flat table, a nested scheme, a LIST root, leaves, runtime and hooks + assert configs["events"].granularity is not None + assert configs["telemetry"].scheme.child is not None + assert configs["shipments"].scheme.method_name == "list" + assert configs["telemetry"].leaves.kind == "local" + assert document.runtime.marker_prefix == "acme" + assert document.hooks is not None + assert set(document.hooks.commands()) == {HookPhase.BEFORE_DROP, HookPhase.AFTER_CREATE} + assert set(document.hooks.python_blocks()) == {HookPhase.BEFORE_DETACH, HookPhase.AFTER_DROP} + + +def test__example_python_hook__compiles_from_the_file_the_document_names() -> None: + # Arrange: resolved relative to the document, exactly as the CLI does it + document = load_document(EXAMPLES / "partitions.yaml") + assert document.hooks is not None + + # Act + sources, names = load_python_hooks(document.hooks, EXAMPLES) + + # Assert: the file compiled, the inline block compiled, both are named + assert HookPhase.BEFORE_DETACH in sources + assert names[HookPhase.BEFORE_DETACH].endswith("export_partition.py") + assert HookPhase.AFTER_DROP in sources + + +@pytest.mark.parametrize("script", SCRIPTS, ids=lambda p: p.name) +def test__example_shell_hook__parses_and_is_executable(script: Path) -> None: + # Arrange / Assert: a shebang and the executable bit, so a COPY into an + # image is all it takes + assert script.read_text(encoding="utf-8").startswith("#!/usr/bin/env bash") + bash = shutil.which("bash") + if bash is None: + pytest.skip("bash is not on PATH") + + # Act: a syntax check, no execution + completed = subprocess.run([bash, "-n", str(script)], capture_output=True, text=True, check=False) # noqa: S603 + + # Assert + assert completed.returncode == 0, completed.stderr + + +@pytest.mark.skipif( + tuple(int(part) for part in pydantic.VERSION.split(".")[:2]) < (2, 11), + reason="the file is rendered by the pydantic in the lock; releases before 2.11 render the same schema differently", +) +def test__the_committed_schema__is_the_one_the_document_generates() -> None: + # A stale schema file would validate the wrong vocabulary in an editor, + # which is worse than none; `pg-partsmith schema` regenerates it. + committed = json.loads((EXAMPLES / "partitions.schema.json").read_text(encoding="utf-8")) + + # Assert + assert committed == PartitionsDocument.model_json_schema() diff --git a/tests/unit/test_execution.py b/tests/unit/test_execution.py index 7bf9e24..ddb4eff 100644 --- a/tests/unit/test_execution.py +++ b/tests/unit/test_execution.py @@ -34,6 +34,7 @@ PartitionError, PartitionReferencedError, PartitionTopologyError, + PlanConfigMismatchError, PlanStaleError, RowMoveRefusedError, ) @@ -170,8 +171,8 @@ def _hash_root_config() -> TablePartitionConfig: ) -def _plan(*operations: Operation, findings: tuple[Finding, ...] = ()) -> MaintenancePlan: - return MaintenancePlan(table_name="events", generated_at=NOW, operations=tuple(operations), findings=findings) +def _plan(*operations: Operation, findings: tuple[Finding, ...] = (), table_name: str = "events") -> MaintenancePlan: + return MaintenancePlan(table_name=table_name, generated_at=NOW, operations=tuple(operations), findings=findings) def _create_op( @@ -1863,7 +1864,8 @@ async def test__apply__plain_local_leaves__create_is_spelled_as_it_always_was( ) -> None: # Arrange / Act await executor.apply( - _leaves_config(LocalLeaves()), _plan(_create_op("public.events__2024_04", parent="public.events")) + _leaves_config(LocalLeaves()), + _plan(_create_op("public.events__2024_04", parent="public.events"), table_name="public.events"), ) # Assert @@ -1878,7 +1880,7 @@ async def test__apply__customised_local_leaves__physical_spec_reaches_the_reposi leaves = LocalLeaves(tablespace="fast", storage_parameters={"fillfactor": 70}) # Act - await executor.apply(_leaves_config(leaves), _plan(_create_op())) + await executor.apply(_leaves_config(leaves), _plan(_create_op(), table_name="public.events")) # Assert repo.create_table_like.assert_awaited_once_with("events", "events__2024_04", None, physical=leaves) @@ -1892,7 +1894,7 @@ async def test__apply__foreign_leaves__leaf_is_a_foreign_table_with_rendered_opt op = _create_op("public.events__2024_04", parent="public.events") # Act - result = await executor.apply(_leaves_config(leaves), _plan(op)) + result = await executor.apply(_leaves_config(leaves), _plan(op, table_name="public.events")) # Assert repo.create_foreign_table_like.assert_awaited_once_with( @@ -1915,7 +1917,7 @@ async def test__apply__foreign_leaves__branch_stays_local_and_its_buckets_are_fo leaves = ForeignLeaves(server="archive", options={"table_name": "{parent}_{relname}"}) # Act - await executor.apply(_leaves_config(leaves, nested=True), _plan(_branch_op())) + await executor.apply(_leaves_config(leaves, nested=True), _plan(_branch_op(), table_name="public.events")) # Assert repo.create_table_like.assert_awaited_once_with("events", "events__2024_04", _branch_op().partition_by) @@ -2181,3 +2183,16 @@ async def test__attach_partition__branch_orphan__its_children_carry_the_planned_ bucket = repo.attach_partition.call_args_list[0] assert bucket.args[0] == "events__2024_04" assert bucket.kwargs["expected_parent_oid"] == 77 + + +async def test__apply__a_plan_made_for_another_table__is_refused_before_any_ddl( + executor: PlanExecutor, repo: MagicMock +) -> None: + # Arrange: the plan names relations that exist, under a configuration that + # describes a different table -- reachable once a plan is an artifact. + plan = _plan(_create_op(), table_name="public.audit") + + # Act / Assert + with pytest.raises(PlanConfigMismatchError): + await executor.apply(_config(), plan) + repo.create_table_like.assert_not_awaited() diff --git a/tests/unit/test_guides.py b/tests/unit/test_guides.py new file mode 100644 index 0000000..11489f9 --- /dev/null +++ b/tests/unit/test_guides.py @@ -0,0 +1,94 @@ +"""The guides' YAML blocks: they parse, and what they hand the command is something it takes. + +A manifest in the running guide is what a team pastes into a cluster, and a +flag renamed in the CLI would leave it wrong with nothing to say so. Every +``args`` or ``command`` list that starts with one of the commands is checked +against the options that command actually declares. +""" + +from __future__ import annotations + +import re +from pathlib import Path +from typing import TYPE_CHECKING, Any + +import pytest +import typer +import yaml + +from pg_partsmith.cli.main import app +from scripts.k8s_manifests import manifests + +if TYPE_CHECKING: + from collections.abc import Iterator + +pytestmark = pytest.mark.unit + +GUIDES = sorted((Path(__file__).resolve().parents[2] / "docs" / "guide").glob("*.md")) +FENCE = re.compile(r"^```yaml\n(.*?)^```\n", re.MULTILINE | re.DOTALL) +GROUP = typer.main.get_command(app) +GROUP_OPTIONS = {option for parameter in GROUP.params for option in parameter.opts} +COMMAND_OPTIONS = { + name: GROUP_OPTIONS | {option for parameter in command.params for option in parameter.opts} + for name, command in GROUP.commands.items() +} + + +def _blocks() -> Iterator[Any]: + for guide in GUIDES: + for index, block in enumerate(FENCE.findall(guide.read_text(encoding="utf-8")), start=1): + yield pytest.param(guide.name, block, id=f"{guide.name}:{index}") + + +def _invocations(node: Any) -> Iterator[list[str]]: + """Every ``args`` / ``command`` list in ``node`` that begins with one of the commands or a group flag.""" + if isinstance(node, dict): + for key, value in node.items(): + if ( + key in {"args", "command"} + and isinstance(value, list) + and value + and all(isinstance(item, str) for item in value) + and (value[0] in COMMAND_OPTIONS or value[0] in GROUP_OPTIONS) + ): + yield value + else: + yield from _invocations(value) + elif isinstance(node, list): + for item in node: + yield from _invocations(item) + + +@pytest.mark.parametrize(("guide", "block"), list(_blocks())) +def test__yaml_block__parses(guide: str, block: str) -> None: + # A block of only a comment -- the editor's schema line -- parses to nothing, and that is fine. + list(yaml.safe_load_all(block)) + + +@pytest.mark.parametrize(("guide", "block"), list(_blocks())) +def test__every_flag_a_guide_hands_the_command__is_one_the_command_takes(guide: str, block: str) -> None: + for document in yaml.safe_load_all(block): + for invocation in _invocations(document): + command = invocation[0] + allowed = COMMAND_OPTIONS.get(command, GROUP_OPTIONS) + for argument in invocation[1:]: + if argument.startswith("-"): + flag = argument.partition("=")[0] + assert flag in allowed, f"{guide}: `{command}` takes no {flag}" + + +def test__the_running_guide__holds_the_manifests_the_lint_job_validates() -> None: + # Arrange: what scripts/k8s_manifests.py hands to kubeconform in CI + running = next(guide for guide in GUIDES if guide.name == "running.md") + + # Act + kinds = [ + document["kind"] + for block in manifests(running.read_text(encoding="utf-8")) + for document in yaml.safe_load_all(block) + if isinstance(document, dict) + ] + + # Assert: the shapes the guide promises, and nothing that is only a fragment + assert {"ConfigMap", "Secret", "Job", "CronJob"} <= set(kinds) + assert len(kinds) == len(manifests(running.read_text(encoding="utf-8"))) + 1 # one block holds two documents diff --git a/tests/unit/test_metrics.py b/tests/unit/test_metrics.py new file mode 100644 index 0000000..6dd4bc1 --- /dev/null +++ b/tests/unit/test_metrics.py @@ -0,0 +1,234 @@ +"""``--output metrics``: the same run, as a node_exporter textfile.""" + +from __future__ import annotations + +from datetime import UTC, datetime +from typing import Any + +from pg_partsmith.cli.metrics import _labels, render_metrics + + +def _samples(text: str) -> dict[str, float]: + """Every sample line as ``name{labels} -> value``, comments dropped.""" + samples: dict[str, float] = {} + for line in text.splitlines(): + if line.startswith("#") or not line.strip(): + continue + series, _, value = line.rpartition(" ") + samples[series] = float(value) + return samples + + +def _envelope(command: str, tables: list[dict[str, Any]]) -> dict[str, Any]: + return { + "version": 1, + "command": command, + "generated_at": "2026-09-01T12:00:00+00:00", + "tables": tables, + } + + +def test__render_metrics__every_family__is_documented_and_typed() -> None: + # A textfile collector serves these to Prometheus verbatim, so the HELP and + # TYPE lines are part of the output, not a nicety. + text = render_metrics(_envelope("validate", [{"table": "public.events", "ok": True}])) + + # Assert + assert "# HELP pg_partsmith_config_valid" in text + assert "# TYPE pg_partsmith_config_valid gauge" in text + assert text.endswith("\n") + + +def test__render_metrics__the_run_timestamp__is_the_one_in_the_envelope() -> None: + # Arrange / Act: a stale textfile has to be visible as stale + text = render_metrics(_envelope("plan", [])) + + # Assert + expected = datetime.fromisoformat("2026-09-01T12:00:00+00:00").timestamp() + assert _samples(text)['pg_partsmith_run_timestamp_seconds{command="plan"}'] == expected + + +def test__plan__pending_operations__are_counted_by_kind() -> None: + # Arrange + payload = _envelope( + "plan", + [ + { + "table": "public.events", + "plan": { + "operations": [ + {"kind": "create", "children": [{"kind": "create", "children": []}]}, + {"kind": "create", "children": []}, + {"kind": "drop"}, + ], + "findings": [{"severity": "warning"}, {"severity": "info"}, {"severity": "warning"}], + }, + } + ], + ) + + # Act + samples = _samples(render_metrics(payload)) + + # Assert + assert samples['pg_partsmith_pending_operations{table="public.events",kind="create"}'] == 2 + assert samples['pg_partsmith_pending_operations{table="public.events",kind="drop"}'] == 1 + assert samples['pg_partsmith_pending_operations{table="public.events",kind="detach"}'] == 0 + # Three relations: two top-level creations and one nested child + assert samples['pg_partsmith_pending_relations{table="public.events"}'] == 3 + assert samples['pg_partsmith_findings{table="public.events",severity="warning"}'] == 2 + assert samples['pg_partsmith_findings{table="public.events",severity="info"}'] == 1 + + +def test__plan__a_converged_table__reports_zeroes_rather_than_nothing() -> None: + # A missing series and a zero are different alerts; converged is a zero. + payload = _envelope("plan", [{"table": "public.events", "plan": {"operations": [], "findings": []}}]) + + # Act + samples = _samples(render_metrics(payload)) + + # Assert + assert samples['pg_partsmith_pending_operations{table="public.events",kind="create"}'] == 0 + assert samples['pg_partsmith_pending_relations{table="public.events"}'] == 0 + + +def test__inspect__counts_the_tree_and_ages_the_oldest_orphan() -> None: + # Arrange + payload = _envelope( + "inspect", + [ + { + "table": "public.events", + "tree": { + "root": { + "children": [ + {"children": [{"children": []}, {"children": []}]}, + {"children": []}, + ] + }, + "orphans": [ + {"name": "public.events__2025_01", "detached_at": "2026-09-01T11:00:00+00:00"}, + {"name": "public.events__2025_02", "detached_at": None}, + ], + }, + } + ], + ) + + # Act + samples = _samples(render_metrics(payload)) + + # Assert: four relations below the root, two orphans, one of them datable + assert samples['pg_partsmith_partitions{table="public.events"}'] == 4 + assert samples['pg_partsmith_detached_partitions{table="public.events"}'] == 2 + assert samples['pg_partsmith_partitioned{table="public.events"}'] == 1 + assert samples['pg_partsmith_oldest_detached_age_seconds{table="public.events"}'] > 0 + + +def test__inspect__a_table_that_is_not_partitioned__says_so_in_one_series() -> None: + # Arrange / Act + samples = _samples(render_metrics(_envelope("inspect", [{"table": "public.events", "tree": None}]))) + + # Assert + assert samples['pg_partsmith_partitioned{table="public.events"}'] == 0 + assert 'pg_partsmith_partitions{table="public.events"}' not in samples + + +def test__validate__a_table_the_catalog_disagrees_with__is_a_zero() -> None: + # Arrange / Act + payload = _envelope( + "validate", + [{"table": "public.events", "ok": True}, {"table": "public.audit", "ok": False, "error": "not partitioned"}], + ) + samples = _samples(render_metrics(payload)) + + # Assert + assert samples['pg_partsmith_config_valid{table="public.events"}'] == 1 + assert samples['pg_partsmith_config_valid{table="public.audit"}'] == 0 + + +def test__apply__reports_what_it_did_and_what_it_could_not() -> None: + # Arrange + payload = _envelope( + "apply", + [ + { + "table": "public.events", + "result": { + "created_count": 2, + "repaired_count": 0, + "attached_count": 1, + "detached_count": 1, + "dropped_count": 1, + "issues": [{"step": "drop", "error": "refused"}], + }, + } + ], + ) + + # Act + samples = _samples(render_metrics(payload)) + + # Assert + assert samples['pg_partsmith_applied_operations{table="public.events",operation="created"}'] == 2 + assert samples['pg_partsmith_applied_operations{table="public.events",operation="dropped"}'] == 1 + assert samples['pg_partsmith_issues{table="public.events"}'] == 1 + + +def test__render_metrics__a_table_name_with_a_quote_in_it__is_escaped() -> None: + # PostgreSQL allows it, and an unescaped quote would break the whole file. + payload = _envelope("validate", [{"table": 'public."odd"', "ok": True}]) + + # Act + text = render_metrics(payload) + + # Assert + assert 'pg_partsmith_config_valid{table="public.\\"odd\\""} 1' in text + + +def test__render_metrics__a_command_it_has_no_numbers_for__still_says_when_it_ran() -> None: + # Arrange / Act + text = render_metrics(_envelope("something-else", [])) + + # Assert + assert "pg_partsmith_run_timestamp_seconds" in text + assert len(_samples(text)) == 1 + + +def test__render_metrics__an_unreadable_run_instant__falls_back_to_now() -> None: + # A textfile with no timestamp would read as never-stale; now is the honest fallback. + before = datetime.now(UTC).timestamp() + text = render_metrics({"version": 1, "command": "plan", "generated_at": "not a date", "tables": []}) + + # Assert + assert _samples(text)['pg_partsmith_run_timestamp_seconds{command="plan"}'] >= before + + +def test__inspect__orphans_with_unreadable_or_naive_instants__age_what_can_be_aged() -> None: + # Arrange + payload = _envelope( + "inspect", + [ + { + "table": "public.events", + "tree": { + "root": {"children": []}, + "orphans": [ + {"name": "a", "detached_at": "not a date"}, + {"name": "b", "detached_at": "2026-01-01T00:00:00"}, + ], + }, + } + ], + ) + + # Act + samples = _samples(render_metrics(payload)) + + # Assert: the naive one is read as UTC; the unreadable one is skipped + assert samples['pg_partsmith_oldest_detached_age_seconds{table="public.events"}'] > 0 + + +def test__labels__no_labels__is_no_braces() -> None: + # Arrange / Act / Assert + assert _labels({}) == "" diff --git a/tests/unit/test_plan.py b/tests/unit/test_plan.py index 2995d7e..e57e513 100644 --- a/tests/unit/test_plan.py +++ b/tests/unit/test_plan.py @@ -2,11 +2,14 @@ from __future__ import annotations +import json from datetime import UTC, datetime, timedelta import pytest from pydantic import ValidationError +from pg_partsmith.entities import PartitionGranularity, TablePartitionConfig +from pg_partsmith.exceptions import PlanConfigMismatchError from pg_partsmith.lifecycle import DetachMode from pg_partsmith.plan import ( AttachPartition, @@ -22,6 +25,7 @@ PartitionBy, Reason, Severity, + validate_plan_for_config, ) from pg_partsmith.topology import DefaultBounds, HashBounds, ListBounds, PartitionType, RangeBounds @@ -592,3 +596,126 @@ def test__create_and_attach_capabilities__name_the_locks_on_referencing_tables() expected = "SHARE ROW EXCLUSIVE on every table referencing the parent" assert expected in _create().capabilities.lock assert expected in _attach().capabilities.lock + + +# ── The plan as an artifact ───────────────────────────────────────────────────── + + +def _config(*, schema: str | None = "public", retention: int = 12) -> TablePartitionConfig: + return TablePartitionConfig( + schema=schema, + table_name="events", + partition_column="created_at", + granularity=PartitionGranularity.MONTH, + retention_count=retention, + ) + + +def test__model_dump_json__round_trip__gives_back_the_same_plan() -> None: + # Arrange: everything a real plan carries beyond its operations + plan = FULL_PLAN.model_copy(update={"cursors": {"id": 42}, "config_fingerprint": "0123456789abcdef"}) + + # Act / Assert: the aliased form is what the configuration vocabulary uses, + # and both forms read back, so a plan written by one process and applied by + # another is the plan that was written. + assert MaintenancePlan.model_validate_json(plan.model_dump_json(by_alias=True)) == plan + assert MaintenancePlan.model_validate_json(plan.model_dump_json()) == plan + + +def test__model_dump_json__by_alias__spells_every_operation_kind_as_the_documented_key() -> None: + # Arrange / Act + dumped = json.loads(FULL_PLAN.model_dump_json(by_alias=True)) + + # Assert + assert [op["kind"] for op in dumped["operations"]] == ["create", "attach", "detach", "drop", "drop"] + + +def test__cursors__integers__survive_the_round_trip_as_integers() -> None: + # Arrange + plan = MaintenancePlan(table_name=ROOT, generated_at=NOW, cursors={"id": 900_001}) + + # Act + back = MaintenancePlan.model_validate_json(plan.model_dump_json(by_alias=True)) + + # Assert + assert back.cursors == {"id": 900_001} + assert back == plan + + +def test__cursors__a_value_no_integer_axis_could_have__is_rejected() -> None: + # Only an integer axis records a cursor -- a time axis is cursored by + # ``generated_at`` -- so anything else would not have round-tripped. + with pytest.raises(ValidationError): + MaintenancePlan(table_name=ROOT, generated_at=NOW, cursors={"created_at": NOW}) # type: ignore[dict-item] + + +def test__validate_plan_for_config__the_configuration_it_was_planned_from__passes() -> None: + # Arrange + config = _config() + plan = MaintenancePlan(table_name=ROOT, generated_at=NOW, config_fingerprint=config.fingerprint) + + # Act / Assert + validate_plan_for_config(config, plan) + + +def test__validate_plan_for_config__a_plan_for_another_table__is_refused_naming_both() -> None: + # Arrange + plan = MaintenancePlan(table_name="public.audit", generated_at=NOW) + + # Act / Assert + with pytest.raises(PlanConfigMismatchError) as exc: + validate_plan_for_config(_config(), plan) + assert "public.audit" in str(exc.value) + assert "public.events" in str(exc.value) + + +def test__validate_plan_for_config__configuration_edited_after_planning__is_refused() -> None: + # Arrange: the plan still names the right relations, for reasons that have + # stopped being true -- which OID revalidation cannot see. + planned_under = _config(retention=12) + plan = MaintenancePlan(table_name=ROOT, generated_at=NOW, config_fingerprint=planned_under.fingerprint) + edited = _config(retention=3) + + # Act / Assert + with pytest.raises(PlanConfigMismatchError) as exc: + validate_plan_for_config(edited, plan) + assert planned_under.fingerprint in str(exc.value) + assert edited.fingerprint in str(exc.value) + + +def test__validate_plan_for_config__allow_config_drift__takes_the_plan_as_it_stands() -> None: + # Arrange + plan = MaintenancePlan(table_name=ROOT, generated_at=NOW, config_fingerprint=_config(retention=12).fingerprint) + + # Act / Assert + validate_plan_for_config(_config(retention=3), plan, allow_config_drift=True) + + +def test__validate_plan_for_config__plan_without_a_fingerprint__is_checked_for_its_table_alone() -> None: + # Arrange: a plan built by hand, or by a version that recorded none + plan = MaintenancePlan(table_name=ROOT, generated_at=NOW) + + # Act / Assert + validate_plan_for_config(_config(), plan) + with pytest.raises(PlanConfigMismatchError): + validate_plan_for_config(_config(schema="archive"), plan) + + +def test__model_dump__carries_the_lock_each_operation_takes() -> None: + # A plan written to a file is what an operator reads before agreeing to a + # window, so what each operation locks is in the dump, not only on the object. + dumped = json.loads(FULL_PLAN.model_dump_json(by_alias=True)) + + # Assert + by_kind = {op["kind"]: op for op in dumped["operations"]} + assert "ACCESS EXCLUSIVE on the dropped table only" in by_kind["drop"]["capabilities"]["lock"] + assert by_kind["detach"]["capabilities"]["transactional"] is False + assert by_kind["drop"]["is_destructive"] is True + assert by_kind["create"]["is_destructive"] is False + # and a subtree member says so as well + assert "capabilities" in by_kind["create"]["children"][0] + + +def test__model_validate__a_dump_carrying_capabilities__reads_back_as_the_same_plan() -> None: + # Computed on the way out, ignored on the way in: the round trip holds. + assert MaintenancePlan.model_validate_json(FULL_PLAN.model_dump_json(by_alias=True)) == FULL_PLAN diff --git a/tests/unit/test_planner.py b/tests/unit/test_planner.py index 21ae80b..7a9784d 100644 --- a/tests/unit/test_planner.py +++ b/tests/unit/test_planner.py @@ -2421,3 +2421,14 @@ def test__plan_maintenance__detach_pending_child_in_a_wanted_window__finalized_w assert [op.reason for op in plan.detaches] == [Reason.DETACH_FINALIZE] assert plan.creates == () assert _reasons(plan) == [FindingReason.DETACH_PENDING] + + +def test__plan_maintenance__records_the_configuration_it_planned_under() -> None: + # Arrange + config = _config() + + # Act + plan = _plan(config, _root()) + + # Assert: what makes a plan read back from a file answerable + assert plan.config_fingerprint == config.fingerprint diff --git a/tests/unit/test_python_hooks.py b/tests/unit/test_python_hooks.py new file mode 100644 index 0000000..37b90b3 --- /dev/null +++ b/tests/unit/test_python_hooks.py @@ -0,0 +1,164 @@ +"""``PythonHooks``: a lifecycle hook written as a block in a configuration file.""" + +from __future__ import annotations + +import logging +from pathlib import Path + +import pytest + +from pg_partsmith.aio.python_hooks import PythonHookError, PythonHooks +from pg_partsmith.entities import PartitionGranularity, PartitionInfo, TablePartitionConfig +from pg_partsmith.events import HookPhase, PartitionEvent +from pg_partsmith.plan import DropPartition, Reason +from pg_partsmith.python_hooks import compile_hook_source, run_hook_source +from pg_partsmith.sync.python_hooks import PythonHooks as SyncPythonHooks +from pg_partsmith.topology import RangeBounds + +CONFIG = TablePartitionConfig( + schema="public", + table_name="events", + partition_column="created_at", + granularity=PartitionGranularity.MONTH, +) + + +def _event(phase: HookPhase = HookPhase.BEFORE_DROP) -> PartitionEvent: + info = PartitionInfo( + name="events__2025_08", + schema_name="public", + partition_type="range", + is_attached=False, + bounds=RangeBounds(from_value="2025-08-01", to_value="2025-09-01"), + ) + operation = DropPartition(target="public.events__2025_08", reason=Reason.GRACE_ELAPSED, oid=42, size_bytes=4096) + return PartitionEvent.build(phase, CONFIG, info, operation) + + +async def test__on_event__the_block_sees_the_event_and_a_logger(tmp_path: Path) -> None: + # Arrange: a block that writes what it was handed + marker = tmp_path / "seen.txt" + source = f""" +import pathlib +pathlib.Path({str(marker)!r}).write_text( + f"{{event.phase.value}} {{event.partition.name}} {{event.operation.size_bytes}} {{event.window.start.date()}}", + encoding="utf-8", +) +log.info("seen %s", event.partition.name) +""" + hooks = PythonHooks({HookPhase.BEFORE_DROP: source}) + + # Act + await hooks.on_event(_event()) + + # Assert + assert marker.read_text(encoding="utf-8") == "before_drop events__2025_08 4096 2025-08-01" + + +async def test__on_event__another_phase__runs_nothing(tmp_path: Path) -> None: + # Arrange + marker = tmp_path / "ran" + hooks = PythonHooks({HookPhase.BEFORE_DROP: f"import pathlib; pathlib.Path({str(marker)!r}).write_text('x')"}) + + # Act + await hooks.on_event(_event(HookPhase.AFTER_CREATE)) + + # Assert + assert not marker.exists() + + +async def test__on_event__a_block_that_raises__refuses_the_operation_and_keeps_the_cause() -> None: + # Arrange: raising is how a block says "not yet" + hooks = PythonHooks({HookPhase.BEFORE_DROP: "raise RuntimeError('rows still referenced')"}) + + # Act / Assert + with pytest.raises(PythonHookError, match="rows still referenced") as exc: + await hooks.on_event(_event()) + assert exc.value.phase is HookPhase.BEFORE_DROP + assert exc.value.partition_name == "events__2025_08" + assert isinstance(exc.value.__cause__, RuntimeError) + + +def test__python_hooks__a_block_that_does_not_parse__is_refused_when_built() -> None: + # A SyntaxError found at 03:00 by a CronJob is the failure mode to design out. + with pytest.raises(SyntaxError): + PythonHooks({HookPhase.BEFORE_DROP: "if event.partition.name\n pass"}) + + +def test__python_hooks__a_block_is_named_after_its_phase_in_tracebacks() -> None: + # Arrange + code = compile_hook_source("raise ValueError('x')", name="") + + # Act / Assert + with pytest.raises(PythonHookError) as exc: + run_hook_source(code, _event(), logger=logging.getLogger("test")) + assert exc.value.__cause__ is not None + assert exc.value.__cause__.__traceback__ is not None + frames = [] + trace = exc.value.__cause__.__traceback__ + while trace is not None: + frames.append(trace.tb_frame.f_code.co_filename) + trace = trace.tb_next + assert "" in frames + + +def test__python_hooks__an_empty_block__is_refused() -> None: + # Arrange / Act / Assert + with pytest.raises(ValueError, match="empty"): + PythonHooks({HookPhase.BEFORE_DROP: " "}) + + +def test__python_hooks__implements_every_phase_method_the_executor_calls() -> None: + # The executor calls the method named for the phase after on_event. + hooks = PythonHooks({HookPhase.AFTER_CREATE: "pass"}) + + # Act / Assert + assert all(callable(getattr(hooks, phase.value, None)) for phase in HookPhase) + assert hooks.phases == (HookPhase.AFTER_CREATE,) + + +def test__sync_python_hooks__runs_the_same_block_the_same_way(tmp_path: Path) -> None: + # Arrange + marker = tmp_path / "seen.txt" + hooks = SyncPythonHooks( + {HookPhase.BEFORE_DROP: f"import pathlib; pathlib.Path({str(marker)!r}).write_text(event.table_name)"} + ) + + # Act + hooks.on_event(_event()) + + # Assert + assert marker.read_text() == "public.events" + + +def test__sync_python_hooks__a_block_that_raises__refuses_the_operation() -> None: + # Arrange + hooks = SyncPythonHooks({HookPhase.BEFORE_DROP: "raise KeyError('archive')"}) + + # Act / Assert + with pytest.raises(PythonHookError, match="KeyError"): + hooks.on_event(_event()) + + +def test__python_hooks__a_phase_that_is_not_one__is_refused_in_both_mirrors() -> None: + # Arrange / Act / Assert + with pytest.raises(ValueError, match="not a hook phase"): + PythonHooks({"before_lunch": "pass"}) # type: ignore[dict-item] + with pytest.raises(ValueError, match="not a hook phase"): + SyncPythonHooks({"before_lunch": "pass"}) # type: ignore[dict-item] + + +def test__sync_python_hooks__the_same_refusals_the_same_phases_and_the_same_silence(tmp_path: Path) -> None: + # Arrange + marker = tmp_path / "ran" + body = f"import pathlib; pathlib.Path({str(marker)!r}).write_text('x')" + hooks = SyncPythonHooks({HookPhase.BEFORE_DROP: body}) + + # Act / Assert + with pytest.raises(ValueError, match="empty"): + SyncPythonHooks({HookPhase.BEFORE_DROP: " "}) + with pytest.raises(SyntaxError): + SyncPythonHooks({HookPhase.BEFORE_DROP: "def broken(:"}) + assert hooks.phases == (HookPhase.BEFORE_DROP,) + hooks.on_event(_event(HookPhase.AFTER_CREATE)) + assert not marker.exists() diff --git a/tests/unit/test_service.py b/tests/unit/test_service.py index 8546ebc..7b5946e 100644 --- a/tests/unit/test_service.py +++ b/tests/unit/test_service.py @@ -494,7 +494,7 @@ async def _apply(*args: object, **kwargs: object) -> MaintenanceResult: assert result is expected locks.acquire_lock.assert_called_once_with("events") assert events == ["acquire", "apply", "release"] - service._executor.apply.assert_awaited_once_with(config, plan, continue_on_error=True) + service._executor.apply.assert_awaited_once_with(config, plan, continue_on_error=True, allow_config_drift=False) async def test__apply__executor_fails__lock_is_still_released( diff --git a/tests/unit/test_toolkit.py b/tests/unit/test_toolkit.py new file mode 100644 index 0000000..7644856 --- /dev/null +++ b/tests/unit/test_toolkit.py @@ -0,0 +1,143 @@ +"""``PartitionToolkit``: one engine in, a set of collaborators that agree out.""" + +from __future__ import annotations + +from dataclasses import FrozenInstanceError +from unittest.mock import MagicMock + +import pytest + +from pg_partsmith.aio import ( + BasePartitionLifecycleHooks, + PartitionLifecycleService, + PartitionMaintainer, + PartitionToolkit, + PostgresAdvisoryLockManager, + PostgresMetadataProvider, + PostgresPartitionRepository, +) +from pg_partsmith.boundaries import UUIDv7BoundaryCodec +from pg_partsmith.document import ToolkitOptions + + +@pytest.fixture +def engine() -> MagicMock: + return MagicMock() + + +def test__from_engine__builds_every_part_around_the_one_engine(engine: MagicMock) -> None: + # Arrange / Act + kit = PartitionToolkit.from_engine(engine) + + # Assert + assert isinstance(kit.repo, PostgresPartitionRepository) + assert isinstance(kit.metadata, PostgresMetadataProvider) + assert isinstance(kit.locks, PostgresAdvisoryLockManager) + assert isinstance(kit.service, PartitionLifecycleService) + assert isinstance(kit.maintainer, PartitionMaintainer) + + +def test__from_engine__marker_prefix__reaches_the_writer_and_the_reader(engine: MagicMock) -> None: + # Arrange / Act: the prefix given to one of the two only is the failure this + # exists to prevent -- partitions detached under it are invisible to the + # other, so they are never dropped. + kit = PartitionToolkit.from_engine(engine, marker_prefix="acme") + + # Assert + assert kit.repo.marker_prefix == kit.metadata.marker_prefix + assert kit.repo.marker_prefix != PartitionToolkit.from_engine(engine).repo.marker_prefix + + +def test__from_engine__ddl_timezone__is_given_to_both_sides_of_the_boundary(engine: MagicMock) -> None: + # Arrange / Act + kit = PartitionToolkit.from_engine(engine, ddl_timezone="Europe/Berlin") + + # Assert: one writes naive bounds in it, the other reads them back in it + assert kit.repo.ddl_timezone == "Europe/Berlin" + assert kit.metadata._ddl_timezone == "Europe/Berlin" + + +def test__from_engine__nothing_passed__leaves_no_disagreement_to_default_into(engine: MagicMock) -> None: + # The two constructors default differently -- "UTC" on the repository, None + # on the provider -- so a caller who passed neither used to get a reader on + # a timezone the writer never used. + kit = PartitionToolkit.from_engine(engine) + + assert kit.repo.ddl_timezone == "UTC" + assert kit.metadata._ddl_timezone == "UTC" + + +def test__from_engine__a_lock_manager_of_your_own__is_used_as_given(engine: MagicMock) -> None: + # Arrange + locks = MagicMock() + + # Act + kit = PartitionToolkit.from_engine(engine, locks=locks) + + # Assert + assert kit.locks is locks + assert kit.service._locks is locks + + +def test__from_engine__the_service_holds_the_very_parts_that_are_returned(engine: MagicMock) -> None: + # Arrange / Act: the point of returning parts rather than a maintainer is + # that calling metadata or locks directly needs no second wiring. + kit = PartitionToolkit.from_engine(engine) + + # Assert + assert kit.service._repo is kit.repo + assert kit.service._metadata is kit.metadata + assert kit.maintainer._service is kit.service + + +def test__from_engine__hooks__reach_the_executor_that_fires_them(engine: MagicMock) -> None: + # Arrange + hooks = BasePartitionLifecycleHooks() + + # Act + kit = PartitionToolkit.from_engine(engine, hooks=[hooks]) + + # Assert + assert kit.service._executor._hooks == [hooks] + + +def test__toolkit__is_frozen(engine: MagicMock) -> None: + # Arrange + kit = PartitionToolkit.from_engine(engine) + + # Act / Assert + with pytest.raises(FrozenInstanceError): + kit.repo = MagicMock() # type: ignore[misc] + + +def test__from_options__the_runtime_section_of_a_document__is_the_wiring(engine: MagicMock) -> None: + # Arrange: what a file says, in the words a file says it in + options = ToolkitOptions(marker_prefix="acme", ddl_timezone="Europe/Berlin", boundary_codec="uuidv7") + + # Act + kit = PartitionToolkit.from_options(engine, options) + + # Assert + assert kit.repo.marker_prefix == kit.metadata.marker_prefix + assert kit.repo.ddl_timezone == "Europe/Berlin" + assert kit.metadata._ddl_timezone == "Europe/Berlin" + assert isinstance(kit.metadata._boundary_codec, UUIDv7BoundaryCodec) + + +def test__from_options__hooks_and_a_lock_manager__are_passed_through(engine: MagicMock) -> None: + # Arrange + hooks = BasePartitionLifecycleHooks() + locks = MagicMock() + + # Act + kit = PartitionToolkit.from_options(engine, ToolkitOptions(), hooks=[hooks], locks=locks) + + # Assert + assert kit.locks is locks + assert kit.service._executor._hooks == [hooks] + + +def test__from_options__a_codec_name_nothing_answers_to__is_refused(engine: MagicMock) -> None: + # Act / Assert: the file is wrong, and says so before any connection is opened + with pytest.raises(ValueError, match="uuidv8"): + PartitionToolkit.from_options(engine, ToolkitOptions(boundary_codec="uuidv8")) diff --git a/uv.lock b/uv.lock index 7b59257..63cdf61 100644 --- a/uv.lock +++ b/uv.lock @@ -6,6 +6,15 @@ resolution-markers = [ "python_full_version < '3.15'", ] +[[package]] +name = "annotated-doc" +version = "0.0.5" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/5a/8e/38aa427ed5402449e226975b649c5dc73ccadfefeb95e6aecb8f8ea4b6b6/annotated_doc-0.0.5.tar.gz", hash = "sha256:c7e58ce09192557605d8bbd92836d7e1d520ac9580096042c0bfd197efacf1bb", size = 10758, upload-time = "2026-07-28T13:50:58.129Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3e/30/e900b21425a860e195f32e37657aa1f7c7f2b1bfb26f03ca209b90933c06/annotated_doc-0.0.5-py3-none-any.whl", hash = "sha256:117bac03a25ede5df5440e855b32d556049ca169ead221505badf432fed4b101", size = 5302, upload-time = "2026-07-28T13:50:57.239Z" }, +] + [[package]] name = "annotated-types" version = "0.7.0" @@ -594,6 +603,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/de/1f/77fa3081e4f66ca3576c896ae5d31c3002ac6607f9747d2e3aa49227e464/markdown-3.10.2-py3-none-any.whl", hash = "sha256:e91464b71ae3ee7afd3017d9f358ef0baf158fd9a298db92f1d4761133824c36", size = 108180, upload-time = "2026-02-09T14:57:25.787Z" }, ] +[[package]] +name = "markdown-it-py" +version = "4.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mdurl" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/06/ff/7841249c247aa650a76b9ee4bbaeae59370dc8bfd2f6c01f3630c35eb134/markdown_it_py-4.2.0.tar.gz", hash = "sha256:04a21681d6fbb623de53f6f364d352309d4094dd4194040a10fd51833e418d49", size = 82454, upload-time = "2026-05-07T12:08:28.36Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b3/81/4da04ced5a082363ecfa159c010d200ecbd959ae410c10c0264a38cac0f5/markdown_it_py-4.2.0-py3-none-any.whl", hash = "sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a", size = 91687, upload-time = "2026-05-07T12:08:27.182Z" }, +] + [[package]] name = "markupsafe" version = "3.0.3" @@ -668,6 +689,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/70/bc/6f1c2f612465f5fa89b95bead1f44dcb607670fd42891d8fdcd5d039f4f4/markupsafe-3.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:32001d6a8fc98c8cb5c947787c5d08b0a50663d139f1305bac5885d98d9b40fa", size = 14146, upload-time = "2025-09-27T18:37:28.327Z" }, ] +[[package]] +name = "mdurl" +version = "0.1.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d6/54/cfe61301667036ec958cb99bd3efefba235e65cdeb9c84d24a8293ba1d90/mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba", size = 8729, upload-time = "2022-08-14T12:40:10.846Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979, upload-time = "2022-08-14T12:40:09.779Z" }, +] + [[package]] name = "mergedeep" version = "1.3.4" @@ -857,6 +887,11 @@ dependencies = [ ] [package.optional-dependencies] +cli = [ + { name = "asyncpg" }, + { name = "pyyaml" }, + { name = "typer" }, +] pydantic-settings = [ { name = "pydantic-settings" }, ] @@ -871,12 +906,16 @@ dev = [ { name = "mypy" }, { name = "pre-commit" }, { name = "psycopg2-binary" }, + { name = "pydantic-settings" }, { name = "pytest" }, { name = "pytest-asyncio" }, { name = "pytest-cov" }, + { name = "pyyaml" }, { name = "ruff" }, { name = "testcontainers", extra = ["redis"] }, + { name = "typer" }, { name = "types-python-dateutil" }, + { name = "types-pyyaml" }, { name = "tzdata" }, ] docs = [ @@ -887,23 +926,30 @@ test = [ { name = "asyncpg" }, { name = "freezegun" }, { name = "psycopg2-binary" }, + { name = "pydantic-settings" }, { name = "pytest" }, { name = "pytest-asyncio" }, { name = "pytest-cov" }, + { name = "pyyaml" }, { name = "testcontainers", extra = ["redis"] }, + { name = "typer" }, { name = "types-python-dateutil" }, + { name = "types-pyyaml" }, { name = "tzdata" }, ] [package.metadata] requires-dist = [ - { name = "pydantic", specifier = ">=2.0.0,<3.0.0" }, + { name = "asyncpg", marker = "extra == 'cli'", specifier = ">=0.29.0" }, + { name = "pydantic", specifier = ">=2.6.0,<3.0.0" }, { name = "pydantic-settings", marker = "extra == 'pydantic-settings'", specifier = ">=2.0.0,<3.0.0" }, { name = "python-dateutil", specifier = ">=2.7.0,<3.0.0" }, + { name = "pyyaml", marker = "extra == 'cli'", specifier = ">=6.0,<7.0" }, { name = "redis", marker = "extra == 'redis-locks'", specifier = ">=4.2.0" }, { name = "sqlalchemy", extras = ["asyncio"], specifier = ">=2.0.0,<3.0.0" }, + { name = "typer", marker = "extra == 'cli'", specifier = ">=0.17,<1.0" }, ] -provides-extras = ["pydantic-settings", "redis-locks"] +provides-extras = ["cli", "pydantic-settings", "redis-locks"] [package.metadata.requires-dev] dev = [ @@ -912,12 +958,16 @@ dev = [ { name = "mypy", specifier = ">=1.19.1" }, { name = "pre-commit", specifier = ">=4.5.1" }, { name = "psycopg2-binary", specifier = ">=2.9.11" }, + { name = "pydantic-settings", specifier = ">=2.0.0,<3.0.0" }, { name = "pytest", specifier = ">=9.0.2" }, { name = "pytest-asyncio", specifier = ">=1.3.0" }, { name = "pytest-cov", specifier = ">=7.0.0" }, + { name = "pyyaml", specifier = ">=6.0,<7.0" }, { name = "ruff", specifier = ">=0.15.1" }, { name = "testcontainers", extras = ["redis"], specifier = ">=4.14.1" }, + { name = "typer", specifier = ">=0.17,<1.0" }, { name = "types-python-dateutil", specifier = "~=2.9.0" }, + { name = "types-pyyaml", specifier = ">=6.0" }, { name = "tzdata", specifier = ">=2024.1" }, ] docs = [ @@ -928,11 +978,15 @@ test = [ { name = "asyncpg", specifier = ">=0.31.0" }, { name = "freezegun", specifier = ">=1.5.5" }, { name = "psycopg2-binary", specifier = ">=2.9.11" }, + { name = "pydantic-settings", specifier = ">=2.0.0,<3.0.0" }, { name = "pytest", specifier = ">=9.0.2" }, { name = "pytest-asyncio", specifier = ">=1.3.0" }, { name = "pytest-cov", specifier = ">=7.0.0" }, + { name = "pyyaml", specifier = ">=6.0,<7.0" }, { name = "testcontainers", extras = ["redis"], specifier = ">=4.14.1" }, + { name = "typer", specifier = ">=0.17,<1.0" }, { name = "types-python-dateutil", specifier = "~=2.9.0" }, + { name = "types-pyyaml", specifier = ">=6.0" }, { name = "tzdata", specifier = ">=2024.1" }, ] @@ -1365,6 +1419,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d7/8e/7540e8a2036f79a125c1d2ebadf69ed7901608859186c856fa0388ef4197/requests-2.33.1-py3-none-any.whl", hash = "sha256:4e6d1ef462f3626a1f0a0a9c42dd93c63bad33f9f1c1937509b8c5c8718ab56a", size = 64947, upload-time = "2026-03-30T16:09:13.83Z" }, ] +[[package]] +name = "rich" +version = "15.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markdown-it-py" }, + { name = "pygments" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/c0/8f/0722ca900cc807c13a6a0c696dacf35430f72e0ec571c4275d2371fca3e9/rich-15.0.0.tar.gz", hash = "sha256:edd07a4824c6b40189fb7ac9bc4c52536e9780fbbfbddf6f1e2502c31b068c36", size = 230680, upload-time = "2026-04-12T08:24:00.75Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/82/3b/64d4899d73f91ba49a8c18a8ff3f0ea8f1c1d75481760df8c68ef5235bf5/rich-15.0.0-py3-none-any.whl", hash = "sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb", size = 310654, upload-time = "2026-04-12T08:24:02.83Z" }, +] + [[package]] name = "ruff" version = "0.15.12" @@ -1390,6 +1457,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c0/98/6beb4b351e472e5f4c4613f7c35a5290b8be2497e183825310c4c3a3984b/ruff-0.15.12-py3-none-win_arm64.whl", hash = "sha256:a538f7a82d061cee7be55542aca1d86d1393d55d81d4fcc314370f4340930d4f", size = 11120821, upload-time = "2026-04-24T18:16:57.979Z" }, ] +[[package]] +name = "shellingham" +version = "1.5.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/58/15/8b3609fd3830ef7b27b655beb4b4e9c62313a4e8da8c676e142cc210d58e/shellingham-1.5.4.tar.gz", hash = "sha256:8dbca0739d487e5bd35ab3ca4b36e11c4078f3a234bfce294b0a0291363404de", size = 10310, upload-time = "2023-10-24T04:13:40.426Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e0/f9/0595336914c5619e5f28a1fb793285925a8cd4b432c9da0a987836c7f822/shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686", size = 9755, upload-time = "2023-10-24T04:13:38.866Z" }, +] + [[package]] name = "six" version = "1.17.0" @@ -1532,6 +1608,21 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/7b/61/cceae43728b7de99d9b847560c262873a1f6c98202171fd5ed62640b494b/tomli-2.4.1-py3-none-any.whl", hash = "sha256:0d85819802132122da43cb86656f8d1f8c6587d54ae7dcaf30e90533028b49fe", size = 14583, upload-time = "2026-03-25T20:22:03.012Z" }, ] +[[package]] +name = "typer" +version = "0.27.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "annotated-doc" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "rich" }, + { name = "shellingham" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/16/f7/57713ba479fd405eb76de31404b2c744c289e336b2d999511ebf51e496f7/typer-0.27.2.tar.gz", hash = "sha256:269b7eb9d3c202ca84b4bc9618cb04ebb43d3d4d1e567e4c768607232c05f945", size = 204045, upload-time = "2026-08-28T10:26:55.046Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/dc/bf/205d0004930ede8f542fb58f601526fccf4ae7626075ca1e6c4de5d3d652/typer-0.27.2-py3-none-any.whl", hash = "sha256:b3a5fc4342d5fc8fda8fc3010b1cf117e9249aab7fae800c2eff62fd3842d97d", size = 123130, upload-time = "2026-08-28T10:26:53.752Z" }, +] + [[package]] name = "types-python-dateutil" version = "2.9.0.20260508" @@ -1541,6 +1632,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/db/7c/1788ff10edf56031d74ad3fba40947e0e8b82e3a529b30e6b7d71c191dec/types_python_dateutil-2.9.0.20260508-py3-none-any.whl", hash = "sha256:bfc6fd2d81aa86e5ac97206a64304f6bd247426eedbca9b98619bbc48c6a1c10", size = 18425, upload-time = "2026-05-08T04:47:07.207Z" }, ] +[[package]] +name = "types-pyyaml" +version = "6.0.12.20260815" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9f/72/b56089aeee6c496d969bac42376bedb6e3eeab4682e1018fa3137122f94b/types_pyyaml-6.0.12.20260815.tar.gz", hash = "sha256:28764110c9cf35846e733da32d8d734df7473c5dde9ef67c3b7332ec0e819858", size = 18545, upload-time = "2026-08-15T02:41:51.532Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/08/52/eefeba09be4ef2a1eb989eb92934561e8e502a6ee3c32654996e4be7e399/types_pyyaml-6.0.12.20260815-py3-none-any.whl", hash = "sha256:6f332212b7e191f3afd5016a713c510b6340593b7ebec573c7d5d20aa5386d3b", size = 21148, upload-time = "2026-08-15T02:41:50.555Z" }, +] + [[package]] name = "typing-extensions" version = "4.15.0" diff --git a/zensical.toml b/zensical.toml index 9ac9c43..b6d6dca 100644 --- a/zensical.toml +++ b/zensical.toml @@ -34,6 +34,11 @@ nav = [ { "How-to guides" = [ { "Configure a table" = "guide/configuration.md" }, { "Schedule maintenance" = "guide/scheduling.md" }, + { "The command line" = "guide/cli.md" }, + { "The container image" = "guide/container.md" }, + { "Ways to run it" = "guide/running.md" }, + { "Configuration examples" = "guide/examples.md" }, + { "Commands around the lifecycle" = "guide/hooks-in-config.md" }, { "Monitor and alert" = "guide/monitoring.md" }, { "Query a partitioned table" = "guide/querying.md" }, { "Backfill partitions for existing data" = "guide/backfill.md" }, @@ -51,6 +56,7 @@ nav = [ { "Reference" = [ { "API" = "reference/index.md" }, { "Configuration fields" = "reference/configuration.md" }, + { "The configuration document" = "reference/document.md" }, { "Findings and issues" = "reference/findings.md" }, { "Environment settings" = "reference/settings.md" }, { "Glossary" = "reference/glossary.md" },