Skip to content

meta: probe databases over TCP in container healthchecks - #18291

Merged
WikiRik merged 3 commits into
mainfrom
meta/fix-flaky-db-healthchecks
Aug 13, 2026
Merged

WikiRik merged 3 commits into
mainfrom
meta/fix-flaky-db-healthchecks

Conversation

@WikiRik

@WikiRik WikiRik commented Jul 29, 2026 •

Copy link
Copy Markdown
Member

Problem

yarn start-postgres-{oldest,latest} fails intermittently in CI — roughly one job in twenty-four, always exactly one job of the postgres matrix. Recent examples: 30449391928, 30446403587, 30446392962, 30165843220.

All four failed with exit code 7, which is what Node produces when dev/check-connection.ts dies on ECONNREFUSED. The failing steps ran 24–36s against 16–22s for successful ones, so it is not the wait-until-healthy.sh timeout (that would be ~170s): the healthcheck passes, and then the connection is refused.

Cause

pg_isready -U sequelize_test has no -h, so it probes the unix socket. During initdb the postgres entrypoint runs a temporary bootstrap server that listens on the socket only, with an empty listen_addresses. The probe passes, the container is marked healthy, and nothing is listening on TCP yet.

Measured at the instant docker reported healthy, 4 runs out of 4:

init-complete=NO | TCP: 127.0.0.1:5432 - no response
                 | socket: /var/run/postgresql:5432 - accepting connections

CI volumes always start empty, so every job runs initdb and every job races. Whether the first probe lands inside that ~1–2s window is pure timing.

Fix

Probe over TCP, which the bootstrap server genuinely does not answer. Throttling the container to 0.15 CPU — what a loaded runner effectively looks like — makes the flake deterministic:

before after
postgres oldest 3/3 failed 0/3 failed
postgres latest 3/3 failed 0/3 failed

mysql and mariadb have the same defect: their entrypoints start the temporary server on the same socket path with --skip-networking, and sequelize_test is created while it is running. The window is far narrower — polling both probes across a full startup catches socket=ok tcp=fail for only 2 samples out of ~2200 — but it is real, so they get --protocol=TCP too. All four containers were confirmed to still reach healthy and connect.

The probe timeout also goes to 5s and gains a start_period, so a slow runner cannot mark a container unhealthy while it is legitimately still starting.

wait-until-healthy.sh

Three separate problems, all of which made these failures harder to diagnose than they should have been:

  • return_code=$? captured the exit status of the preceding echo, so it was always 0 and the check was dead code.
  • The timeout message claimed 20s; the loop actually ran for about 170s.
  • It waited out the full timeout even when the container had already exited, and printed nothing at all on failure — no logs, no probe output. This is why the CI job logs said nothing useful.

It now fails fast on an exited or missing container, reports the real timeout, and dumps .State.Health plus the last 50 log lines when it gives up. Output is also one line per state change rather than a \r redraw every second, which renders badly in Actions logs.

Reproducing locally

# override.yml:  services: {postgres-latest: {cpus: 0.15}}
docker volume rm -f sequelize-postgres-latest-volume
docker compose -p sequelize-postgres-latest -f docker-compose.yml -f override.yml up -d
dev/wait-until-healthy.sh sequelize-postgres-latest
DIALECT=postgres yarn ts-node dev/check-connection.ts   # exit 7 before this PR

The volume must be removed between runs, otherwise initdb is skipped and it always passes.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Improved database container health checks across supported MySQL, MariaDB, and PostgreSQL environments.
    • Made health checks more reliable by using explicit TCP-based readiness checks and updated timing behavior (longer timeouts, more retries, and added startup grace periods).
    • Strengthened the “wait for healthy” script with stricter validation, clearer failure modes, and less repetitive output.
    • On startup failure, now surfaces healthcheck results and recent container logs to speed up troubleshooting.

`yarn start-postgres-{oldest,latest}` fails intermittently in CI, roughly one
job in twenty-four, with exit code 7 — the exit code Node produces when
`dev/check-connection.ts` dies on `ECONNREFUSED`.

The healthcheck was the cause. `pg_isready -U sequelize_test` has no `-h`, so
it probes the unix socket. During `initdb` the postgres entrypoint runs a
temporary bootstrap server that listens on the socket only, with an empty
`listen_addresses`, so the probe passes and the container is reported healthy
while nothing is listening on TCP yet. `wait-until-healthy.sh` then returns and
`check-connection.ts` connects to the published port and is refused. CI volumes
are always empty, so every job runs `initdb` and every job races.

Measured at the instant docker reported healthy, 4 runs out of 4:

    init-complete=NO | TCP: 127.0.0.1:5432 - no response
                     | socket: /var/run/postgresql:5432 - accepting connections

Passing `-h 127.0.0.1` probes TCP instead, which the bootstrap server does not
answer. Throttling the container to 0.15 CPU makes the flake deterministic —
3 failures out of 3 before the change, 0 out of 3 after, for both oldest and
latest.

mysql and mariadb have the same defect: their entrypoints start the temporary
server on the same socket path with `--skip-networking`, and `sequelize_test`
is created while it is running. The window is much narrower — polling both
probes across a full startup catches `socket=ok tcp=fail` for only 2 samples
out of ~2200 — but it is real, so they get `--protocol=TCP` too.

Also raise the probe timeout to 5s and add a `start_period`, so a slow runner
does not mark a container unhealthy while it is legitimately still starting.

While here, `wait-until-healthy.sh`:

- `return_code=$?` captured the exit status of the preceding `echo`, so it was
  always 0 and the check was dead code.
- The timeout message claimed 20s; the loop actually ran for about 170s.
- It waited out the full timeout even when the container had already exited,
  and printed nothing on failure — no logs, no probe output — which is why the
  CI failures were undiagnosable from the job log alone.

It now fails fast on an exited or missing container, reports the real timeout,
and dumps `.State.Health` plus the last 50 log lines when it gives up.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@WikiRik
WikiRik requested a review from a team as a code owner July 29, 2026 13:19
@WikiRik
WikiRik requested review from ephys and sdepold July 29, 2026 13:19
@coderabbitai

coderabbitai Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: b0aba8e7-ef96-43a8-b2aa-317ef4c1af7a

📥 Commits

Reviewing files that changed from the base of the PR and between c9ded7a and e249fdd.

📒 Files selected for processing (1)
  • dev/wait-until-healthy.sh
🚧 Files skipped from review as they are similar to previous changes (1)
  • dev/wait-until-healthy.sh

📝 Walkthrough

Walkthrough

Database Compose healthchecks now use explicit TCP probes with expanded startup timing. The health-waiting script adds strict validation, deadline-based polling, container-state handling, deduplicated output, and failure diagnostics.

Changes

Container health readiness

Layer / File(s) Summary
Database healthcheck configuration
dev/mariadb/*/docker-compose.yml, dev/mysql/*/docker-compose.yml, dev/postgres/*/docker-compose.yml
MariaDB, MySQL, and PostgreSQL healthchecks now target TCP on 127.0.0.1, use longer timeouts and retry counts, and add startup periods where applicable.
Health status polling and diagnostics
dev/wait-until-healthy.sh
The script validates its container argument, polls health status against a configurable deadline, handles missing or stopped containers and absent healthchecks, and prints probe details plus recent logs on failure.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant wait_until_healthy.sh
  participant Docker
  participant DatabaseContainer
  participant Healthcheck
  wait_until_healthy.sh->>Docker: inspect container state and health status
  Docker->>DatabaseContainer: execute configured healthcheck
  DatabaseContainer->>Healthcheck: run TCP readiness probe
  Healthcheck-->>Docker: return probe status
  Docker-->>wait_until_healthy.sh: return health status
  wait_until_healthy.sh->>Docker: request probe details and logs on failure
Loading

Suggested reviewers: ephys

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: switching container database healthchecks to TCP.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch meta/fix-flaky-db-healthchecks

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@dev/wait-until-healthy.sh`:
- Around line 16-26: Handle failure of the health-status docker inspect in the
wait loop after the initial state check. Update the inspection assigning health
so a missing container immediately records an appropriate failure and exits or
breaks consistently with the existing failure handling, instead of continuing
with an empty status. Preserve normal health polling when the inspection
succeeds.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: bac5aeb7-2d03-4829-b202-b6cdb5aee249

📥 Commits

Reviewing files that changed from the base of the PR and between 040ad6d and c9ded7a.

📒 Files selected for processing (7)
  • dev/mariadb/latest/docker-compose.yml
  • dev/mariadb/oldest/docker-compose.yml
  • dev/mysql/latest/docker-compose.yml
  • dev/mysql/oldest/docker-compose.yml
  • dev/postgres/latest/docker-compose.yml
  • dev/postgres/oldest/docker-compose.yml
  • dev/wait-until-healthy.sh

Comment thread dev/wait-until-healthy.sh Resolved
The health inspection did not silence stderr the way the state inspection
above it does, so a container removed between the two calls would leak a raw
docker error and one "waiting for ... (currently: )" line before the next
iteration exited. Handle it the same way as the state inspection instead.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@WikiRik
WikiRik requested a review from SippieCup July 29, 2026 18:03

@SippieCup SippieCup left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM.

@WikiRik
WikiRik enabled auto-merge (squash) August 13, 2026 20:15
@WikiRik
WikiRik merged commit c204536 into main Aug 13, 2026
147 of 148 checks passed
@WikiRik
WikiRik deleted the meta/fix-flaky-db-healthchecks branch August 13, 2026 20:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants