Skip to content

Retry Spark query on transient hang in test_database_delta - #107133

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix/flaky-test-check-database-unity-spark-retry
Jun 13, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix/flaky-test-check-database-unity-spark-retry

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

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

Fix chronic flakiness in test_database_delta/test.py::test_check_database_unity (and sibling tests using execute_spark_query). The spark-sql invocation occasionally hangs for the full 600s timeout, failing with subprocess.TimeoutExpired.

Root cause (jstack thread dump captured by the hang diagnostics from #104801, on the failure in PR #106374 / Integration tests (arm_binary, distributed plan, 4/4)): the Spark main thread parks for the whole timeout inside the Unity Catalog Java client, which uses the JDK HttpClient with no per-request timeout:

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 hang is transient, not a UC outage: in the same run the UC liveness probe answered in 7.8ms (http_code 500), Ivy resolution finished in 396ms (so it is not a package-download issue), and the next test (test_multiple_schemes_tables, same CREATE SCHEMA path) passed in under a second 17s later once the stuck JVM was killed.

Fix: retry the Spark invocation with a fresh JVM when it hangs. Only the timeout is retried; real query errors are re-raised immediately. The existing pkill + metastore cleanup preamble runs before each attempt, so the retry starts clean. Per-attempt timeout is 300s with at most two attempts, keeping the worst case within the 900s per-test pytest limit.

No related open issue was found for this test.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? No, and it cannot be. The failure is a transient Unity Catalog HTTP-client stall that hit ~weekly across 30 days of CI; it is not triggerable on demand. The root cause is instead proven by hard evidence (see b).
b Root cause explained? Yes. jstack from the hang diagnostics added in #104801, captured on the #106374 failure, shows the Spark main thread parked the full 600.05s in jdk.internal.net.http.HttpClientImpl.send -> SchemasApi.getSchema -> UCProxy.loadNamespaceMetadata -> namespaceExists -> CreateNamespaceExec.run (first CREATE SCHEMA). The UC Java client uses the JDK HttpClient with no per-request timeout, so a single transient stall hangs forever. It is transient, not a UC outage: UC liveness probe answered in 7.8ms (http_code 500), Ivy resolution finished in 396ms, and test_multiple_schemes_tables (same CREATE SCHEMA path) passed in <1s 17s later once the stuck JVM was killed.
c Fix matches root cause? Yes. Bounded-timeout retry with a fresh JVM on the transient hang. Only the timeout is retried; real query errors are re-raised immediately. The existing pkill + metastore-cleanup preamble runs before each attempt, reaping the stuck JVM first.
d Test intent preserved / new tests added? Yes. No assertion was weakened and no setting was pinned; all test logic is unchanged. The change is confined to the execute_spark_query helper. The hang diagnostics from #104801 are still captured on a final (non-recovered) failure.
e Both directions demonstrated? Partial, by necessity. "Fails without fix" cannot be shown for a transient ~weekly hang. The retry control flow is validated deterministically: hang->success recovers with a fresh JVM (2 attempts); a real error does NOT retry and raises immediately (1 attempt); a persistent hang raises after 2 attempts and captures diagnostics once; a clean success runs once. A full integration repro was attempted but the host environment lacks the privileged Docker-in-Docker the praktika runner needs; CI exercises the happy path here.
f Fix is general, not a narrow patch? Yes. The fix lives in the single shared execute_spark_query helper, so it covers every caller (execute_multiple_spark_queries and all direct callers) and every line number this flake has surfaced at across its re-emergences, not just test_check_database_unity.

Session id: cron:clickhouse-worker-slot-14:20260611-015500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @scanhex12 — could you review this? It fixes the chronic flake in test_check_database_unity: the Unity Catalog Java client (JDK HttpClient, no per-request timeout) occasionally parks the whole 600s on the first CREATE SCHEMA (SchemasApi.getSchema -> namespaceExists), per a jstack from the #104801 hang diagnostics. The fix retries the hung spark-sql with a fresh JVM; real query errors are not retried.

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

clickhouse-gh Bot commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1ea6cc0]

Summary: ✅


AI Review

Summary

This PR makes the Spark SQL timeout retry in test_database_delta opt-in, preserves the original 600s budget for non-retry callers, and makes test_check_database_unity idempotent before enabling a two-attempt retry. I found no remaining correctness issue in the changed helper or its current callers; the earlier retry-idempotency, timeout-budget, and cleanup self-match findings are addressed.

Missing context / blind spots
  • ⚠️ Full PR CI for commit 1ea6cc02 was still pending during review; fetch_ci_report.js could not fetch the Praktika comment because the available GitHub token was rejected by the enterprise token policy. A completed Praktika report for the affected integration shard would close this operational validation gap.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jun 11, 2026
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]>
@groeneai
groeneai force-pushed the fix/flaky-test-check-database-unity-spark-retry branch from 8c12431 to 674a4a2 Compare June 11, 2026 11:14
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (updated for 674a4a2 idempotency fixup)

# Question Answer
a Deterministic repro? No, and it cannot be made deterministic: the failure is a transient Unity Catalog HTTP-client hang (JDK HttpClient with no per-request timeout) that fires ~weekly at random across 30d. This is the defining property of the chronic flake, not a gap in investigation. The hang location IS proven on demand though, via the jstack thread dump captured by PR #104801's diagnostics on the PR #106374 CI failure.
b Root cause explained? Yes. spark-sql parks the main thread for the full timeout inside io.unitycatalog.client.api.SchemasApi.getSchema -> UCProxy.loadNamespaceMetadata -> CreateNamespaceExec.run (first CREATE SCHEMA). The UC Java client uses JDK HttpClient with no per-request timeout, so one transient stall hangs forever. Corroborated: UC liveness probe answered in 7.8ms (http_code 500), Ivy resolved in 396ms (not a download issue), and the next test on the same CREATE SCHEMA path passed in <1s once the stuck JVM was killed.
c Fix matches root cause? Yes. Bounded-timeout retry with a fresh JVM is the standard test-infra remedy for a proven-transient hang in a third-party client we do not control (the Dockerfile already retries the same Spark setup 3x). Real query errors are re-raised immediately, only the hang is retried.
d Test intent preserved / new tests added? Yes. The retry is opt-in (retry_on_timeout, default False), so non-idempotent callers keep single-attempt behavior unchanged. test_check_database_unity is made idempotent (CREATE SCHEMA/TABLE IF NOT EXISTS, INSERT OVERWRITE) and asserts only table count + CHECK DATABASE, so no assertion changes. No production code touched, so no new regression test applies.
e Both directions demonstrated? Partial, by design. "Fails without fix" cannot be forced locally (transient, random across 30d). The retry control-flow is validated by a deterministic standalone harness (6/6 cases): opt-in hang->success recovers (2 calls), default hang does NOT retry (1 call, old behavior), opt-in real error does NOT retry, opt-in persistent hang raises after 2 attempts + diagnostics once. Full praktika integration repro is blocked by this host (no privileged Docker-in-Docker; shared docker daemon across the 32-slot fleet).
f Fix is general, not a narrow patch? Yes. The opt-in lives in the shared execute_spark_query/execute_multiple_spark_queries helpers, so all callers (every re-emergence line number) benefit consistently, while only idempotent/read-only ones opt in. The clickhouse-gh[bot] CR (blind retry could replay a partial-commit batch) is addressed at the shared helper, not just the one test.

Session id: cron:clickhouse-worker-slot-11:20260611-103400

_run_spark_query_once hardcoded the 300s per-attempt timeout for every
caller, so non-opt-in (retry_on_timeout=False) callers lost the original
600s budget that master used. A slow-but-progressing spark-sql setup or
query could newly time out at 300s and flake.

Thread the timeout into _run_spark_query_once: retry_on_timeout=False
runs a single attempt at the original 600s; retry_on_timeout=True runs up
to 2 attempts at 300s each (worst case 600s, within the 900s pytest limit).

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (fixup 3756093)

# Question Answer
a Deterministic repro? Yes, statically. git show fc73f46:tests/integration/test_database_delta/test.py (master merge-base) used timeout=600 for the single Spark attempt; the reviewed commit 674a4a2 routed every caller through _run_spark_query_once with a hardcoded SPARK_QUERY_ATTEMPT_TIMEOUT = 300, so non-opt-in callers deterministically drop to a 300s budget. The regression is provable from the diff, not rate-based.
b Root cause explained? _run_spark_query_once hardcoded the per-attempt timeout at 300s for ALL callers. retry_on_timeout only controlled the attempt COUNT (1 vs 2), not the per-attempt budget, so a retry_on_timeout=False caller that previously had 600s now only gets 300s and a slow-but-progressing spark-sql setup/query times out where it would not have before.
c Fix matches root cause? Yes. The timeout is now a parameter of _run_spark_query_once. retry_on_timeout=False selects SPARK_QUERY_TIMEOUT = 600 (one attempt, restoring the exact pre-PR budget); retry_on_timeout=True selects SPARK_QUERY_RETRY_ATTEMPT_TIMEOUT = 300 per attempt (<=2 attempts). No symptom-masking.
d Test intent preserved / new tests added? Preserved. The opt-in retry semantics (only the idempotent test_check_database_unity batch retries) are unchanged; this only restores the wall-clock budget for non-opt-in callers. No assertions weakened. (Integration timeout-budget change; no new test case applicable.)
e Both directions demonstrated? Yes, via a focused harness replicating the exact attempt/timeout selection logic: reviewed-commit logic yields non-opt-in budget = 300s (the bug); fixed logic yields 600s (restored). Retry worst case = 2*300 = 600s <= the 900s pytest per-test limit. All assertions pass.
f Fix is general, not a narrow patch? Yes. The timeout flows through the single _run_spark_query_once chokepoint, so every caller (execute_spark_query and execute_multiple_spark_queries, both default and retry_on_timeout=True) gets the correct budget. No sibling code path bypasses it.

Session id: cron:clickhouse-worker-slot-16:20260611-125100

The pre-attempt cleanup in _run_spark_query_once runs as bash -c "...",
so the shell's own command line contains the literal pkill pattern. A plain
pkill -f 'org.apache.spark' therefore matched and SIGKILLed that shell before
'sleep 1; rm -rf metastore_db' could run; with nothrow=True the nonzero exit
was swallowed, so a corrupt Derby metastore_db could survive into the next
retry and hang Spark initialization.

Use the [o]rg.apache.spark character-class pattern (already used by
_capture_spark_hang_diagnostics) so the regex no longer matches its own
command line while still matching real Spark JVMs.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (fixup 1ea6cc0)

# Question Answer
a Deterministic repro? Yes. Out-of-container harness: a bash -c "<inline>" whose <inline> carries the literal pattern (exactly how exec_in_container runs). OLD 'org.apache.spark' -> the bash -c shell is SIGKILLed by its own pkill (exit -9). NEW '[o]rg.apache.spark' -> exit 0. 100% reproducible both ways.
b Root cause explained? The cleanup preamble runs as bash -c "pkill -9 -f 'org.apache.spark'; sleep 1; rm -rf metastore_db". That shell's own /proc/<pid>/cmdline contains the literal org.apache.spark, so the pkill regex matches and SIGKILLs the shell before sleep/rm -rf run; nothrow=True swallows the nonzero exit, so the corrupt Derby metastore_db this block must clear can survive into the next retry and hang Spark init.
c Fix matches root cause? Yes. Switch the pattern to [o]rg.apache.spark (character class): [o] matches o but keeps the literal text out of the regex, so it no longer matches its own command line. Same trick already used in _capture_spark_hang_diagnostics. No band-aid (no nothrow removal, no sleep bump).
d Test intent preserved / new tests added? Preserved. Both patterns still match a genuine java ... org.apache.spark.deploy.SparkSubmit cmdline via pgrep -f, so real Spark JVMs are still reaped; only self-match is removed. Integration-test infra change, no new regression test added (this is an integration helper, not a code bug with a unit-testable surface).
e Both directions demonstrated? Yes. OLD: cleanup shell killed, rm -rf never runs, metastore survives. NEW: shell survives, rm -rf runs, metastore cleared. Verified in the same harness.
f Fix is general, not a narrow patch? Yes. Grepped the whole file: both pkill/pgrep call sites (line 119 diagnostics, line 235 cleanup) now use [o]rg.apache.spark; no self-matching 'org.apache.spark' pattern remains.

Session id: cron:clickhouse-worker-slot-16:20260611-140400

@clickhouse-gh

clickhouse-gh Bot commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.60% 84.60% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.30% 77.20% -0.10%

Changed lines: No C/C++ source files changed — skipping uncovered code analysis.

Newly covered by added/modified tests: 315 line(s), 120 function(s) across 113 file(s) · Details

Top files
  • src/AggregateFunctions/AggregateFunctionIntervalLengthSum.cpp: 22 line(s), 40 function(s)
  • src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesChanges.h: 14 line(s), 32 function(s)
  • src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesLinearRegression.h: 14 line(s), 32 function(s)
  • src/Storages/StorageReplicatedMergeTree.cpp: 12 line(s)
  • src/Storages/Statistics/ConditionSelectivityEstimator.cpp: 11 line(s), 2 function(s)

Full report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on 1ea6cc0. All checks green (55 success, 111 skipped, 0 failures). No PR-caused failures. Ready for review.

(cron:our-pr-ci-monitor:20260611-210000)

@alexey-milovidov alexey-milovidov self-assigned this Jun 13, 2026

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I love your work!

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jun 13, 2026
Merged via the queue into ClickHouse:master with commit 8b97146 Jun 13, 2026
166 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 13, 2026
qiuyanjun888 pushed a commit to qiuyanjun888/ClickHouse that referenced this pull request Sep 27, 2026
test_complex_table_schema and test_varchar_char_types_via_unity_catalog fail with
"subprocess.TimeoutExpired: ... bin/spark-sql ... timed out after 600 seconds".
CIDB over 30 days: 5 rows across 5 distinct PRs for this signature, 0 on master.

The Unity Catalog server accepts GET /schemas/{name} and never answers it, and the
UC Java client issues that request through java.net.http.HttpClient with no
per-request timeout, so the Spark driver parks for the whole subprocess budget.
The jstack that the test's own hang diagnostics capture 600s into the stall puts
it in the batch's first statement:

  "main" ClickHouse#1 cpu=11625.96ms elapsed=600.24s WAITING (parking)
    jdk.internal.net.http.HttpClientImpl.send
    io.unitycatalog.client.api.SchemasApi.getSchemaWithHttpInfo(SchemasApi.java:273)
    io.unitycatalog.spark.UCProxy.loadNamespaceMetadata(UCSingleCatalog.scala:399)
    SupportsNamespaces.namespaceExists(SupportsNamespaces.java:98)
    CreateNamespaceExec.run(CreateNamespaceExec.scala:43)

CreateNamespaceExec.run probes namespaceExists before creating anything. In the
same diagnostics both socket ends are ESTAB with Recv-Q = Send-Q = 0 for 600s
(the request was fully delivered and UC produced no response byte) while a
concurrent UC liveness probe answered in 10.7ms, so the server was serving other
requests and a fresh client converges.

Two alternatives are excluded by measurement. Ivy package resolution is not
involved: the failing run reports "0 artifacts copied, 33 already retrieved
(0kB/16ms)", because the image pre-resolves the same --packages list at build
time. Derby metastore init is not involved either: the JVM got well past
ObjectStore init.

UC is a third-party server pinned in the test image and its client constructs its
own HttpClient, so neither the handler nor a request timeout is reachable from the
spark-sql command line. The only lever the test owns is to survive the stall,
which is what ClickHouse#107133 established and ClickHouse#109641 extended to the read path.

Hence the same two-part remedy at the two measured write sites: rewrite the batch
into the idempotent form already used at the precedent site (CREATE SCHEMA IF NOT
EXISTS, CREATE TABLE IF NOT EXISTS, INSERT OVERWRITE), then pass
retry_on_timeout=True so one fresh-JVM replay is allowed. 2 x 300s fits the 900s
per-test cap from tests/integration/pytest.ini with roughly 300s of headroom; no
timeout constant changes. Both tables are named with a fresh uuid4() and hold
exactly one row, so a replay converges to identical content.

test_snapshot_version is deliberately left alone. It asserts the Delta commit
history (get_table_versions() == ["0","1","2"] and _commit_version), so INSERT
OVERWRITE would add a commit and break the assertions; making it replay-safe
needs a real restructure. That is the same boundary ClickHouse#109641 drew when it retried
only that test's read-only DESCRIBE HISTORY.

Validation. Since the UC stall cannot be forced, a temporary local injection
reported a timeout after the batch had really executed and committed, which is
the worst case for a replay: 4/4 test executions passed and each logged the
retry. Reverting exactly one edit at a time then reddens the run for the
predicted reason (SCHEMA_ALREADY_EXISTS, TABLE_OR_VIEW_ALREADY_EXISTS, and a
duplicate row breaking the column assertions), so no edit is decoration. Without
injection: 4/4 on the pristine tree and 4/4 with the fix in the same wall-clock
band, 21 passed / 3 skipped for the whole module, and 40/40 over --count 10 on
all four parameter ids.

Failing job:
https://github.com/ClickHouse/ClickHouse/actions/runs/35763632624/job/107009114425

Co-Authored-By: Claude Opus 5 <[email protected]>
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.

4 participants