Repository navigation
Capture jstack/UC liveness diagnostics on Spark hang in test_database_delta - #104801
antonio2368 merged 4 commits into
Conversation
The chronic flaky test `test_database_delta::test_check_database_unity` times out on `Integration tests (arm_binary, distributed plan, 4/4)` when the Spark JVM hangs between metastore initialization and actual query execution. PR ClickHouse#102649 (merged 2026-04-14) batched 7 sequential Spark invocations into one, dropping the failure rate to 2 master hits in 30 days, but a residual hang remains and we currently have no data to localize it: on `subprocess.TimeoutExpired` the Spark JVM is killed by SIGKILL, so `stdout`/`stderr` are truncated to whatever Spark logged before the hang point and the existing `uc.log` tail is not enough to say where the JVM is stuck. Add a `_capture_spark_hang_diagnostics` helper that runs after the existing log capture in the exception handler of `execute_spark_query` and collects three pieces of state from inside the test container: 1. `jstack` thread dump of every running `org.apache.spark` JVM — shows exactly where the JVM is stuck during the hang. 2. Unity Catalog HTTP liveness probe on `http://localhost:8080` — shows whether UC is responsive while Spark is hung. 3. `ss -tnp` snapshot of sockets matching `:8080` or `java` — shows whether Spark holds open sockets to UC at the moment of the hang. Each diagnostic is wrapped in its own `try`/`except` so a failure in one does not prevent collection of the others, and all `exec_in_container` calls use a short timeout (15-30 s) so the diagnostics cannot extend the test failure time noticeably. The helper runs only on the already-failing path so it cannot make a passing test fail. This is diagnostic-only — it does not fix the residual hang. The data it captures will let the next master hit be localized to a specific stuck thread or UC RPC instead of "Spark stopped logging". Tracked in worker task 2026-05-12-ci-p2-testdatabasedeltatestcheckd.
|
cc @antonio2368 @kssenii — could you review? Small diagnostic-only change in |
|
Pre-PR validation gate (session This PR is diagnostic-only — it does not change behavior on the passing path, only adds extra captures inside the existing exception handler of a) Tools exist in the test container? Yes — verified b) Cannot break a passing test? Yes — the helper is called only inside the c) Cannot extend test failure time noticeably? Yes — all d) Test intent preserved? Yes — no test assertion or query changed; only the failure-mode logging is richer. e) Why a fix is not in this PR. The root cause of the residual hang is unknown — CIDB rows always stop at Recent failure history (post-PR #102649): 2 master hits in 30 days, both on |
|
Workflow [PR], commit [37e278d] Summary: ✅ AI ReviewSummaryThis PR adds failure-path diagnostics in Final Verdict
|
There was a problem hiding this comment.
Mostly small stuff, but the jstack fallback doesn't actually fall back — head masks jstack's exit code, so -F never runs. Same pattern bites the ss sentinel.
@groeneai address all the comments
| # 1. Thread dumps of running Spark JVMs. | ||
| try: | ||
| pids_out = node.exec_in_container( | ||
| ["bash", "-c", "pgrep -f 'org.apache.spark' || true"], |
There was a problem hiding this comment.
pgrep -f 'org.apache.spark' can match the bash -c wrapper itself, so when no Spark JVM is left you sometimes get the wrapper PID back and jstack runs against it. Easy fix:
["bash", "-c", "pgrep -f '[o]rg.apache.spark' || true"]There was a problem hiding this comment.
Fixed in 720c43fe7e6 — pgrep -f '[o]rg.apache.spark' || true. The [o] character class matches a literal o, so the regex still matches a real Spark JVM cmdline, but the regex string itself contains [o] instead of plain o and therefore does not match the wrapper's own bash -c command line. Verified the trick in isolation (real Spark cmdline java ... org.apache.spark.executor.CoarseGrained... still matches; wrapper cmdline bash -c "pgrep -f '[o]rg.apache.spark' || true" does not).
| f"jstack {pid} 2>&1 | head -500" | ||
| f" || jstack -F {pid} 2>&1 | head -500", |
There was a problem hiding this comment.
The -F fallback never runs. head -500 exits 0 as soon as it sees any byte, and jstack's errors go through 2>&1 into head, so the left side of the || succeeds even when jstack failed. This is the unresponsive-JVM path the PR exists to capture.
f"(jstack {pid} || jstack -F {pid}) 2>&1 | head -500"or set -o pipefail; at the start if you'd rather keep the current shape.
There was a problem hiding this comment.
Fixed in 87abec5f9fc — restructured to (jstack {pid} 2>&1 || jstack -F {pid} 2>&1) | head -500 so the fallback runs inside the subshell, before head truncates. Smoke-verified: forcing jstack to fail (false substitute) now triggers the -F branch; with the old shape it did not.
| for pid in pids: | ||
| try: | ||
| # Prefer non-force jstack; fall back to ``-F`` if the JVM is | ||
| # unresponsive to the attach mechanism. | ||
| dump = node.exec_in_container( | ||
| [ | ||
| "bash", | ||
| "-c", | ||
| f"jstack {pid} 2>&1 | head -500" | ||
| f" || jstack -F {pid} 2>&1 | head -500", | ||
| ], | ||
| nothrow=True, | ||
| timeout=30, | ||
| ) | ||
| print(f"Spark hang diag: jstack of PID {pid}:\n{dump}") | ||
| except Exception as je: | ||
| print(f"Spark hang diag: jstack PID {pid} failed: {str(je)}") |
There was a problem hiding this comment.
If executors are also stuck you'll pay 30s per PID. Usually just one driver, so probably fine — head -n 3 on the PID list would cap it if you want a belt.
There was a problem hiding this comment.
Capped in 720c43fe7e6 — pids = pids[:3] in Python. Belt for the pathological case where driver + several executors are all hung; normal case (one driver JVM per query) is unchanged.
| "ss -tnp 2>&1 | grep -E ':8080|java' | head -50" | ||
| " || echo ' no_matching_sockets'", |
There was a problem hiding this comment.
Same head-eats-exit-status thing here: when nothing matches, grep fails but head succeeds, so || echo ' no_matching_sockets' never runs and you get empty output instead of the sentinel. set -o pipefail and { grep ... || true; } would do it.
There was a problem hiding this comment.
Fixed in 87abec5f9fc — set -o pipefail; ss -tnp 2>&1 | { grep -E ':8080|java' || true; } | head -50 || echo ' no_matching_sockets'. pipefail propagates ss's exit status through head; grep ... || true deliberately swallows the exit-1 that grep produces on no matches, so the sentinel fires only when ss itself fails. Smoke-verified that forcing ss to fail now triggers the sentinel.
…_diagnostics`
The diagnostic helper added in commit `44b9947afaf` used two shell pipelines
whose fallback branches were unreachable due to exit-code masking by `head`:
1. `jstack <pid> 2>&1 | head -500 || jstack -F <pid> 2>&1 | head -500`
The exit code of `cmd | head` is `head`'s, not `cmd`'s. Once `jstack`
emits even a single byte (or fails to attach with a non-empty error
message on stderr that gets folded by `2>&1`), `head` returns 0 and
the `|| jstack -F` fallback never fires. On the exact hang path this
PR targets — JVM unresponsive to the regular attach mechanism — we
could silently get an empty thread dump instead of the force-attach
dump that actually localizes the stuck thread.
2. `ss -tnp 2>&1 | grep -E ':8080|java' | head -50 || echo ' no_matching_sockets'`
Same class of bug, deeper pipeline. `head -50`'s exit code masks both
`ss` and `grep`. The `|| echo` sentinel is unreachable even when `ss`
itself fails to run.
Reshape both pipelines so the fallback can actually fire:
1. `(jstack <pid> 2>&1 || jstack -F <pid> 2>&1) | head -500`
The fallback runs INSIDE the subshell, BEFORE `head` truncates. If
plain `jstack` fails, `jstack -F` runs; whichever produces output
gets piped through `head`.
2. `set -o pipefail; ss -tnp 2>&1 | { grep -E ':8080|java' || true; } | head -50 || echo ' no_matching_sockets'`
`pipefail` makes the pipeline's exit reflect any failing stage.
`grep ... || true` deliberately swallows the exit-1 that `grep`
produces on no matches (we don't want the sentinel for "ran fine,
just no matches"), so the sentinel fires only when `ss` itself
fails — the intended semantics.
Smoke-verified locally:
- Old `jstack` pattern: forced-fail `jstack` does NOT trigger fallback (bug).
New pattern: forced-fail `jstack` DOES trigger fallback.
- Old `ss` pattern: forced-fail `ss` does NOT trigger sentinel (bug).
New pattern: forced-fail `ss` triggers sentinel; success + no `grep` match
produces empty output (no false-positive sentinel); success + matches
produces the matched lines.
Addresses inline review on PR ClickHouse#104801:
- clickhouse-gh[bot] 2026-05-13T07:59:39Z (`jstack`)
- @antonio2368 2026-05-13T12:19:51Z ("address all the comments";
flagged that the same pattern also bites the `ss` sentinel)
…ng_diagnostics` Two further follow-ups on the diagnostic helper, addressing the remaining inline comments from @antonio2368 on PR ClickHouse#104801: 1. `pgrep -f 'org.apache.spark'` matched the wrapper `bash -c` cmdline itself on shards where no real Spark JVM is left, so the next loop ran `jstack` against an unrelated shell PID and produced a confusing "no Java thread state" dump instead of the intended "no Spark JVMs" message. Switch the pattern to `[o]rg.apache.spark`: the character class `[o]` matches a literal `o`, so the regex still matches a real Spark cmdline, but the regex string itself contains `[o]` rather than plain `o` and therefore does NOT match the wrapper's own command line. 2. The `jstack` loop has a 30s per-PID timeout. If a hang affects both the driver and several executors the helper would consume `30 * N` seconds before the test could fail and be reported. In practice there is one driver JVM per query, but the safe upper bound is cheap: cap the iterated PID list at 3 with a slice. The cap is a belt; the normal-case behaviour is unchanged. Smoke-verified in isolation (`tmp/testpattern.py`): the OLD pattern self-matches its OLD wrapper cmdline; the NEW pattern does NOT self-match its NEW wrapper cmdline; both patterns still match a real Spark JVM cmdline (`java ... org.apache.spark.executor.CoarseGrained...`). Addresses inline review on PR ClickHouse#104801: - @antonio2368 2026-05-13T12:16:23Z (`pgrep` self-match) - @antonio2368 2026-05-13T12:16:24Z (30s-per-PID cap)
|
@antonio2368 — addressed all four inline comments in two commits.
For
The Smoke-verified each change in isolation:
The changes are diagnostic-only and run only on the already-failing path inside |
The v2 ss-block pipeline (`set -o pipefail; ss | grep | head -50 || ' no_matching_sockets'`)
fixed one bug (sentinel was unreachable without `pipefail`) but introduced another:
under `pipefail`, when `ss` produces more than 50 matching lines, `head -50` closes
its stdin after reading 50 lines. Upstream `ss` (and `grep`) continue writing into
the closed pipe, receive `SIGPIPE`, and exit 141. `pipefail` propagates that as the
pipeline status, so `||` then triggers `echo ' no_matching_sockets'` even though
`ss` succeeded with many matches. This produces a false "no matching sockets"
signal in exactly the scenario where rich diagnostics matter most — a container
with many java/UC connections during a Spark hang.
Reproduction:
set -o pipefail
yes ':8080 estab pid=java' | head -100000 \
| { grep -E ':8080|java' || true; } \
| head -50 \
|| echo ' no_matching_sockets'
# → last line of output is ' no_matching_sockets' even though grep
# succeeded with thousands of matches.
Fix: decouple `ss` execution from filtering/truncation. Capture `ss` into a shell
variable; test its exit status directly via `if ss_output=$(ss -tnp 2>&1); then ...`.
The filtering/truncation stage then operates on the variable with no `pipefail`,
so `head`'s early-close cannot influence the success/failure decision. The
sentinel fires only when `ss` itself fails to run (e.g., not installed, permission
denied).
Smoke-verified across six scenarios: (A) 200 lines fitting pipe buffer, (B) 100K
lines forcing SIGPIPE, (C) 10 matching lines, (D) zero grep matches, (E) `ss`
exits non-zero, (F) command not found. Old pattern false-fires in (B); new
pattern is correct in all six.
Addresses @antonio2368's review feedback and clickhouse-gh[bot]'s inline review
on PR ClickHouse#104801.
|
Third fix-up pushed: Root cause of the v2 bug. The previous shape Fix. Capture if ss_output=$(ss -tnp 2>&1); then
echo "$ss_output" | { grep -E ":8080|java" || true; } | head -50
else
echo ' no_matching_sockets'
fiPre-PR validation gate (diagnostic-only change).
All four prior inline review comments from @antonio2368 (the original review) remain addressed by |
test_check_database_unity (and other test_database_delta tests that call execute_spark_query) is chronically flaky: the spark-sql invocation occasionally hangs for the full 600s timeout and the test fails with subprocess.TimeoutExpired. Root cause, from a jstack thread dump captured by the existing hang diagnostics (PR ClickHouse#104801) on a CI failure (PR ClickHouse#106374, Integration tests (arm_binary, distributed plan, 4/4)): the Spark main thread parks for the whole timeout inside the Unity Catalog Java client: jdk.internal.net.http.HttpClientImpl.send io.unitycatalog.client.api.SchemasApi.getSchema io.unitycatalog.spark.UCProxy.loadNamespaceMetadata SupportsNamespaces.namespaceExists CreateNamespaceExec.run <- first CREATE SCHEMA The UC client uses the JDK HttpClient with no per-request timeout, so a single transient stall hangs forever. The hang is transient, not a UC outage: in the same run the UC liveness probe answered in 7.8ms with http_code 500, Ivy dependency resolution succeeded in 396ms (so this is not a package-download problem), and the very next test (test_multiple_schemes_tables, same CREATE SCHEMA path) ran 17s later and passed in under a second once the stuck JVM was killed. Retry the Spark invocation with a fresh JVM when it hangs. Only the timeout is retried; real query errors are re-raised immediately. Per-attempt timeout is 300s and at most two attempts are made, keeping the worst case within the 900s per-test pytest limit. The retry is opt-in (retry_on_timeout, default False) because the pkill + metastore cleanup preamble does not reset Unity Catalog or Delta committed state: blindly re-running a multi-statement batch that already committed an earlier statement could fail on "already exists" or duplicate INSERT rows. Non-idempotent callers keep the original single-attempt behavior. test_check_database_unity opts in after being made idempotent (CREATE SCHEMA/TABLE IF NOT EXISTS, INSERT OVERWRITE), so a fresh-JVM retry after a partial commit converges to the same final state. The test asserts only table count and CHECK DATABASE, so OVERWRITE vs INSERT changes no assertion. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The chronic flaky test
test_database_delta::test_check_database_unitytimes out onIntegration tests (arm_binary, distributed plan, 4/4)when the Spark JVM hangs between Hive metastore initialization and actual query execution. PR #102649 (merged 2026-04-14) batched 7 sequential Spark invocations into one, dropping the failure rate to 2 master hits in 30 days, but a residual hang remains and we currently have no data to localize it.When
subprocess.TimeoutExpiredfires insideexecute_spark_query, the Spark JVM is killed by SIGKILL so itsstdout/stderrare truncated to whatever it logged before the hang point, and the existinguc.logtail is not enough to tell us where the JVM is stuck. CIDB rows for the failing master shards (2a00d99d,2f0c1004— 2026-05-11) consistently stop atObjectStore.setMetaStoreSchemaVersion, which is the last metastore-init log line. We do not know whether Spark is then blocked on a Unity Catalog HTTP call, on a Derby file lock, or somewhere else entirely.This PR adds a
_capture_spark_hang_diagnosticshelper that runs after the existing log capture in the exception handler ofexecute_spark_queryand collects three pieces of state from inside the test container:jstackthread dump of every runningorg.apache.sparkJVM — shows exactly where the JVM is stuck during the hang.http://localhost:8080/api/2.1/unity-catalog/schemas— shows whether UC is responsive while Spark is hung.ss -tnpsnapshot of sockets matching:8080orjava— shows whether Spark holds open sockets to UC at the moment of the hang.Each diagnostic is wrapped in its own
try/exceptso a failure in one does not prevent collection of the others, and allexec_in_containercalls use short timeouts (15–30 s) so the diagnostics cannot meaningfully extend the test failure time. The helper runs only on the already-failing path so it cannot make a passing test fail. All three tools (jstack,curl,ss) are present in theclickhouse/integration-test-with-unity-catalog:latestimage used by the test fixture (verified bydocker run --entrypoint /bin/bash ... -c 'which jstack curl ss').This is diagnostic-only — it does not fix the residual hang. The data it captures will let the next master hit be localized to a specific stuck thread or UC RPC instead of "Spark stopped logging".
Sample failure (master): https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=2a00d99de694fda4302148265b75a9d42ae878fa&name_0=MasterCI
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
...
Documentation entry for user-facing changes
Version info
26.5.1.648