diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 61aef20..a8aa099 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -83,3 +83,9 @@ jobs: - name: Dump database logs if: failure() run: docker compose logs --no-color + + # Every pull request also upgrades from the latest release, so a + # change that breaks the upgrade is caught when it is made, not + # when the release workflow refuses to publish. + upgrade: + uses: ./.github/workflows/upgrade.yml diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 63faed1..b12698a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -229,6 +229,16 @@ jobs: exit 1 fi + # Upgrade coverage (rds-distribution decision 8): the latest + # release upgraded to this build through both channels, with a + # consumer registration surviving and the full suite green on + # the upgraded database. No tag is cut without it. + upgrade: + if: >- + github.repository == 'emfga/cel4postgres' && + github.ref == 'refs/heads/main' + uses: ./.github/workflows/upgrade.yml + # The tag does not exist beforehand; gh creates it at the # released commit, and re-running on an already-released # version fails here instead of republishing. @@ -236,7 +246,7 @@ jobs: if: >- github.repository == 'emfga/cel4postgres' && github.ref == 'refs/heads/main' - needs: [smoke, pgtle] + needs: [smoke, pgtle, upgrade] runs-on: ubuntu-latest timeout-minutes: 10 permissions: diff --git a/.github/workflows/upgrade.yml b/.github/workflows/upgrade.yml new file mode 100644 index 0000000..92e3c10 --- /dev/null +++ b/.github/workflows/upgrade.yml @@ -0,0 +1,82 @@ +name: Upgrade + +# Upgrade coverage: no release without it. Installs the latest +# published release (N-1) the way a consumer did, registers a +# consumer overload, upgrades to this checkout's build, and runs the +# full suite against the upgraded database. Both shipped channels: +# plain psql scripts and pg_tle's ALTER EXTENSION ... UPDATE. +# +# Reusable only: CI runs it on every pull request, and the release +# workflow's publish job needs it. +on: + workflow_call: + +permissions: + contents: read + +jobs: + upgrade: + runs-on: ubuntu-latest + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + channel: [plain, pgtle] + steps: + - uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: go.mod + cache: true + + # The latest release is N-1 by construction: the release + # workflow refuses to publish a version that already exists. + - name: Download the previous release + env: + GH_TOKEN: ${{ github.token }} + run: | + gh release download -R "$GITHUB_REPOSITORY" -D "$RUNNER_TEMP/prev" \ + -p 'cel4postgres--*.sql' -p SHA256SUMS + + - name: Build images and artifacts + run: | + ./scripts/build-release.sh + base=$(sed -n 's/^ *image: \(postgres:[^ ]*\)$/\1/p' \ + compose.yaml) + if [ "${{ matrix.channel }}" = pgtle ]; then + docker build -f docker/pg_tle.Dockerfile \ + --build-arg BASE_IMAGE="$base" -t pgtle . + image=pgtle + else + image=$base + fi + echo "IMAGE=$image" >>"$GITHUB_ENV" + + - name: Upgrade from the previous release + run: | + ./scripts/upgrade-check.sh "${{ matrix.channel }}" "$IMAGE" \ + "$RUNNER_TEMP/prev" 5432 + + # Same corpus pin as ci.yml; a test checks both against + # internal/corpus.Pin. + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: cel-expr/cel-spec + ref: ba58ae5007845f3a1279b488cdeb79645ce958bb + path: .cel-expr/cel-spec + + # An upgraded database has to be exactly as conformant as a + # fresh install. + - run: go test ./... -v + env: + CEL_EXPR_DIR: ${{ github.workspace }}/.cel-expr + DATABASE_URL: postgres://cel:pw@127.0.0.1:5432/cel?sslmode=disable + + - name: Dump database logs + if: failure() + run: docker logs "cel-upgrade-${{ matrix.channel }}" diff --git a/docs/INSTALL.md b/docs/INSTALL.md index 3769bfe..30544e5 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -165,10 +165,37 @@ reads the registry tables. The role still cannot register anything `SELECT cel.version()` reports the installed version, recorded in `cel.schema_version` at install time. -There is no in-place upgrade path yet: moving to a new version -means uninstalling and installing the new artifact. Note that this -also removes anything you registered in the registry tables -yourself — re-register after reinstalling. +To upgrade, run the new release's artifact over the installed one, +exactly as you installed it. The installer is idempotent: it +replaces every function and every registry row it ships, and leaves +alone anything you registered yourself. + +```bash +psql -v ON_ERROR_STOP=1 --single-transaction "$DATABASE_URL" \ + -f cel4postgres--.sql +``` + +Through pg_tle, register the new bundle as an update path and +update the extension: + +```bash +./scripts/pgtle-wrap.sh --update-from cel4postgres \ + cel4postgres--.sql > cel4postgres-update.pgtle.sql + +psql -v ON_ERROR_STOP=1 "$DATABASE_URL" \ + -f cel4postgres-update.pgtle.sql \ + -c "ALTER EXTENSION cel4postgres UPDATE TO '';" +``` + +Both paths are tested before every release: CI installs the +previous release, registers an overload of its own, upgrades to +the new build, and runs the full conformance suite against the +upgraded database. The upgrade tested is from the immediately +previous release; when skipping versions, upgrade through each. + +A release that adds functions needs the access-control grants +re-run afterwards: `GRANT … ON ALL FUNCTIONS` covers only the +functions that existed when it ran. [releases]: https://github.com/emfga/cel4postgres/releases [pg_tle]: https://github.com/aws/pg_tle diff --git a/internal/corpus/corpus_test.go b/internal/corpus/corpus_test.go index afb776b..5941861 100644 --- a/internal/corpus/corpus_test.go +++ b/internal/corpus/corpus_test.go @@ -74,28 +74,35 @@ func TestPinMatchesWorkflow(t *testing.T) { t.Fatal(err) } - path := filepath.Join(root, ".github", "workflows", "ci.yml") - source, err := os.ReadFile(path) - if err != nil { - t.Fatalf("read ci.yml: %v", err) - } - pattern := regexp.MustCompile( `repository:\s*cel-expr/cel-spec\s*\n\s*ref:\s*([0-9a-f]{40})`, ) - match := pattern.FindSubmatch(source) - if match == nil { - t.Fatal("ci.yml does not check cel-expr/cel-spec out by commit") - } + // Every workflow that runs the suite checks the corpus out + // itself: CI on a fresh install, and the upgrade job on an + // upgraded one. + for _, name := range []string{"ci.yml", "upgrade.yml"} { + path := filepath.Join(root, ".github", "workflows", name) + source, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read %s: %v", name, err) + } - if ref := string(match[1]); ref != Pin { - t.Fatalf( - "ci.yml checks out cel-spec %s but corpus.Pin says %s\n"+ - "The corpus defines what the conformance number means: "+ - "move both together, with a re-measurement behind it.", - ref, Pin, - ) + match := pattern.FindSubmatch(source) + if match == nil { + t.Fatalf("%s does not check cel-expr/cel-spec out by commit", + name) + } + + if ref := string(match[1]); ref != Pin { + t.Fatalf( + "%s checks out cel-spec %s but corpus.Pin says %s\n"+ + "The corpus defines what the conformance number "+ + "means: move both together, with a re-measurement "+ + "behind it.", + name, ref, Pin, + ) + } } } diff --git a/scripts/pgtle-wrap.sh b/scripts/pgtle-wrap.sh index 05694df..c01f8c2 100755 --- a/scripts/pgtle-wrap.sh +++ b/scripts/pgtle-wrap.sh @@ -5,6 +5,13 @@ # the output is generated where needed, never published. # # pgtle-wrap.sh ... > out.sql +# pgtle-wrap.sh --update-from \ +# ... > out.sql +# +# The first form registers for CREATE EXTENSION; the +# second registers the -> update path for ALTER +# EXTENSION ... UPDATE. The update script is the same bundle: the +# installer is idempotent and resyncs what it ships. # # The artifacts run unchanged. Pass the plain ones, never a -tx # twin: a pg_tle script executes inside CREATE EXTENSION's own @@ -12,6 +19,12 @@ set -eu +from= +if [ "$1" = --update-from ]; then + from=$2 + shift 2 +fi + name=$1 version=$2 shift 2 @@ -36,9 +49,14 @@ if grep -qF "\$$tag\$" "$tmp"; then exit 1 fi -printf "SELECT pgtle.install_extension(\n" -printf " '%s',\n '%s',\n 'CEL for PostgreSQL',\n" \ - "$name" "$version" +if [ -n "$from" ]; then + printf "SELECT pgtle.install_update_path(\n" + printf " '%s',\n '%s',\n '%s',\n" "$name" "$from" "$version" +else + printf "SELECT pgtle.install_extension(\n" + printf " '%s',\n '%s',\n 'CEL for PostgreSQL',\n" \ + "$name" "$version" +fi printf '$%s$\n' "$tag" cat "$tmp" printf '$%s$\n);\n' "$tag" diff --git a/scripts/upgrade-check.sh b/scripts/upgrade-check.sh new file mode 100755 index 0000000..5a6fd9e --- /dev/null +++ b/scripts/upgrade-check.sh @@ -0,0 +1,175 @@ +#!/usr/bin/env sh +# Upgrade a database from the previous release to this checkout's +# build, and leave it running for the conformance suite. +# +# upgrade-check.sh +# +# holds the previous release's published artifacts +# (cel4postgres--.sql and SHA256SUMS, verified here); dist/ +# holds this checkout's, from scripts/build-release.sh. is +# the pinned postgres image for plain, the pg_tle image for pgtle. +# +# Each channel installs N-1 the way a consumer did, registers a +# consumer overload of its own, runs the upgrade, and asserts that +# the schema reports the new version and the consumer row both +# survived and still evaluates. The caller then runs the suite +# against 127.0.0.1: -- an upgraded database has to be as +# conformant as a fresh one -- and removes the container, named +# cel-upgrade-. +# +# The upgrade itself is the new installer run over the old schema: +# the installer is idempotent and resyncs every row it ships. A +# release that needs drops or signature changes ships a delta script +# that runs first; none exists yet. + +set -eu + +cd "$(dirname "$0")/.." + +channel=$1 +image=$2 +prev_dir=$3 +port=$4 + +version() { + sed -n "s/^VALUES ('\([0-9][0-9.]*\)')$/\1/p" "$1" +} + +head=$(version sql/000_install.sql) +prev_file=$(ls "$prev_dir"/cel4postgres--*.sql) +prev=$(basename "$prev_file" .sql | sed 's/^cel4postgres--//') +head_file="dist/cel4postgres--$head.sql" + +(cd "$prev_dir" && sha256sum --check --ignore-missing SHA256SUMS) +[ -f "$head_file" ] || { + echo "$head_file is missing; run scripts/build-release.sh" >&2 + exit 1 +} + +echo "upgrade $prev -> $head through the $channel channel" + +if [ "$prev" = "$head" ] && [ "$channel" = pgtle ]; then + # pg_tle has no update path from a version to itself. Say so in + # the log instead of passing quietly: this happens only between a + # release and the commit that numbers the next one. + echo "::warning::$head is already released; nothing to upgrade" \ + "through pg_tle until sql/000_install.sql is renumbered" +fi + +name="cel-upgrade-$channel" +docker rm -f "$name" >/dev/null 2>&1 || true + +args= +[ "$channel" = pgtle ] && args='-c shared_preload_libraries=pg_tle' +# shellcheck disable=SC2086 +docker run -d --name "$name" \ + -e POSTGRES_DB=cel -e POSTGRES_USER=cel -e POSTGRES_PASSWORD=pw \ + -p "127.0.0.1:$port:5432" "$image" $args >/dev/null + +# -h 127.0.0.1: over the socket, pg_isready can reach initdb's +# temporary server; only the final one listens on TCP. +for _ in $(seq 60); do + docker exec "$name" pg_isready -h 127.0.0.1 -U cel -d cel -q \ + 2>/dev/null && break + sleep 2 +done + +sql() { + docker exec -i -e PGOPTIONS='-c client_min_messages=warning' \ + "$name" psql -h 127.0.0.1 -U cel -d cel -v ON_ERROR_STOP=1 \ + -q "$@" +} + +expect() { + got=$(sql -tAc "$1") + if [ "$got" != "$2" ]; then + echo "$1" >&2 + echo " returned: $got" >&2 + echo " expected: $2" >&2 + exit 1 + fi +} + +# -- install N-1 ----------------------------------------------------- + +case $channel in + plain) + sql -1 -f - <"$prev_file" + ;; + pgtle) + sql -c 'CREATE EXTENSION pg_tle' + ./scripts/pgtle-wrap.sh cel4postgres "$prev" "$prev_file" | sql -f - + sql -c "CREATE EXTENSION cel4postgres VERSION '$prev'" + ;; + *) + echo "unknown channel $channel" >&2 + exit 1 + ;; +esac +expect 'SELECT cel.version()' "$prev" + +# -- a consumer registration the upgrade must not touch ------------- +# +# Its own schema, its own env, an overload id the installer never +# ships: everything an upgrade has to leave alone. + +sql <<'SQL' +CREATE SCHEMA consumer; + +CREATE FUNCTION consumer.shout(args jsonb[]) +RETURNS jsonb +LANGUAGE sql +IMMUTABLE PARALLEL SAFE +AS $$ + SELECT jsonb_build_object('@t', 'string', 'v', upper(args[1] ->> 'v')); +$$; + +INSERT INTO cel.env (name) VALUES ('consumer'); + +INSERT INTO cel.overload + (id, function, member, arg_types, result_type, impl, ordinal) +VALUES + ('consumer_shout_string', 'shout', false, '[{"kind": "string"}]', + '{"kind": "string"}', 'consumer.shout(jsonb[])', 10); + +INSERT INTO cel.env_item (env, kind, ref) +VALUES ('consumer', 'overload', 'consumer_shout_string'); +SQL + +probe="SELECT cel.evaluate('shout(\"cel\")', '{}', 'standard,consumer')" +want='{"v": "CEL", "@t": "string"}' +expect "$probe" "$want" + +# -- upgrade -------------------------------------------------------- + +case $channel in + plain) + sql -1 -f - <"$head_file" + ;; + pgtle) + if [ "$prev" != "$head" ]; then + ./scripts/pgtle-wrap.sh --update-from "$prev" \ + cel4postgres "$head" "$head_file" | sql -f - + sql -c "ALTER EXTENSION cel4postgres UPDATE TO '$head'" + fi + expect "SELECT extversion FROM pg_extension + WHERE extname = 'cel4postgres'" "$head" + ;; +esac + +expect 'SELECT cel.version()' "$head" +expect "SELECT count(*) FROM cel.overload + WHERE id = 'consumer_shout_string'" 1 +expect "$probe" "$want" + +# Nothing the upgrade did not ship into standard may end up there: +# not the consumer's overload, and not an extension's items. +expect "SELECT count(*) FROM cel.env_item + WHERE env = 'standard' AND ref = 'consumer_shout_string'" 0 +expect "SELECT count(*) FROM cel.env_item s + WHERE s.env = 'standard' AND EXISTS ( + SELECT FROM cel.env_item o + WHERE o.kind = s.kind AND o.ref = s.ref + AND o.env <> 'standard')" 0 + +echo "upgraded $prev -> $head; consumer registration intact" diff --git a/sql/010_registry.sql b/sql/010_registry.sql index 3d091c4..5f179cc 100644 --- a/sql/010_registry.sql +++ b/sql/010_registry.sql @@ -157,6 +157,45 @@ AS $$ ); $$; +-- The core scripts put "everything registered so far" into the +-- standard env. On a fresh install that is exactly the core: the +-- extension scripts run later. Run again over an installed schema -- +-- which is what an upgrade is -- the same sweep would also catch +-- every extension row and every consumer row, enabling them in +-- standard. A row is only swept when no env claims it yet and, if it +-- has an implementation, that implementation lives in the cel +-- schema. +CREATE OR REPLACE FUNCTION cel._unclaimed(kind text, ref text, + impl regprocedure) +RETURNS boolean +LANGUAGE sql +STABLE +SET search_path = cel, pg_temp +AS $$ + SELECT NOT EXISTS ( + SELECT FROM cel.env_item i + WHERE i.kind = _unclaimed.kind AND i.ref = _unclaimed.ref + ) + AND (impl IS NULL + OR (SELECT pronamespace FROM pg_proc WHERE oid = impl) + = 'cel'::regnamespace); +$$; + +-- Repair for schemas reinstalled before that guard existed (0.0.2 +-- and earlier): drop from standard what a shipped extension env +-- also lists. On a fresh install nothing matches -- no shipped item +-- is in two envs. A consumer row swept the same way cannot be told +-- apart from one put in standard on purpose, so it stays. +DELETE FROM cel.env_item s +WHERE s.env = 'standard' + AND EXISTS ( + SELECT FROM cel.env_item o + WHERE o.kind = s.kind AND o.ref = s.ref + AND o.env IN ('strings', 'math', 'lists', 'encoders', + 'bindings', 'two_var_comprehensions', + 'optionals', 'network') + ); + -- The spec-conformant default environment. Its items are seeded by -- the scripts that create the functions they reference. The -- identifier-escape syntax (`a-b`) is part of standard parsing diff --git a/sql/030_parse.sql b/sql/030_parse.sql index 9e18dcd..a3c981c 100644 --- a/sql/030_parse.sql +++ b/sql/030_parse.sql @@ -2091,6 +2091,8 @@ ON CONFLICT (name, arity, member) DO UPDATE SET expander = excluded.expander; INSERT INTO cel.env_item (env, kind, ref) SELECT 'standard', 'macro', format('%s/%s/%s', name, arity, member::int) FROM cel.macro +WHERE cel._unclaimed('macro', + format('%s/%s/%s', name, arity, member::int), expander) ON CONFLICT DO NOTHING; -- Parses CEL source under an environment. Returns the AST envelope, diff --git a/sql/060_stdlib.sql b/sql/060_stdlib.sql index 8e8715b..59352d3 100644 --- a/sql/060_stdlib.sql +++ b/sql/060_stdlib.sql @@ -790,10 +790,12 @@ ON CONFLICT (name) DO NOTHING; -- Everything above is visible in the standard env. INSERT INTO cel.env_item (env, kind, ref) SELECT 'standard', 'overload', id FROM cel.overload +WHERE cel._unclaimed('overload', id, impl) ON CONFLICT DO NOTHING; INSERT INTO cel.env_item (env, kind, ref) SELECT 'standard', 'type', name FROM cel.type +WHERE cel._unclaimed('type', name, NULL) ON CONFLICT DO NOTHING; -- Part 2: type conversions and string functions. Conversion @@ -1270,4 +1272,5 @@ ON CONFLICT (id) DO UPDATE SET INSERT INTO cel.env_item (env, kind, ref) SELECT 'standard', 'overload', id FROM cel.overload +WHERE cel._unclaimed('overload', id, impl) ON CONFLICT DO NOTHING; diff --git a/sql/070_wkt.sql b/sql/070_wkt.sql index e598a7e..19c89be 100644 --- a/sql/070_wkt.sql +++ b/sql/070_wkt.sql @@ -870,8 +870,10 @@ ON CONFLICT (id) DO UPDATE SET INSERT INTO cel.env_item (env, kind, ref) SELECT 'standard', 'type', name FROM cel.type WHERE name LIKE 'google.protobuf.%' + AND cel._unclaimed('type', name, NULL) ON CONFLICT DO NOTHING; INSERT INTO cel.env_item (env, kind, ref) SELECT 'standard', 'overload', id FROM cel.overload +WHERE cel._unclaimed('overload', id, impl) ON CONFLICT DO NOTHING;