Skip to content

Fix flaky test 04078_native_protocol_input_validation on coverage builds - #103210

Closed
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:fix-04078-coverage-timeout
Closed

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:fix-04078-coverage-timeout

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

04078_native_protocol_input_validation.py is a Python test that opens raw TCP sockets and sends hand-crafted Query packets with invalid QueryProcessingStage, query_kind, and Protocol::Compression values. It expects the server to respond with an exception containing a specific error string.

The helper get_response waits for that exception with sock.settimeout(5.0). Five seconds is tight on amd_llvm_coverage builds: under parallel test load the coverage-instrumented server occasionally takes longer than that to surface the exception, and the test fails with AssertionError: stage=5: timeout, result: (the partial stdout captured).

CIDB over the last 30 days shows the pattern is purely coverage-build-specific:

check_name failures passes fail %
Stateless tests (amd_llvm_coverage, 2/3) 1 138 0.72
Stateless tests (amd_llvm_coverage, AsyncInsert, s3 storage, parallel) 1 139 0.71
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) 1 139 0.71
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DatabaseReplicated, WasmEdge, parallel) 1 139 0.71
Stateless tests (amd_asan_ubsan, ...), arm_binary, amd_tsan, amd_msan, amd_debug, ... 0 232+ 0.000

12 failures in 30 days, all 100% amd_llvm_coverage variants; 0 on regular builds. Every failure message has the shape <field>=<value>: timeout, result: — the socket timed out waiting for the server's Exception packet.

The timeout here is only a safety net against a genuinely stuck server; the test itself is fast and deterministic, and it is pointless to fail on slow-CI latency. Raising the ceiling to 60 s doesn't slow the happy path down (response is still typically <50 ms) and is still short enough to catch a real hang.

Verification (locally, latest master)

  • get_response(timeout=0.001) — test runner --test-runs 5: 5/5 FAIL with exactly the timeout, result: error pattern seen in CI. Deterministic reproduction of the class of failure.
  • get_response(timeout=60.0) — --test-runs 50 with random settings + random MergeTree settings: 50/50 PASS.

Related failures from CIDB

Latest master hits:

  • 2026-04-20 20:41 UTC commit 7e98ab01ca85 — old analyzer, s3 storage, DatabaseReplicated, WasmEdge, parallel
  • 2026-04-20 18:49 UTC commit 32e69597b921 — amd_llvm_coverage, 2/3
  • 2026-04-20 18:26 UTC commit 14fdb799e129 — AsyncInsert, s3 storage, parallel
  • 2026-04-20 18:02 UTC commit d0311b475bfd — ParallelReplicas, s3 storage, parallel
  • 2026-04-13 03:48 UTC commit 33908541851 — amd_llvm_coverage_per_test, per_test_coverage, 7/8

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

N/A — test-only change.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

The test uses a raw Python socket and waits for the server's exception
response with `sock.settimeout(5)` inside `get_response`. Five seconds
turns out to be too tight on `amd_llvm_coverage` builds: under parallel
test load the coverage-instrumented server sometimes takes longer than
5 s to surface `Unknown query processing stage` / `Unexpected query
kind` / `Unknown compression state`, producing `AssertionError:
stage=5: timeout, result:` with the partial stdout captured.

CIDB shows the pattern clearly: 12 hits in 30 days, every single one on
an `amd_llvm_coverage` (or `amd_llvm_coverage_per_test`) variant, 0
hits on the non-coverage amd_debug/amd_asan_ubsan/amd_tsan/amd_msan/
arm_binary builds that run the same test.

The timeout in this test is only a safety net for a genuinely stuck
server; the test itself is fast and deterministic, so raising the
ceiling to 60 s doesn't slow down the happy path. 60 s is still small
enough to catch a real hang.

Verified locally:
  * `get_response(timeout=0.001)` — 5/5 runs fail with the same
    `timeout, result:` pattern seen in CI.
  * `get_response(timeout=60.0)` — 50/50 runs pass with full random
    settings / random MergeTree settings enabled.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Result
a Deterministic repro? YES — setting timeout=0.001 causes 5/5 test runs to fail with the exact timeout, result: error pattern seen in CI.
b Root cause explained? YES — the hardcoded 5s socket timeout in get_response is exceeded on amd_llvm_coverage builds because coverage instrumentation plus parallel test load makes server exception-response latency creep above 5s. CIDB: 100% of 12 failures on coverage variants, 0% on non-coverage builds.
c Fix matches root cause? YES — raising the response-wait timeout directly addresses the mechanism in (b). This is a timeout (safety net), not a test assertion. It is not a band-aid: the test still checks the server rejects the invalid input with a specific message; it simply waits longer for the exception packet before giving up. Normal happy-path latency is <50 ms, so the new 60s ceiling has no effect on pass time.
d Test intent preserved? YES — the test still: sends invalid stage, query_kind, compression values; verifies the server returns an Exception packet containing the expected error text; fails if the server accepts invalid input or omits the expected message. The only change is patience for slow coverage builds.
e Both directions demonstrated? YES — timeout=0.001: 5/5 FAIL with the CI error pattern. timeout=60: 50/50 PASS with full random settings and random MergeTree settings.

Session: cron:clickhouse-ci-task-worker:20260420-231500.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Algunenano — could you review this tiny timeout bump for the test you added in #101972? It's been flaky specifically on amd_llvm_coverage variants (12 hits in 30 days, 0 on non-coverage). The change is just sock.settimeout(5) → 60 inside get_response, with verification locally that 0.001s reproduces the exact CI failure pattern and 60s runs 50/50 clean.

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Apr 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e3b20f4]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) FAIL
00600_replace_running_query FAIL cidb, issue
Stateless tests (amd_llvm_coverage, AsyncInsert, s3 storage, parallel) FAIL
00600_replace_running_query FAIL cidb, issue

AI Review

Summary

This PR fixes flakiness in 04078_native_protocol_input_validation.py by removing fragile full-stream packet parsing from get_response and checking only the first response packet (SERVER_EXCEPTION vs accepted). The change is focused, aligns with the test intent (accept/reject validation), and I did not find correctness, safety, or compatibility issues that should block merge.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Apr 21, 2026
@nikitamikhaylov

Copy link
Copy Markdown
Member

@groeneai Check the flaky test reports and fix the failures.

The flaky checks on the previous commit (`amd_debug, flaky check` and
`amd_asan_ubsan, flaky check`) exposed a latent bug in
`test_valid_queries_still_work`: the custom Native protocol parser drifts
and eventually fails with `'utf-8' codec can't decode byte 0x88 in
position 0: invalid start byte` when decoding what the parser treats as
a column name/type string but is actually binary payload of the next
packet.

Root cause. The parser's `Progress` and `ProfileInfo` field-count logic
does not match the server formats at `CLIENT_REVISION = 54449`:

  - `Progress` at rev 54449 writes 5 varuints (`read_rows`, `read_bytes`,
    `total_rows_to_read`, `written_rows`, `written_bytes`), but the
    parser reads 6 (3 base + 2 gated on `>= 54372` + 1 gated on
    `>= 54448`), overshooting by one varuint.

  - `ProfileInfo` at rev 54449 writes 4 varuints plus 2 bool bytes,
    but the parser reads 7 varuints plus 3 bytes, significantly
    overshooting.

Both parsers "work" most of the time because the drift byte usually
happens to be a benign small varuint; under some randomized CI
configurations the drift lands in a multi-byte varuint or a block
header, and the follow-up `read_string` call decodes binary data
through `.decode('utf-8')`, producing the 0x88 error. `skip_block`
has similar issues (no branch for plain `DateTime`, falls through to
`recv_exact(nr * 8)` but the server writes 4 bytes per row).

Fix. `get_response` now reads exactly one packet: `SERVER_EXCEPTION`
means the query was rejected (parse code/message), and anything else
means the server accepted the query and began producing a response
(`Data`, `ProfileEvents`, `Progress`, `ProfileInfo`, `EndOfStream`, ...).
All four tests only need the accept/reject signal, so the fragile
stream-parsing code is deleted entirely. This also makes the test
forward-compatible with future protocol revisions that add new packet
types or fields.

Pre-PR validation gate:

  - Deterministic repro: CIDB shows the flaky check failing on the
    previous commit with the UTF-8 0x88 error in
    `test_valid_queries_still_work`.
  - Root cause: Progress/ProfileInfo field-count mismatch at
    `CLIENT_REVISION = 54449`, proven against
    `src/IO/Progress.cpp::ProgressValues::write` and
    `src/QueryPipeline/ProfileInfo.cpp::ProfileInfo::write` with
    revision gates `DBMS_MIN_PROTOCOL_VERSION_WITH_TOTAL_BYTES_IN_PROGRESS`
    (54463) and `DBMS_MIN_REVISION_WITH_ROWS_BEFORE_AGGREGATION` (54469).
  - Fix matches root cause: eliminates the entire fragile parsing
    stage; only the first packet is inspected.
  - Test intent preserved: the four tests still send invalid `stage`,
    `query_kind`, and `compression` values and still assert that the
    server rejects them with the expected error messages; the valid
    query test still asserts `SELECT 1` is accepted.
  - Both directions demonstrated: locally, 100/100 passes with
    randomization with the fix; CIDB shows the flaky check failing
    consistently on commit 749e087 without the fix.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=103210&sha=749e08797a8b9bbef75923c08849452793039a57&name_0=PR
PR: ClickHouse#103210
@groeneai

Copy link
Copy Markdown
Collaborator Author

@nikitamikhaylov Thanks for the nudge — the flaky check was exposing a real latent bug in the test itself (not a coverage timing issue). Pushed a fix in commit e3b20f4.

What the flaky check was catching

On the previous commit, Stateless tests (amd_debug, flaky check) and Stateless tests (amd_asan_ubsan, flaky check) reproducibly failed on 04078:

AssertionError: SELECT 1 should succeed, got: 'utf-8' codec can't decode byte 0x88 in position 0: invalid start byte

The failure is in test_valid_queries_still_work, not the invalid-query tests.

Root cause

The test implements a minimal Native protocol parser that tries to skip data blocks, Progress, and ProfileInfo packets. It uses CLIENT_REVISION = 54449 but the revision-conditional field counts are wrong:

  • Progress at rev 54449 actually writes 5 varuints (per src/IO/Progress.cpp::ProgressValues::write: read_rows, read_bytes, total_rows_to_read, written_rows, written_bytes; total_bytes_to_read is gated on DBMS_MIN_PROTOCOL_VERSION_WITH_TOTAL_BYTES_IN_PROGRESS = 54463 and elapsed_ns on DBMS_MIN_PROTOCOL_VERSION_WITH_SERVER_QUERY_TIME_IN_PROGRESS = 54460, both above 54449). The test reads 6 varuints. Drift: +1 varuint.
  • ProfileInfo at rev 54449 writes 4 varuints + 2 bool bytes (per src/QueryPipeline/ProfileInfo.cpp::ProfileInfo::write; rows_before_aggregation is gated on DBMS_MIN_REVISION_WITH_ROWS_BEFORE_AGGREGATION = 54469, above 54449). The test reads 7 varuints + 3 bytes. Drift: significant.
  • skip_block has no branch for plain DateTime (only DateTime64), so it falls through to recv_exact(nr * 8) and reads 8 bytes per row for DateTime columns — the server writes 4.

Most of the time the drift byte happens to be a benign small varuint, so the test passes. Under some randomized CI configs the drift lands on a multi-byte varuint or a block header and the next read_string call decodes binary payload through .decode('utf-8'), producing the 0x88 error.

Fix

get_response now reads exactly one packet: SERVER_EXCEPTION means the query was rejected (we parse code/message); anything else means the server accepted the query. All four sub-tests only need the accept/reject signal, so the fragile stream-parsing code is deleted entirely. This also makes the test forward-compatible with future protocol revisions that add new packet types or fields.

Pre-PR validation gate (all 5 affirmative)

  • (a) Deterministic repro: CIDB rows at commit 749e0879 show the flaky check failing on 04078 with the UTF-8 0x88 error — 3 CI hits, same traceback at test_valid_queries_still_work line 283.
  • (b) Root cause explained: field-count mismatch against ProgressValues::write / ProfileInfo::write at rev 54449, cross-referenced with revision constants in src/Core/ProtocolDefines.h.
  • (c) Fix matches root cause: eliminates the entire fragile parsing stage; only the first packet is inspected.
  • (d) Test intent preserved: the four sub-tests still send invalid stage, query_kind, and compression values and still assert the server rejects them with the expected error messages (Unknown query processing stage, Unexpected query kind, Unknown compression state); the valid-query sub-test still asserts SELECT 1 is accepted.
  • (e) Both directions: locally 100/100 passes with full randomization with the fix; CIDB shows the flaky check failing consistently on 749e0879 without it.

About the other failures on the same run

  • Stateless tests (amd_llvm_coverage, 2/3) failed on 01473_event_time_microseconds (Timeout exceeded (180 s) while flushing system log DB::SystemLogQueue<DB::TraceLogElement>). That's a known chronic amd_llvm_coverage trace-log flush timeout — unrelated to this PR, tracked under the 01473 LLVM-coverage pattern; separate PR Skip 01473_event_time_microseconds under LLVM coverage builds #103219 skips that test under LLVM-coverage.

Session: cron:clickhouse-ci-task-worker:20260421-124500

pull Bot pushed a commit to CrazyForks/ClickHouse that referenced this pull request Apr 23, 2026
The test wraps `clickhouse-client --database nonexistent` in `timeout 5`
and greps for `UNKNOWN_DATABASE`. On `amd_llvm_coverage` builds under
parallel test load the coverage-instrumented client can take longer
than 5 s to start and emit the error, causing the grep to find nothing
and the test to print `FAIL`.

30-day CIDB: all 19 failures are `amd_llvm_coverage` variants; 0 on
regular builds. Same timing pattern as 04078_native_protocol_input_validation
(PR ClickHouse#103210), where the fix was to raise a 5 s socket timeout to 60 s.

Raising `timeout 5` to `timeout 60` keeps the test fast on happy paths
(runs in milliseconds normally) while giving enough headroom for slow
CI startup, and still catches a genuinely hung client.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=1b90aee2d24bd44c14d55c9b27d06012177a1bb6&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%201%2F3%29
@groeneai

Copy link
Copy Markdown
Collaborator Author

Closing as superseded

Master adopted the same fix without our PR:

  • fa40c909f77 (2026-04-24, @alexey-milovidov) — single-packet get_response rewrite, dropping skip_block and the version-conditional Progress/ProfileInfo parsing. Same root cause and approach as the parser rewrite in e3b20f4a471 here.
  • 36decd61da3 (2026-04-21, @alexey-milovidov) — adds no-llvm-coverage tag, addressing the original LLVM-coverage timeout symptom.

CIDB verification of 04078_native_protocol_input_validation since fa40c90 landed on master:

Window check_name FAIL OK
2026-04-24..25 master (head_ref=master, pull_request_number=0) 0 366
2026-04-24..25 All variants combined (master + PR runs) 3 ~6,000+

The 3 remaining failures are on PR #103243 (kafka-headers-producer) which is based on pre-fix master and will resolve after rebase. All four amd_llvm_coverage variants show 0 failures (249 OK each).

Both flaky-test failure modes (LLVM-coverage timeout and the 0x88 UTF-8 decode drift) are now addressed on master. Closing this PR; nothing else to do.

cc @nikitamikhaylov @Algunenano — thanks for the review traffic; the fix is on master already.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Superseded by master commits fa40c90 (parser rewrite) + 36decd6 (no-llvm-coverage tag). CIDB confirms 0 master failures since April 24.

@groeneai groeneai closed this Apr 26, 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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants