Aleksei Sviridkin c8ffc87717 fix(postgres): run the collation repair outside the Helm hook (#5479)
## What this PR does

Refs #5459 (item 3: "Waiting for rollout eats Job budget").

**Depends on #5505.** Merge #5505 first or together with this PR. Here a
failed repair no longer fails the HelmRelease. #5505 makes the
WorkloadMonitor report the failed repair Job as `WorkloadsReady=False`
with reason `JobFailed`. Without it the failure shows only on the Job
itself.

Moving tenant PostgreSQL to another image (for example bullseye `17.7`
to `17.12-standard-trixie`) fails the first Helm upgrade of every
release whose clients keep sessions open. The collation repair at the
end of the post-upgrade init-job waits for CNPG to move the primary to
the new image. CNPG rolls the primary last, and every instance spends up
to `smartShutdownTimeout` (180 s) in smart shutdown, so the wait uses up
the init-job's 540 s deadline and the HelmRelease goes `UpgradeFailed`
until Flux retries. When the repair instead meets the primary restart,
psql fails with `FATAL: the database system is shutting down` and the
upgrade fails the same way.

The one commit moves the repair out of the hook. A short
post-install/post-upgrade hook, run after the init-job, creates a
`<release>-collation-repair` Job through the API (outside the release,
so helm-controller does not wait for it) and returns. That Job keeps the
OID mark / fingerprint resume and the in-place attempt records. It waits
for the new image whenever the image changes, not only when an index
already depends on a versioned collation: a plan built on the previous
primary would miss an index created meanwhile, which the release
recorded at the end would then claim as repaired. In the hook that wait
was too expensive to make unconditional. The Job gets an hour, is owned
by the Cluster, and its fixed name keeps two repairs from running at
once. It carries the WorkloadMonitor's selector labels plus the opt-in
`workloads.cozystack.io/report-failure: "true"` from #5505, and has no
`ttlSecondsAfterFinished`, so a failed repair stays until the next
upgrade replaces it (see the proposal in #5459). Both Jobs now rerun
their idempotent script on psql exit status 2 (connection refused or
dropped) with backoff instead of failing.

Decisions for reviewers:

- **Repair failures no longer fail the HelmRelease.** A repair that
cannot finish (for example duplicates under a UNIQUE index) shows up as
a Failed `<release>-collation-repair` Job and its log, kept until the
next upgrade starts a new run. The next upgrade retries it. Before, it
showed up as `UpgradeFailed`.
- **The repair also runs after install.** The install-time init-job used
to record which Debian release each database starts on. Without that
record, a cluster whose first upgrade moves the image would have its C.*
indexes rebuilt only if the repair reached the primary before it
restarted. On a fresh cluster the run only writes that record. The Job
sets `PGCONNECT_TIMEOUT=10`.
- **A failed rebuild no longer holds back the PostGIS update.** The
update runs after the collation pass whatever it found, and the Job
still fails at the end if a rebuild failed.
- **The e2e upgrades twice.** The second upgrade finds the first repair
Job complete on the same image, and the test waits for its replacement
to complete.
- **Lock waits are bounded by the Job's remaining hour, not about 8
minutes.** This is harmless for `REINDEX CONCURRENTLY`. For the in-place
rebuild of an exclusion-constraint index, writers to that table can
queue behind its lock wait for longer. Capping it separately means
touching the per-index code that the parallel PRs on #5459 also edit, so
I left it out.
- **The hook's Role** has `get`/`delete` on the repair Job and `get` on
the release's Cluster, both by `resourceNames`. It also has `create` on
jobs, which RBAC cannot narrow by name. The SA, Role and RoleBinding are
deleted once the hooks succeed.
- **Verified under Flux.** helm-controller v1.5.0 runs the post-upgrade
hooks about a second after it patches the Cluster, without waiting for
the rollout. The rollout therefore no longer counts against the release
timeout. Details in the PR thread.

Rebased onto main after #5477 and #5485. The PostGIS extension update
from #5477 waits for the same rollout, so it moves into `repair.sh`
after the collation pass; left in the init-job, it would bring the
hook-budget problem back for postgis clusters. Every message about a
repair or update that did not finish says that the next upgrade of the
release starts it again. The starter and the repair Job take their names
from one base, which stays distinct and within 63 characters for any
release name.

### Testing

- `helm unittest packages/apps/postgres`: 32 suites, 257 tests pass,
including a new `collation_repair_test.yaml`. It checks gating (upgrade
only, skipped while bootstrap is on), hook order after the init-job, the
Role rules, RBAC removal on success, name length, and the init-job
command.
- Docker, with the rendered `run.sh` + `repair.sh` against
`postgres:17-bullseye` and stale ICU / en_US collations:
- Killing the `REINDEX INDEX CONCURRENTLY` backend mid-rebuild made the
pass exit 2. `run.sh` reran it, the already rebuilt index was skipped by
the OID mark, and the other index was rebuilt. amcheck was clean and the
versions were refreshed.
- With the server stopped before the first connection, the script
retried with 5 s and 10 s pauses and finished once the server came back.
  - An SQL error exits 1 and is not retried.
- dev7 (cozystack v1.7.0): two 3-instance v17 releases installed from
v1.7.1 (bullseye `17.7`), with ICU and en_US UNIQUE indexes on 200k rows
and `pg_sleep(3600)` sessions held on `-rw` and `-ro`. Both were
upgraded with `helm upgrade --timeout 10m`:
- origin/main: the init-job waited for `PostgreSQL 17.12 pgdg13`, hit
`DeadlineExceeded`, and the command failed with `UPGRADE FAILED:
post-upgrade hooks failed: resource Job/tenant-root/rr-main-init-job not
ready. status: Failed` (exit 1 after 611 s).
- This branch: exit 0 after 70 s (init-job 9 s, starter 10 s, starter
RBAC removed afterwards). The repair Job waited out the rollout and
rebuilt `t_u` and `t_k`. Collation versions were refreshed to `2.41` /
`153.128`, `bt_index_check(..., true)` passed on all three instances,
and the resume mark was reset.
- A second upgrade replaced the finished repair Job, and the rerun found
nothing to do.
- The rebuild sat in `waiting for old snapshots` behind the test
client's open transaction. That is expected for `REINDEX CONCURRENTLY`;
I ended that session to finish the run.

### Downstream repositories

Walked against the diff (the new template, test and init-script/init-job
changes in `packages/apps/postgres`). The diff changes no values,
schema, `ApplicationDefinition`, Secret or Service names, package
layout, or tooling. The only new objects are a hook-scoped
ServiceAccount/Role/RoleBinding/Job and a Job created at runtime, which
no listed repository refers to.

- [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:

- Flux (dev cluster, helm-controller v1.5.0): a tenant app on the v1.7.0
chart (bullseye `17.7`, 3 instances, sessions held on `-rw`/`-ro`) was
upgraded by switching the platform's postgres chart.
- With this PR, the HelmRelease reached `UpgradeSucceeded` in 21 s, and
the repair Job finished after the rollout with `bt_index_check` clean on
all instances.
  - With main, the upgrade took 7 min 06 s of the 10-minute timeout.
- Docker: the rendered `repair.sh` for the postgis flavor moved PostGIS
3.6.1 → 3.7.0 after the collation pass. A tenant trigger on
`spatial_ref_sys` did not run.

### Release note

```release-note
[postgres] An image change of a tenant PostgreSQL no longer fails the Helm upgrade while CNPG rolls the instances. The collation repair now runs in a separate `<release>-collation-repair` Job, started after each upgrade, which waits for the new image and retries after connection drops. Check that Job's status and log to confirm the repair finished.
```
2026-11-30 18:24:14 +03:00
2026-11-04 00:56:56 +01:00
2025-10-08 09:43:34 +05:00
2024-02-08 12:04:32 +01:00

Cozystack Cozystack

GitHub Release Apache-2.0 License Commit activity OpenSSF Best Practices OpenSSF Scorecard CLOMonitor Support

Cozystack

Cozystack is a free and open-source platform and framework for building clouds.

Cozystack is a CNCF Sandbox project that was originally built and sponsored by Ænix.

With Cozystack, you can transform a bunch of servers into an intelligent system with a simple REST API for spawning Kubernetes clusters, Database-as-a-Service, virtual machines, load balancers, HTTP caching services, and other services with ease.

Use Cozystack to build your own cloud or provide a cost-effective development environment.

Cozystack user interface

Use-Cases

Documentation

The documentation is located on the cozystack.io website.

Read the Getting Started section for a quick start.

If you encounter any difficulties, start with the troubleshooting guide and work your way through the process that we've outlined.

Versioning

Versioning adheres to the Semantic Versioning principles.
A full list of the available releases is available in the GitHub repository's Release section.

Contributions

Contributions are highly appreciated and very welcomed!

In case of bugs, please check if the issue has already been opened by checking the GitHub Issues section. If it isn't, you can open a new one. A detailed report will help us replicate it, assess it, and work on a fix.

You are welcome to take on the fix yourself. Commits are used to generate the changelog, and their author will be referenced in it.

If you have a concrete feature request, open an issue. For a cross-cutting or architectural change, open a design proposal in the community repo. For questions or early ideas, use GitHub Discussions. See CONTRIBUTING.md for the full routing.

Community

You are welcome to join us in #cozystack, on either CNCF Slack (get an invite) or Kubernetes Slack (get an invite), in our Telegram group, and at our community meetings. Add them to your Google Calendar or iCal for convenience.

Project documents

Document What it covers
Governance How decisions are made and who makes them
Contributor Ladder How to grow from contributor to maintainer
Maintainers Who maintains the project
Code of Conduct What we expect of each other
Security Policy Reporting a vulnerability, and which releases get fixes
Adopters Who runs Cozystack in production
Roadmap Where the project is going

License

Cozystack is licensed under Apache 2.0.
The code is provided as-is with no warranties.

Commercial Support

A list of companies providing commercial support for this project can be found on official site.

Languages
Go 53%
Shell 33.2%
TypeScript 6.7%
Go Template 4.7%
Makefile 1.3%
Other 1%