Skip to content

Fix flaky test_prometheus_before_tables: wait for the log line - #112044

Merged
nikitamikhaylov merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-flaky-prometheus-before-tables
Jul 27, 2026
Merged

nikitamikhaylov merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-flaky-prometheus-before-tables

Conversation

@groeneai

@groeneai groeneai commented Jul 27, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #111782

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

...

Description

test_prometheus_with_handlers_starts_after_tables_are_loaded failed with

Exception: Command [docker exec ...-node_handlers-1 bash -c
  grep -n -m1 'Application: Listening for Prometheus' /var/log/clickhouse-server/clickhouse-server.log]
  return non-zero code 1

grep exit 1 means the line was not in the log yet, so the assertion never ran. Startup
ordering itself is correct in both configurations and is not changed here.

The integration harness reports an instance as started as soon as a bare
sock.connect((ip, 9000)) succeeds (ClickHouseInstance.wait_until_port_is_ready in
helpers/cluster.py). But createServers
(programs/server/Server.cpp:3454, start_servers=false) already calls
socketBindListen, which ends in socket.listen(backlog)
(src/Server/socketBindListen.cpp:31), so the kernel accepts into the backlog with no
accept loop and no log line. The Listening for {} lines are written later, in the
sequential start loop at Server.cpp:3692, and Prometheus is pushed last
(:4162). The prometheus.handlers instance skips the early-start path
(:3318, gated on !config().has("prometheus.handlers")), so its Prometheus line is the
last line of startup. first_log_line_number read it with a one-shot grep and no wait.

On the failing run the harness wait returned at 00:51:18.720 while the line was written at
00:51:19.011710, i.e. 291 ms later. The harness's own probe being accepted
(TCPHandlerFactory: TCP Request. Address: 172.16.1.1:62718) is logged 10 us before that
line, which shows the socket was reachable well before the loop reached Prometheus. The
two Application: Loaded metadata greps in the same module had only about 5 ms of margin
on that run, so they were latently racy too; the fix is in the shared helper and covers all
four call sites.

first_log_line_number now waits for the line when it is not there yet:

if not instance.contains_in_log(pattern):
    instance.wait_for_log_line(pattern)

The contains_in_log guard matters for runtime: wait_for_log_line runs
tail -F ... | grep -Em1 in the container and grep exits on the match, but tail -F
only notices the closed pipe on the server's next log write, so an unconditional barrier
costs about 7 s per call even when the line is already present. Measured on the whole
module: 17.19 s pristine, 35.88 s with an unconditional barrier, 16.17 s as written here.

This cannot mask an ordering regression. The failure mode being fixed is a missing line,
not a wrong order; if the lines were ever emitted in the wrong order, both would still be
found and the assert would still fail.

Verification (integration harness, debug build):

  • Deterministic reproducer: a slow startup_scripts entry on node_handlers.
    loadStartupScripts (Server.cpp:3541) runs between the bind at :3454 and the
    Listening for loop at :3692, so it widens the window while port 9000 already accepts.
    On the unpatched test this fails every time with the exact signature above; with the fix
    it passes and the assertion is really evaluated (line 324 before line 562).
  • Inverting the ordering assertion under that reproducer fails (assert 536 < 324), so the
    wait did not make the test vacuous.
  • Disabling the new wait under that reproducer fails again with the original grep error.
  • pytest --count 10 over the module (50 executions): 50 passed.

CI reports for the two failures:

An alternative would be to wait once for Application: Ready for connections.
(Server.cpp:3699) in the fixture. That is also a sound barrier, but it is coarser and
would leave first_log_line_number unsafe for any future caller.

Version info

  • Merged into: 26.8.1.211 (included in 26.8 and later)

groeneai added 2 commits July 27, 2026 05:20
… reading it

test_prometheus_with_handlers_starts_after_tables_are_loaded failed with

  Exception: Command [docker exec ...-node_handlers-1 bash -c
    grep -n -m1 'Application: Listening for Prometheus' /var/log/clickhouse-server/clickhouse-server.log]
    return non-zero code 1

grep exit 1 means the line was not in the log yet, so the assertion never ran.
Startup ordering itself is correct in both configurations and is not changed here.

The integration harness reports an instance as started as soon as a bare
sock.connect((ip, 9000)) succeeds (helpers/cluster.py:6008). But createServers
(programs/server/Server.cpp:3454, start_servers=false) already calls
socketBindListen, which ends in socket.listen(backlog)
(src/Server/socketBindListen.cpp:31), so the kernel accepts into the backlog with
no accept loop and no log line. The "Listening for {}" lines are written later, in
the sequential start loop at Server.cpp:3692, and Prometheus is pushed last
(:4162). The prometheus.handlers instance skips the early-start path (:3318, gated
on !config().has("prometheus.handlers")), so its Prometheus line is the last line
of startup. first_log_line_number read it with a one-shot grep and no wait.

On the failing run the harness wait returned at 00:51:18.720 while the line was
written at 00:51:19.011710, i.e. 291 ms later. The harness's own probe being
accepted (TCPHandlerFactory: TCP Request) is logged 10 us before that line, which
shows the socket was reachable well before the loop reached Prometheus. The two
"Application: Loaded metadata" greps in the same module had only about 5 ms of
margin on that run, so they were latently racy too; the fix is in the shared
helper and covers all four call sites.

The contains_in_log guard matters for runtime: wait_for_log_line runs
"tail -F ... | grep -Em1" in the container and grep exits on the match, but tail -F
only notices the closed pipe on the server's next log write, so an unconditional
barrier costs about 7 s per call even when the line is already present. Measured on
the whole module: 17.19 s unpatched, 35.88 s with an unconditional barrier, 16.17 s
as written here.

This cannot mask an ordering regression. The failure mode being fixed is a missing
line, not a wrong order; if the lines were ever emitted in the wrong order, both
would still be found and the assert would still fail.

Verified with a deterministic reproducer (a slow startup_scripts entry on
node_handlers, which runs between the bind and the "Listening for" loop): the
unpatched test fails every time with the signature above, the patched one passes
with the assertion really evaluated. Inverting the ordering assertion under that
reproducer fails, and disabling the new wait fails again with the original grep
error. pytest --count 10 over the module: 50 executions, 50 passed.
`.claude/CLAUDE.md` asks for literal excerpts from log messages to be wrapped in
inline code blocks. The comment added to `first_log_line_number` quoted the
`Listening for ...` excerpt with double quotes instead of backticks.

Comment-only change: the file is byte-identical to the previous commit once
comment and blank lines are stripped.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Two review rounds by a second model, independent of the author, plus my own cold read of
the resulting code. Round 1: 1 nit, fixed in 5c6ee2d57bfea5. Round 2: 0 findings.

# Finding Verdict
💡 The literal log excerpt in the new comment was written with double quotes. .claude/CLAUDE.md asks for literal excerpts from log messages inside inline code blocks. Agreed, fixed in 5c6ee2d57bfea5 (comment only; the file is byte-identical to the previous commit once comment and blank lines are stripped, with the merge-base as a differing control).
💡 The sock.connect call was cited by line number, which had already shifted on master because of an unrelated change to helpers/cluster.py. Agreed; the description now names ClickHouseInstance.wait_until_port_is_ready instead, so the reference does not rot.

Checks that came back clean:

  • Only one log-reading path exists in the module and it is module-private, so the single
    change covers all four call sites; no other integration module reads a startup
    Listening for or Ready for connections line, so there is no wider set to fix.
  • The assertions are byte-identical and were proven still live: inverting the ordering
    assertion under the reproducer fails (assert 536 < 324), and disabling the new wait
    fails again with the original grep error. No no-random-* tag, no timeout bump, no
    widened bound, no reduced dataset.
  • The guard and the barrier both read the module's log file, and wait_for_log_line writes
    its tee copy to a separate <log>.wait_for_log_line file, so it cannot perturb the line
    numbers the test then greps.
  • exec_in_container defaults to nothrow=False, so a line that never appears raises
    rather than leaking a wrong number.
  • Startup ordering is not touched: the diff contains no product code, and the build ID is
    unchanged.

Session id: cron:clickhouse-review-slot-48:20260727-084200

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100%, not a "~1%". A slow startup_scripts entry on node_handlers widens the window: loadStartupScripts (Server.cpp:3541) runs between the bind+listen at :3454 and the Listening for loop at :3692, so the log line is delayed while port 9000 already accepts. Every run of pytest test_prometheus_before_tables/test.py::test_prometheus_with_handlers_starts_after_tables_are_loaded on the unpatched test failed with the byte-identical CI signature grep -n -m1 'Application: Listening for Prometheus' ... return non-zero code 1.
b Root cause explained? Yes. The harness reports an instance started on a bare sock.connect((ip, 9000)) (ClickHouseInstance.wait_until_port_is_ready in helpers/cluster.py), but createServers (Server.cpp:3454, start_servers=false) already calls socketBindListen, which ends in socket.listen(backlog) (src/Server/socketBindListen.cpp:31), so the kernel accepts into the backlog with no accept loop and no log line. The Listening for {} lines are written later in the start loop at :3692, Prometheus is pushed last (:4162), and the prometheus.handlers instance skips the early-start path (:3318), so its line is the last of startup. first_log_line_number read it with a one-shot grep and no wait, so grep exited 1 and the assertion never ran. On the failing run the wait returned 291 ms before the line was written.
c Fix matches root cause? Yes. The failure is "the line is not written yet"; the fix waits for exactly that line. No widened bound, no reduced dataset, no no-random-* tag, no skip, no timeout bump, no weakened assertion. Startup ordering is not touched: no product code changes.
d Test intent preserved / new tests added? Preserved. Both assert statements are byte-identical. The changed file is itself the test, so no separate regression test applies; instead the assertions were proven still live by mutation (row e).
e Both directions demonstrated? Yes, same command. Unpatched + repro config -> FAIL with the CI signature. Patched + repro config -> PASS, with the barrier engaged (awaited line genuinely absent, waited 12.1 s) and the ordering assertion really evaluated (line 324 before line 562). Plus two mutations, both of which must fail and did: inverting the assertion -> assert 536 < 324 FAIL (so the wait did not make the test vacuous); disabling the new wait -> FAIL again with the original grep error (so the wait, not luck, is what makes it pass). pytest --count 10 over the module: 50 executions, 50 passed.
f Fix is general across code paths? Yes. first_log_line_number is the only log-reading path in the module and is module-private (grep -rn first_log_line_number tests/ matches this file only), so one change covers all four call sites, including the two Application: Loaded metadata greps, which had only ~5 ms of margin on the failing run and were latently racy too. A fix aimed only at the Prometheus line would have left those open. Deliberately not widened further: the module's other log readers are already safe (get_metrics has its own 10x0.5 s retry loop; test_startup_failure_after_early_prometheus_bind has its own 120-iteration poll and slices from the last startup banner because the log rotates on restart).
g Fix generalizes across inputs (params/datatypes/wrappers)? The inputs here are the pattern and the instance. Both patterns (Application: Listening for Prometheus, Application: Loaded metadata) and both instances (node, early-start path; node_handlers, regular lifecycle) flow through the fixed helper and were exercised: under normal configs all four call sites found the line already present (0.095-0.126 s); under the reproducer the Prometheus call found it absent and waited. Both patterns are free of regex metacharacters, so passing them to the helper's grep -E is safe.
h Backward compatible? (maintainer-approved exception only) N/A, test-only change. No setting default, no SettingsChangesHistory.cpp, no serialization or format change, no user-visible behaviour.
i Invariants and contracts preserved? Yes. first_log_line_number keeps its signature, its int return type, its assert output and its int(output.split(":", 1)[0]) parse, and remains a pure read. wait_for_log_line's tee -a writes to a separate <log>.wait_for_log_line file, so it cannot perturb the line numbers the test then greps. On the failure path the helper raises rather than returning a wrong number, so no early return leaks a bogus value.

Session id: cron:clickhouse-impl-slot-42:20260727-043200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @tavplubix — could you review this? It is a test-only fix for a flaky integration test: the harness reports an instance started as soon as its TCP port accepts, but the port is bound and listening before the Listening for ... lines are written, so the test's one-shot grep could run before the line existed and fail before its assertion. The helper now waits for the line; startup ordering itself is unchanged.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 27, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5c6ee2d]

Summary: ✅


AI Review

Summary

This PR fixes the flaky test_prometheus_before_tables helper by waiting for a startup log line when the instance is already accepting TCP connections but has not written that line yet. I reviewed the current diff, the linked flaky-test issue, the PR discussion, and the surrounding log-wait helpers in tests/integration/helpers/cluster.py; I did not find a correctness issue in the change, and the updated helper still preserves the ordering assertions the test is meant to enforce.

Missing context / blind spots
  • ⚠️ The current PR CI report for commit 5c6ee2d57bfea5dc393382377ecf1753b15ab79b has only style/config results finished so far; I did not have a completed integration-test run for this exact head SHA to independently confirm the reproducer/fix path. A passing test_prometheus_before_tables integration shard on this PR would close that gap.
Final Verdict

✅ No inline review findings. The added wait matches the reported race and does not weaken the test's ordering checks.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jul 27, 2026
@nikitamikhaylov nikitamikhaylov self-assigned this Jul 27, 2026
@nikitamikhaylov
nikitamikhaylov added this pull request to the merge queue Jul 27, 2026
Merged via the queue into ClickHouse:master with commit 9598ab4 Jul 27, 2026
179 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-ci pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Flaky test: test_prometheus_before_tables/test.py::test_prometheus_with_handlers_starts_after_tables_are_loaded

4 participants