fix(postgres): update PostGIS extensions after an image upgrade (#5477)

## What this PR does

Refs #5459 (item 2)

After an upgrade that moves a `postgis` flavor Postgres to a new PostGIS
release (3.6.1 to 3.7.0 for v14-v18 on the current `main`), the PostGIS
library is new but the SQL objects in every database stay on the old
release: `postgis_full_version()` reports `core procs from "3.6.1 ..."
need upgrade`. The release notes tell users to run `ALTER EXTENSION
postgis UPDATE`, but the init Job created the extensions as the
superuser, so the tenant gets `must be owner of extension postgis` and
has no way to run the update.

The init Job now runs that update. It covers `postgis`,
`postgis_raster`, `postgis_topology`, `postgis_sfcgal`,
`postgis_tiger_geocoder`, `address_standardizer` and
`address_standardizer_data_us` in every connectable database where they
are installed:

- The target is the `default_version` the server offers, so the pass
only runs once the server is on the new image. If the server is already
up to date, it does nothing.
- Helm starts the hook while CNPG is still rolling the instances. The
pass waits until the server offers the PostGIS version that the Job's
own image ships, and stops waiting 120 s before the Job deadline (the
same bound the collation pass uses).
- If the rollout is slower than that, the Job fails. The init Job is a
hook, so a run that ends well does not come again before the next change
of the release; a failed one makes the release retry once the server
runs the new image. The version probe is bounded by `timeout 10`.
- `postgis_extensions_upgrade()` is not used: it leaves out
`address_standardizer`, and on every call it updates each installed
extension to `ANY` and back, even when nothing changed. Each extension
gets `ALTER EXTENSION ... UPDATE TO <server default_version>`, with
`postgis` first. Each session pins `search_path` to `pg_catalog,
pg_temp`.
- If the image ships no update path for an extension, the pass prints a
warning and leaves it alone. The check uses `pg_extension_update_paths`.
- A tenant transaction can hold a lock an update needs, and one update
can wait for several in turn. Before each `ALTER EXTENSION`, the session
therefore sets `statement_timeout` and `lock_timeout` to what is left of
the Job, keeping the same one-minute reserve as the collation pass. So
every update, lock waits included, ends before the Job does. A database
reached with no time left counts as failed.
- The update scripts run as the superuser and write to tables a tenant's
admin role is granted `ALL` on, `spatial_ref_sys` among them (the
PostGIS 3.7 script inserts into it). A trigger the tenant attached there
would run with the superuser's privileges.
- The update session therefore sets `session_replication_role =
replica`, so triggers enabled the default way (`ENABLE ORIGIN`, what
`CREATE TRIGGER` gives) do not fire.
- Only the table's owner, the superuser, can enable a trigger `ALWAYS`
or `REPLICA`. A database where such a trigger sits on a table of these
extensions is not updated and is reported.
- A database whose extensions cannot be looked up counts as failed, and
the pass continues with the others.
- If an update fails, the other databases are still processed and then
the Job fails. Under `RetryOnFailure` the release is retried and shows
as failed, so the error does not get lost in the log of a Job that is
deleted an hour later. The pass runs after the collation repair, so a
failure here cannot block index rebuilds.
- The section is rendered only for `flavor: postgis`. For the
`postgresql` flavor, the rendered `init.sh` is byte-identical to `main`.

**Needs a separate decision:** PostGIS 3.7 renamed the
`address_standardizer` library (`address_standardizer-3.so` became
`address_standardizer.so`) and ships no update path from 3.6.1. As a
result, an `address_standardizer` created under 3.6.1 fails after the
upgrade with `could not access file "$libdir/address_standardizer-3"`.
`ALTER EXTENSION` cannot fix this; only `DROP EXTENSION` followed by
`CREATE EXTENSION` as the superuser can. This PR only reports it.
Whether the Job should drop and recreate the extension (which risks
tenant objects that depend on it) is left to reviewers.

### Testing

- Docker, rendered `init.sh` (`helm template --set flavor=postgis`) run
with the Job's environment on the `17.12-3.7.0-standard-trixie` image:
- Run against a server still on `17.7-3.6.1`: it waited, printed "the
server did not move to PostGIS 3.7.0 in time … failing the init-job" and
exited 1.
- A tenant transaction held open on `geography_columns` in `appdb`, with
`JOB_DEADLINE=85`:
- the update in `appdb` was cancelled when the budget ran out
(`canceling statement due to statement timeout`, 25 s);
    - `db2`, reached with no time left, was reported as not updated;
    - the Job exited 1 after 25 s;
- after the blocker ended, the next run updated both databases to 3.7.0
and exited 0;
    - a further run was a no-op.
- Tenant trigger: as a non-superuser `appdb_admin` granted `ALL` on
`public` tables, a `BEFORE INSERT ... FOR EACH STATEMENT` trigger on
`spatial_ref_sys` whose function runs `ALTER ROLE appdb_admin
SUPERUSER`.
    - Without the guard, the update made `appdb_admin` a superuser.
- With it, the update to 3.7.0 passed and `appdb_admin` stayed
non-superuser.
- With the same trigger set `ENABLE ALWAYS` (superuser only), the
database was skipped with an error, the Job exited 1, and the role
stayed non-superuser.
- The same data directory restarted on `17.12-3.7.0`: `postgis`,
`postgis_raster`, `postgis_topology` and `postgis_sfcgal` went from
3.6.1 to 3.7.0 and `postgis_tiger_geocoder` from 3.6.1 to 2025.2 in
`appdb`; `postgis` went to 3.7.0 in a second database. Afterwards
`postgis_full_version()` no longer reports "need upgrade". The md5 of a
spatial join and area query was the same before and after.
  - A second run was a no-op.
- A database with a planted conflicting object failed with `function
st_x(geometry) is not a member of extension "postgis"`. The other
database was still updated, and the Job exited 1.
- `flavor: postgresql`: the rendered `init.sh` is identical to `main`.
- `helm unittest packages/apps/postgres`: 31 suites, 247 tests passed.
- Dev cluster: v1.7.1 chart installed (postgis, v17, 2 replicas,
`postgis` in `appdb` at 3.6.1), then `helm upgrade` to this branch:
- The first attempt passed (exit 0). The Job logged `waiting for the
server to offer PostGIS 3.7.0`, then `updating extension postgis in
database appdb from 3.6.1 to 3.7.0`.
- Afterwards the image is `17.12-3.7.0-standard-trixie` and `postgis` is
3.7.0, with no "need upgrade" left. A spatial query gave the same md5 as
before.
  - A second upgrade left the PostGIS section empty.

**This change is verified only by hand** (Docker and the dev cluster
above). No e2e suite upgrades a postgis-flavor release, and one cannot
be added without an upgrade harness.

### Downstream repositories

The diff only touches
`packages/apps/postgres/templates/init-script.yaml`. It adds no values
key, schema field, version enum, default, app, CRD, hack script or
naming change, so none of the triggers in the map apply.

- [x] No downstream repository is affected by this change
- [ ] [cozystack/website](https://github.com/cozystack/website) -
follow-up:
- [ ]
[cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack)
- follow-up:
- [ ]
[cozystack/ansible-cozystack](https://github.com/cozystack/ansible-cozystack)
- follow-up:
- [ ] [cozystack/ccp](https://github.com/cozystack/ccp) - follow-up:
- [ ] [cozystack/talm](https://github.com/cozystack/talm) - follow-up:
- [ ] [cozystack/cozyhr](https://github.com/cozystack/cozyhr) -
follow-up:
- [ ] [cozystack/cozy-proxy](https://github.com/cozystack/cozy-proxy) -
follow-up:
- [ ]
[cozystack/cozystack-telemetry-server](https://github.com/cozystack/cozystack-telemetry-server)
- follow-up:
- [ ]
[cozystack/external-apps-example](https://github.com/cozystack/external-apps-example)
- follow-up:
- [ ] [cozystack/examples](https://github.com/cozystack/examples) -
follow-up:
- [ ] [cozystack/community](https://github.com/cozystack/community) -
follow-up:

If a release note on the website tells users to run `ALTER EXTENSION
postgis UPDATE` by hand, that note becomes obsolete. I did not find such
a note in the trigger map and did not search the website repository.

### Release note

```release-note
[postgres] The init Job of a postgis-flavor Postgres now updates the PostGIS extensions in every database once the server runs the new image, so tenants no longer get "must be owner of extension postgis" or stay on outdated PostGIS SQL objects after an upgrade. An address_standardizer created under PostGIS 3.6 has no update path to 3.7 and is reported, not changed.
```


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Improvements**
* For PostGIS jobs, installed extensions are checked and updated to the
version available in the job environment, with dependencies handled in
order.
* The process waits for the required PostGIS version and skips
extensions without a supported update path, reporting a warning.
* Databases with relevant always-enabled or replica triggers are
rejected. Checks and updates are bounded by the job deadline; failures
are collected across databases, and the job reports an error if any
database could not be checked or updated.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
Aleksei Sviridkin authored and GitHub committed 2026-11-27 18:27:52 +03:00
commit 8e5600d5e3
1 file changed
+118 -2
@@ -611,8 +611,9 @@ stringData:
This pass comes after the ones that manage roles and databases, so
that a rebuild that fails, or does not finish before the Job deadline,
costs none of them. Only the record of an adopted restore follows it:
that record must not be written by a run that failed.
costs none of them. Only the PostGIS update and the record of an
adopted restore follow it: that record must not be written by a run
that failed.
Helm runs this hook as soon as the Cluster is patched, while CNPG is
still rolling the instances, so the primary may answer from the previous
@@ -855,6 +856,121 @@ stringData:
echo "index rebuilds failed in:$COLLATION_FAILED (the errors are above); the other indexes were rebuilt. A unique index cannot be rebuilt over rows that the previous ordering kept apart and the new one treats as equal, so remove such duplicates. The next run of the init-job tries again, except for an index an error above reports as left alone" >&2
exit 1
fi
{{- if eq .Values.flavor "postgis" }}
{{- /*
A new PostGIS library leaves the SQL objects of every database on the
release they were installed with until ALTER EXTENSION ... UPDATE runs
there, and postgis_full_version() reports them as needing an upgrade
meanwhile. The extensions were created in this Job's superuser session,
so only the superuser owns them and can update them; a tenant gets
"must be owner of extension". This pass updates them in every database
where they are installed, including ones values no longer list.
The target is the version the server offers, never one rendered here,
so a database only moves to what the running library implements, and
a database already on it is left alone. While CNPG is still rolling the
instances the server offers the previous release and there is nothing
to update yet, so the pass first waits for the server to offer the
PostGIS release the Job's own image ships, until 120 seconds before
the Job's deadline. A rollout that takes longer fails the Job: this Job
is a hook, so a run that ended well would not come again before the
next change of the release, while a failed one makes the release retry.
postgis_extensions_upgrade() is not used: it leaves out
address_standardizer, and it updates every installed extension to ANY
and back on each call, even when nothing changed. Each extension is
updated on its own instead, postgis before the ones that require it,
in sessions that pin search_path as the collation pass does. A version
the image ships no update path from is reported and left as it is: the
address_standardizer of PostGIS 3.7 has none from earlier releases.
ALTER EXTENSION is transactional, so an update that fails leaves its
extension as it was. A tenant transaction can hold a lock an update
needs, and one update can wait for several of them in turn, so each
update, its lock waits included, runs no longer than what is left of
the Job, with the same minute in reserve as the collation pass, and a
database reached with no time left counts as failed. The pass carries
on with the other databases and then fails the Job, so that the
release is retried and reported as failed instead of the error staying
in the log of a Job that is deleted an hour later.
The update scripts run as the superuser and write to tables a tenant's
admin role may attach triggers to (spatial_ref_sys among them), and a
trigger runs with the privileges of the session that fires it. The
update session therefore runs with session_replication_role = replica,
under which triggers enabled the default way do not fire; only a
table's owner, the superuser, can enable one ALWAYS or REPLICA, and a
database where such a trigger sits on a table of these extensions is
not updated.
*/}}
echo "== update postgis extensions"
POSTGIS_SHIPPED=$(sed -n "s/^default_version *= *'\([^']*\)'.*/\1/p" "$(pg_config --sharedir)/extension/postgis.control")
postgis_offered() {
timeout 10 psql -t -A -c "SELECT default_version FROM pg_catalog.pg_available_extensions WHERE name = 'postgis'" 2>/dev/null
}
ALL_DBS=$(psql -v ON_ERROR_STOP=1 -t -A -c "SELECT datname FROM pg_database WHERE datallowconn AND NOT datistemplate")
POSTGIS_DBS=""
POSTGIS_FAILED=""
for db in $ALL_DBS; do
if ! installed=$(psql -v ON_ERROR_STOP=1 -q -t -A --dbname "$db" -c "SET search_path = pg_catalog, pg_temp" -c "SELECT count(*) FROM pg_extension WHERE extname IN ('postgis', 'postgis_raster', 'postgis_topology', 'postgis_sfcgal', 'postgis_tiger_geocoder', 'address_standardizer', 'address_standardizer_data_us')"); then
echo "the PostGIS extensions in database $db were not checked (the error is above); the next run of the init-job carries on" >&2
POSTGIS_FAILED="$POSTGIS_FAILED $db"
continue
fi
if [ "$installed" != 0 ]; then
POSTGIS_DBS="$POSTGIS_DBS $db"
fi
done
if [ -n "$POSTGIS_DBS" ] && [ -n "$POSTGIS_SHIPPED" ] && [ "$(postgis_offered)" != "$POSTGIS_SHIPPED" ]; then
echo "waiting for the server to offer PostGIS $POSTGIS_SHIPPED"
until [ "$(postgis_offered)" = "$POSTGIS_SHIPPED" ]; do
if [ "$SECONDS" -ge $((JOB_DEADLINE - 120)) ]; then
echo "the server did not move to PostGIS $POSTGIS_SHIPPED in time (check the rollout of the cnpg.io/Cluster); the PostGIS extensions are not updated yet - failing the init-job, the next run of it updates them" >&2
exit 1
fi
sleep 5
done
fi
for db in $POSTGIS_DBS; do
LEFT=$((JOB_DEADLINE - SECONDS - 60))
if [ "$LEFT" -lt 10 ]; then
echo "the PostGIS extensions in database $db were not updated: the init-job is out of time, the next run of it carries on" >&2
POSTGIS_FAILED="$POSTGIS_FAILED $db"
continue
fi
if ! psql -v ON_ERROR_STOP=1 -q -t -A --dbname "$db" -v lock_wait="${LEFT}s" <<\EOT
SET client_min_messages = warning;
SET search_path = pg_catalog, pg_temp;
SET lock_timeout = :'lock_wait';
SET session_replication_role = replica;
SELECT EXISTS (SELECT FROM pg_trigger t JOIN pg_depend d ON d.classid = 'pg_class'::regclass AND d.objid = t.tgrelid AND d.deptype = 'e' JOIN pg_extension x ON x.oid = d.refobjid WHERE NOT t.tgisinternal AND t.tgenabled IN ('A', 'R') AND x.extname IN ('postgis', 'postgis_raster', 'postgis_topology', 'postgis_sfcgal', 'postgis_tiger_geocoder', 'address_standardizer', 'address_standardizer_data_us')) AS armed \gset
\if :armed
SELECT format('DO %L', format('BEGIN RAISE EXCEPTION %L, %L; END', '%', format('the PostGIS extensions in database %s were not updated: a table of theirs carries a trigger enabled ALWAYS or REPLICA, which would run inside the superuser update; drop that trigger, and the next run of the init-job updates them', current_database()))) \gexec
\endif
SELECT clock_timestamp() + :'lock_wait'::interval AS deadline_at \gset
CREATE TEMP TABLE cozystack_postgis AS
SELECT e.extname, e.extversion, a.default_version, f.position,
EXISTS (SELECT FROM pg_extension_update_paths(e.extname) p WHERE p.source = e.extversion AND p.target = a.default_version AND p.path IS NOT NULL) AS reachable
FROM unnest(ARRAY['postgis', 'postgis_raster', 'postgis_topology', 'postgis_sfcgal', 'postgis_tiger_geocoder', 'address_standardizer', 'address_standardizer_data_us']::name[]) WITH ORDINALITY AS f(name, position)
JOIN pg_extension e ON e.extname = f.name
JOIN pg_available_extensions a ON a.name = e.extname
WHERE e.extversion <> a.default_version;
SELECT format('WARNING: extension %s in database %s stays at version %s: the image ships no update path from it to %s', extname, current_database(), extversion, default_version) FROM cozystack_postgis WHERE NOT reachable ORDER BY position;
SELECT format('updating extension %s in database %s from %s to %s', extname, current_database(), extversion, default_version) FROM cozystack_postgis WHERE reachable ORDER BY position;
SELECT format('DO %L', format('BEGIN PERFORM set_config(%L, greatest(1, floor(extract(epoch FROM %L::timestamptz - clock_timestamp()) * 1000))::bigint::text, false); PERFORM set_config(%L, current_setting(%L), false); END', 'statement_timeout', :'deadline_at', 'lock_timeout', 'statement_timeout')),
format('ALTER EXTENSION %I UPDATE TO %L', extname, default_version)
FROM cozystack_postgis WHERE reachable ORDER BY position \gexec
EOT
then
POSTGIS_FAILED="$POSTGIS_FAILED $db"
fi
done
if [ -n "$POSTGIS_FAILED" ]; then
echo "PostGIS extension updates failed in:$POSTGIS_FAILED (the errors are above); the extensions there stay at their previous version. The next run of the init-job tries again" >&2
exit 1
fi
{{- end }}
{{- if .Values.bootstrap.newServerName }}
echo "== record the adopted restore"