Aleksei Sviridkin 36af0b0110 fix(postgres): skip a stale index while another session builds on its table (#5485)
## What this PR does

Refs #5459 (item 4)

The collation repair pass in the postgres init Job rebuilds each stale
index in its own psql session: it picks the index by OID, takes its name
and runs `REINDEX INDEX CONCURRENTLY <name>`. A rebuild started by a run
that hit its Job deadline keeps going, because its backend only notices
the lost client when the rebuild ends. The next run then lines up behind
that orphaned rebuild on the table lock. Once the orphan swaps in the
new index, the name resolves to the new, already rebuilt index and the
run rebuilds it a second time, holding its table until the new run's own
deadline. On PostgreSQL 17 the waiting run can also deadlock with the
orphan in its final phase, and the deadlock detector then throws away
the orphan's finished build.

This PR skips an index while `pg_stat_progress_create_index` shows
another backend building an index of its table (same database, other
pid). The skip is reported the same way as a failed rebuild, so the run
exits non-zero and the next run carries on. That next run finds the new
index above the resume mark and treats it as done.

The check is the first statement of the session. It runs before the
index is looked up by OID and its name taken, with the table taken from
`pg_index` by that OID. A rebuild that ended before the check has
already removed the index the session looks for, so `present` skips it.
An orphaned backend never starts another statement after the check, so
it cannot swap the index in between. As a result the check also runs
before:
- the `_ccnew` leftover count, which a build in progress would otherwise
inflate (it owns one invalid `_ccnew` index);
- the in-place attempt record of an exclusion constraint's index, so a
skip never counts towards leaving that index to an operator.

The resume mark, the fingerprint, the `_ccnew` leftover rule and the
`lock_timeout`/`statement_timeout` bounds are unchanged.

A build that a live session starts after the check, in the moment before
REINDEX takes its lock, is not covered: SQL has no way to REINDEX by
OID. Only an operator or a tenant racing the Job could hit that window,
because an orphaned rebuild cannot start a new statement.

### Screenshots

Not a UI change.

### Testing

- `helm unittest packages/apps/postgres`: 31 suites, 247 tests passed.
- `helm template` renders. The only change in the rendered `init.sh`
compared with `main` is the new check.
- Ran the repair section of the rendered `init.sh` from `main` and from
this branch in Docker (`postgres:17-trixie`). Each init-job run was a
separate container on the same network as the database, the way the Job
pod and the Cluster are. A run "hit its deadline" by having its
container removed while its `REINDEX INDEX CONCURRENTLY` was in the
`building index` phase. The index was made stale by setting `collversion
= '0'` for `en-x-icu`. The build was slowed deterministically with an
expression index over an ICU column through an immutable function that
sleeps 1 ms per row (about 2.5 minutes per build).
- `main`: run 2 logged `rebuilding index public.t_k` and waited behind
the orphaned build. The deadlock detector then cancelled the orphan
after its full build (`Process 135 waits for ShareLock on virtual
transaction ...; blocked by process 175`), and run 2 rebuilt the index
from scratch, so the index was built twice. In the field report on
PostgreSQL 18 the orphan finished instead, and the waiting run rebuilt
the fresh index a second time.
- this branch (check first in the session): run 2 failed at once with
`index public.t_k in database postgres was skipped: another session is
building an index of its table ...` and exit 1. The orphan finished
alone and the index got a new OID. Run 3 rebuilt nothing, refreshed the
collation version, reset the repair setting and exited 0, with no
invalid indexes left.
- Exclusion constraint index (in-place path) on this branch: while
another session ran `CREATE INDEX CONCURRENTLY` on the same table, the
run skipped the index without recording an in-place attempt. The next
run rebuilt it in place (same OID, new relfilenode) and exited 0.

- Dev cluster (cozystack v1.7.0): this branch's chart with
`17.12-standard-trixie` and 2 instances. A table of 300k rows with the
slow expression index over `en-x-icu`, so a `REINDEX INDEX CONCURRENTLY`
took about 12 minutes. `en-x-icu` was marked stale with `collversion =
'0'`.
- Upgrade 1 started the rebuild (`rebuilding index public.t_k ...`). Its
init Job was deleted mid-build, and the backend kept building after the
Job was gone.
- Upgrade 2 while that build ran: the init Job failed at once with
`index public.t_k in database postgres was skipped: another session is
building an index of its table ...`, without queueing behind the lock.
  - The orphaned build finished alone (index OID 16453 → 16464).
- Upgrade 3: the init Job completed in 10 s with no `rebuilding` line.
The OID stayed 16464, the collation version was refreshed,
`cozystack.collation_repair` was reset, and no invalid indexes were
left.

### Downstream repositories

Walked the trigger map against the diff. The PR changes only
`packages/apps/postgres/templates/init-script.yaml` (SQL inside the init
Job script). It touches no values, schema, README,
ApplicationDefinition, package layout, `hack/`, platform keys or names
that any listed repository mirrors.

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

### Release note

```release-note
[postgres] The init Job's collation repair no longer rebuilds an index a second time, or deadlocks with a rebuild left running by an earlier run that hit its deadline; it skips an index while another session builds an index of its table, and the next run of the Job carries on.
```


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

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

## Summary by CodeRabbit

* **Bug Fixes**
* Collation repair now detects when another session is building a
planned index and reports an error identifying the index and database.
The database’s repair failure is recorded, rather than proceeding to
inspect or rebuild the index during the concurrent operation. This makes
the conflict visible in the repair results.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-27 18:21:49 +03:00
2026-11-27 18:31:07 +05: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.1%
Shell 33%
TypeScript 6.8%
Go Template 4.6%
Makefile 1.3%
Other 1.1%