Skip to content

Fix tests that create databases with static names causing flaky check conflicts; improve flaky check coverage - #101553

Merged
fm4v merged 40 commits into
masterfrom
fix-find-tests-gh-auth
Apr 6, 2026
Merged

fm4v merged 40 commits into
masterfrom
fix-find-tests-gh-auth

Conversation

@fm4v

@fm4v fm4v commented Apr 1, 2026 •

Copy link
Copy Markdown
Member

When the flaky check runs tests 50 times in parallel, tests that create databases
with hardcoded static names (e.g. CREATE DATABASE test_02771) conflict with
each other — all 50 workers try to create the same database simultaneously.

This PR fixes the problem across ~160 test files using two approaches:

  1. Replace static names with {CLICKHOUSE_DATABASE_1:Identifier} / ${CLICKHOUSE_DATABASE_1} (SQL and shell tests respectively) — the test framework already provides CLICKHOUSE_DATABASE as a unique-per-run identifier; CLICKHOUSE_DATABASE_1 is its _1 suffix variant. Infrastructure: shell_config.sh exports CLICKHOUSE_DATABASE_1 and CLICKHOUSE_DATABASE_2; clickhouse-test already passes --param_CLICKHOUSE_DATABASE_1 to SQL tests.

  2. Add no-flaky-check tag for tests where the database name cannot easily be made dynamic — e.g. tests that check database names in their reference output, tests that use the db name in dictionary SOURCE(CLICKHOUSE(DB '...')) string literals with cluster configs that hardcode the name, or tests whose CNF hash stability depends on a fixed identifier.

Also fixed in ci/find_tests.py: use git diff instead of gh pr diff in CI runs (flaky check containers lack enable_gh_auth=True, so gh pr diff returned empty strings silently).

Also added to clickhouse-test:

  • --sequential-test-runs N — controls run count for sequential (no-parallel) and no-flaky-check tests (defaults to test_runs // 2)
  • In flaky check mode, no-flaky-check tests now run sequentially with --sequential-test-runs iterations instead of being skipped entirely

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

...

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.4.1.572

fm4v added 2 commits April 1, 2026 18:33
`get_diff_text` was calling `gh pr diff` unconditionally, but flaky
check containers do not have `enable_gh_auth=True` so `gh` is
unauthenticated. This caused Step 3 (coverage-relevant tests) to
always return 0 — the empty diff yielded no changed lines and the
CIDB coverage query was never issued.

Fix: in non-local runs use `git diff <merge_base_commit_sha>...HEAD`
(the merge base is stored in `JOB_KV_DATA` by `store_data.py`).
`gh pr diff` is kept for local runs only.

Also fix the cache guard: `not self._diff_text` treated an empty
string as uncached, causing `gh pr diff` to be called twice per job.
Changed to `self._diff_text is not None`.

Also fix `query_result.strip()` on a potentially-`None` CIDB result
(`or ""` guard on line 123).
@clickhouse-gh

clickhouse-gh Bot commented Apr 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [355aae4]

Summary: ❌

job_name test_name status info comment
Stress test (arm_msan) failure
Server died FAIL cidb IGNORED
MemorySanitizer: use-of-uninitialized-value (STID: 2410-47e0) FAIL cidb IGNORED

AI Review

Summary

This PR updates flaky-check test orchestration and rewrites many stateless tests to avoid static database-name collisions under parallel reruns, while also changing find_tests diff retrieval in CI. I found one additional high-confidence correctness issue in find_tests hunk parsing (inline comment posted), and there are several existing unresolved blocker-level inline findings from clickhouse-gh[bot] in the same areas. Verdict: request changes until the hunk parsing bug and blocker findings are addressed.

Findings

❌ Blockers

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 ✅
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Fix deleted-file hunk attribution bug in _parse_diff_hunk_ranges so hunks from +++ /dev/null are not recorded under the previous file.
    • Resolve remaining blocker-level inline comments already posted on this PR (including clickhouse-gh[bot] blockers in find_tests/functional_tests/clickhouse-test).

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Apr 1, 2026
Comment thread ci/jobs/scripts/find_tests.py Outdated
f"gh pr diff {self.info.pr_number} --repo ClickHouse/ClickHouse"
)
else:
merge_base = (self.info.get_kv_data() or {}).get("merge_base_commit_sha", "")

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.

Using merge_base_commit_sha computed against master can produce an incorrect diff for PRs targeting non-master base branches (for example backports to release branches). In those cases git diff <master_merge_base>...HEAD may include unrelated changes and skew coverage-based test selection.

Please derive the merge base from the PR actual base ref (or use the merge-commit parents in CI) before running git diff, so the diff always matches the PR scope.

The flaky check Docker container has no .git directory, so the previous
fix using `git diff <merge_base>...HEAD` failed with 'Not a git
repository'. `gh pr diff` also fails because there is no gh auth.

Use the unauthenticated GitHub API endpoint instead:
  https://patch-diff.githubusercontent.com/raw/ClickHouse/ClickHouse/pull/{PR}.diff

This works from any context (container, local, CI) without requiring
git history or gh authentication. `gh pr diff` is kept for local runs.
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Outdated
check(*sorting_key_type);
sorting_key_type->forEachChild(check);
if (sorting_key_type->haveSubtypes())
sorting_key_type->forEachChild(check);

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.

validateSortingKeyType now skips forEachChild when haveSubtypes is false, but DataTypeObject (JSON) is a real counterexample: it reports haveSubtypes() == false while still exposing nested typed paths via forEachChild.

That means nested Dynamic/Variant under JSON are no longer validated in ORDER BY when allow_suspicious_types_in_order_by = 0, so queries that previously threw ILLEGAL_COLUMN can silently pass. This is a behavior regression in type safety checks.

Please keep recursive validation unconditional (as before), or gate on a predicate that matches forEachChild semantics rather than haveSubtypes.

Two changes:

1. Remove force_ok_exit=True for flaky check.  The flag was unconditional,
   so any failure (actual test fail, server died, unexpected termination)
   was silently reported as Success.  Now flaky-check failures actually
   fail the CI job.

2. Move the time-limit enforcement from --global_time_limit inside
   clickhouse-test to Shell.run(timeout=...) on the Python side.

   With --global_time_limit, clickhouse-test raises GlobalTimeout inside
   the multiprocessing worker, which sends SIGTERM to every worker process.
   Workers die with 'Terminated: 15', cleanup is messy, and the result is
   marked 'terminated unexpectedly' (ERROR status).

   With Shell.run(timeout=...), SIGTERM is sent to the clickhouse-test
   process itself after the allotted time.  clickhouse-test handles SIGTERM
   via its own signal_handler, finishes the currently running tests, and
   exits cleanly — allowing the result to be collected properly.
…allel-self collisions

Tests that CREATE DATABASE with static (hardcoded) names fail when the
flaky check runs them in parallel with themselves — the second worker
finds the database already exists.  The existing mechanism renames only
the *primary* test database (to test_XXXXXXXX) but leaves explicitly
created extra databases unchanged.

This commit adds transparent name mangling for such tests:

1. Before executing a test, scan its content for CREATE DATABASE <name>
   where <name> is a bare identifier (not a query parameter like
   {VAR:Type}, not a shell variable like $VAR, not a keyword).

2. Derive a per-run suffix from the unique part of the primary database
   name: database='test_a1b2c3d4' → suffix='_a1b2c3d4'.

3. Write the test content with all occurrences of each extra database
   name replaced by name+suffix into a temp file in the test's tmp dir.
   Use the temp file for execution instead of the original.

4. After execution, normalize name+suffix → name in stdout (matching
   the existing replace_in_file(stdout, database, 'default') pattern).
   Reference files need no changes.

Two helper functions are added near replace_in_file():
- find_extra_databases(content): regex-based scanner with filters for
  SQL/shell keywords, shell-variable continuations (name${...}),
  names shorter than 3 chars, and built-in databases.
- mangle_extra_databases(content, extra_dbs, suffix): word-boundary
  replacement for all found names.

Validated on 114 tests with static extra databases (round-trip test:
mangle → normalize → compare with original reference: all pass) over
10165 total test files scanned.
# Flaky-check exits normally via --global_time_limit or --max-failures.
# Both are expected stopping conditions; do not block the pipeline.
force_ok_exit = True
if "parallel" in test_options and test_result:

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.

The PR removes the dedicated flaky-check non-blocking behavior (if is_flaky_check: force_ok_exit = True).

This changes job semantics: flaky-check can now fail the pipeline whenever there are 4+ failed tests or any non-test-runner error path, even though this job is designed as a signal-only flaky detector (bounded by --max-failures / global timeout), not a merge blocker.

Please restore explicit non-blocking behavior for flaky-check (e.g. keep force_ok_exit = True when is_flaky_check) and leave stricter blocking policy to dedicated required jobs.

…tdout

Previous approach mangled the test SQL but then normalized stdout back to
original names.  The correct approach (per user feedback) is:

1. Mangle the test file (name → name+suffix in a temp copy)
2. Mangle the reference file identically (name → name+suffix in a temp copy)
3. Compare stdout (containing mangled names) against the mangled reference

This way stdout is never post-processed and the comparison is direct.
self.reference_file is redirected to the temp mangled copy for the duration
of the test run.

Validated locally on 97 tests (89 with static extra databases + 8 unaffected):
- 45 passed, 10 skipped
- 22 'failures' are all pre-existing local env issues (missing test.hits
  dataset, no cluster, privileges, version incompatibilities)
- Only 1 failure (01470_show_databases_like) is mangling-related: the test
  uses LIKE '%01470' which doesn't match the suffixed name.  That test is
  tagged no-parallel and won't run in the flaky check.
Comment thread tests/clickhouse-test Outdated
)
with open(_mangled_ref_file, "w") as _f:
_f.write(_mangled_ref)
self.reference_file = _mangled_ref_file

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.

run_single_test mutates self.reference_file to a per-run temp path (args.test_tmp_dir/...) and never restores it.

That becomes a correctness issue on retries: after a failed run, _cleanup removes args.test_tmp_dir, but the same TestCase object is reused for retry (while True in run_tests). On the next run, self.reference_file still points to a deleted file, so diffing can fail for the wrong reason (missing reference instead of real output mismatch).

Please keep self.reference_file stable across runs (e.g. store the mangled reference in a local variable used only for this run, or reinitialize self.reference_file to get_reference_file at the start of each retry).

f"gh pr diff {self.info.pr_number} --repo ClickHouse/ClickHouse"
)
else:
self._diff_text = Shell.get_output(

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.

In CI path, get_diff_text still uses Shell.get_output with default strict=False.

If curl fails (transient network error, GitHub outage/rate-limit), Shell.get_output returns empty stdout and this method silently returns "". That recreates the original failure mode: no changed lines, no CIDB lookup, and zero coverage-based tests selected, but without a hard failure.

Please make diff fetch fail-fast here (e.g. Shell.get_output(..., strict=True)), or explicitly validate non-empty diff text and raise when fetching fails.

Tests tagged no-parallel never run concurrently with themselves, so
hardcoded database names cannot collide.  Skipping the mangling for
them avoids false failures in cases like 01470_show_databases_like
where the test uses a partial name in a LIKE clause that wouldn't
match the suffixed database name.
Comment thread tests/clickhouse-test Outdated
# Pattern to find hardcoded (static) database names in CREATE DATABASE statements.
# Captures the identifier after CREATE DATABASE [IF NOT EXISTS].
# Excludes query-parameter syntax like {VAR:Type} and function calls like currentDatabase().
_CREATE_DB_RE = re.compile(

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.

find_extra_databases only matches unquoted identifiers ([a-zA-Z_][a-zA-Z0-9_]*), so tests that create quoted static DB names are skipped and can still collide in parallel flaky-check runs.

Concrete example already in tree: tests/queries/0_stateless/03566_system_completions_table.sql uses:

CREATE DATABASE IF NOT EXISTS `0003566aaadatabase`;

find_extra_databases returns [] for this file, so no mangling is applied even though the DB name is hardcoded and shared by all workers.

Please extend detection/replacement to support backtick-quoted identifiers too (including replacement in mangle_extra_databases) so quoted static names are isolated the same way as unquoted ones.

.sh and .expect tests are executed directly as scripts, so the temp
copy must be executable.  Copy the original file's mode bits after
writing the mangled content.
Comment thread tests/clickhouse-test Outdated
)


def find_extra_databases(content: str) -> list:

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.

mangle_extra_databases currently replaces every word-boundary match in the whole file, so any false-positive token extracted by find_extra_databases rewrites unrelated SQL.

Concrete path to failure:

  • find_extra_databases scans raw text (including comments/strings) and can extract tokens that are not DB identifiers from real CREATE DATABASE statements.
  • mangle_extra_databases then globally rewrites that token everywhere.
  • If the token is cluster, statements like ... ON CLUSTER cluster ... become ... ON CLUSTER cluster_<suffix> ..., which changes execution semantics and can fail because that cluster does not exist.

Please restrict replacement to CREATE/USE/DROP/ATTACH/DETACH DATABASE identifier positions instead of global \bname\b substitution, or parse SQL AST and rewrite only database identifiers.

…ktick support

Two fixes:

1. Skip temp-file creation for non-.sql tests (.sh, .expect).
   .sh scripts source ../shell_config.sh relative to their own path.
   When the mangled copy is placed in test_tmp_dir (a subdirectory of
   the tmp area, not the suite dir), that relative path no longer
   resolves and the script immediately fails with 'No such file or
   directory'. Restrict temp-file mangling to .sql tests only, where
   the file is piped via stdin and no relative sourcing occurs.

2. Support backtick-quoted database identifiers.
   _CREATE_DB_RE now matches both bare identifiers and `quoted` names.
   find_extra_databases picks the non-None group.
   mangle_extra_databases replaces both `name` → `name_sfx` (quoted)
   and word-boundary name → name_sfx (bare).
   Example: 03566_system_completions_table.sql uses
   CREATE DATABASE IF NOT EXISTS `0003566aaadatabase` which was
   previously undetected and now gets correctly mangled.
if Path(test_output_file).exists():
Path(test_output_file).unlink()
Shell.run(command, verbose=True)
Shell.run(command, verbose=True, timeout=global_time_limit if global_time_limit > 0 else None)

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.

Replacing clickhouse-test's internal --global_time_limit with an external Shell.run(..., timeout=...) changes timeout semantics: the parent sends SIGTERM/SIGKILL to the whole process group, so clickhouse-test may stop without executing its own global-timeout path (GlobalTimeout in workers), cleanup, and final result aggregation.

This can produce partial/empty result artifacts and make flaky-check output less reliable exactly at timeout boundaries. Please keep --global_time_limit in the runner command and use process-level timeout only as a higher-level watchdog (with some safety margin).

fm4v added 2 commits April 2, 2026 21:40
The approach of rewriting test SQL and reference files at runtime has
too many edge cases and breaks tests in CI. Reverting completely.
When flaky check runs tests 50 times in parallel, tests that create
databases with static names (e.g. `test_02771`) conflict with each
other — all copies try to create the same database simultaneously.

Fix by running a script (`fix_static_db_names.py`) that:
- Rewrites 82 tests to use `{CLICKHOUSE_DATABASE_1:Identifier}` (SQL)
  or `${CLICKHOUSE_DATABASE_1}` (shell) instead of static names
- Adds `no-flaky-check` tag to 73 tests that either check database
  names in their reference output, need multiple extra databases
  (only `CLICKHOUSE_DATABASE_1` is defined in `clickhouse-test`),
  or use special-character database names (backtick-quoted)

assert len(db_names) == 1
name = db_names[0]
var = 'CLICKHOUSE_DATABASE_1'

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.

This script rewrites .sh tests to ${CLICKHOUSE_DATABASE_1} (replace_db_name_sh), but clickhouse-test does not export CLICKHOUSE_DATABASE_1 to shell tests (only CLICKHOUSE_DATABASE is exported).

That makes rewritten tests expand ${CLICKHOUSE_DATABASE_1} to an empty string and produce invalid SQL like CREATE DATABASE ;.

Please either:

  1. export CLICKHOUSE_DATABASE_1 from clickhouse-test for shell tests, or
  2. avoid rewriting .sh tests to ${CLICKHOUSE_DATABASE_1} until that env var exists.

fm4v added 4 commits April 2, 2026 22:53
After migrating tests from static database names to {CLICKHOUSE_DATABASE_1:Identifier},
several issues remained:

1. Shell tests: add CLICKHOUSE_DATABASE_1/2 exports to shell_config.sh
   so ${CLICKHOUSE_DATABASE_1} is available as a bash variable

2. Delete fix_static_db_names.py from test directory (clickhouse-test
   picks up .py files as tests, causing "Permission denied" failure)

3. Dictionary source DB field: {CLICKHOUSE_DATABASE_1:Identifier} in
   DB '...' string literal is not substituted. Fix: add USE statement
   after CREATE DATABASE, then use DB currentDatabase() in SOURCE

4. View/materialized view body: {db:Identifier}.table in CREATE VIEW AS
   SELECT body fails (ClickHouse bug - param substitution doesn't work in
   view body when the view name also uses a parameter). Fix: after USE,
   use unqualified table names in the view body

5. dictGet* function string arguments: '{CLICKHOUSE_DATABASE_1:Identifier}.dict'
   in string literals is not substituted. Fix: use unqualified 'dict' name
   since USE sets the current database context

6. EXISTS DATABASE, DETACH/ATTACH DATABASE, Buffer engine: add these
   patterns to the replacement (missed in original script)
- Use currentDatabase() in system.* table queries instead of
  {CLICKHOUSE_DATABASE_1:String} (required by style checker)
- Fix 01257: unquoted static DB name in dictionary SOURCE was not replaced
- Add no-parallel tag to 04036_system_commands_coverage (uses SYSTEM DROP)
… dictionary

The dictionary one_cell_cache_ints_overflow is defined in
tests/config/ints_dictionary.xml with hardcoded db test_01054_overflow.
Changing the database name breaks the dictionary source lookup.
Add no-flaky-check tag instead since the database name is constrained
by the external config file.
DROP TABLE dict_db_02179.dict_data;
DROP DATABASE dict_db_02179;
DROP DATABASE empty_db_02179;
DROP DATABASE IF EXISTS {CLICKHOUSE_DATABASE_2:Identifier};

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.

02179_dict_reload_on_cluster.sql now uses {CLICKHOUSE_DATABASE_2:Identifier} (lines 35/36/42), but clickhouse-test only injects --param_CLICKHOUSE_DATABASE and --param_CLICKHOUSE_DATABASE_1 for need-query-parameters tests.

For .sql tests this means parameter substitution for CLICKHOUSE_DATABASE_2 is missing, so the test can fail with an unknown query parameter error when parsing those statements.

Please also pass --param_CLICKHOUSE_DATABASE_2=<database>_2 in run_single_test next to CLICKHOUSE_DATABASE_1.

fm4v added 2 commits April 3, 2026 00:19
…m substitution

When {CLICKHOUSE_DATABASE_1:Identifier} is used as a qualifier before
table names starting with digits (e.g. .03711_join_with), ClickHouse's
parser fails with a syntax error after the backtick-quoted identifier.
The test also has 'long' and 'no-parallel' tags, so it won't run in
parallel in flaky check. Revert to static db name and add no-flaky-check.
…ed input table

After USE {CLICKHOUSE_DATABASE_1:Identifier}, unqualified CREATE TABLE goes
to the extra database. The test had both a data table 'input' (for the
dictionary source) and a distributed table 'input' in the same database,
causing TABLE_ALREADY_EXISTS. Rename the data table to 'dict_source' to
avoid the conflict while keeping the test logic intact.
fm4v added 2 commits April 3, 2026 16:16
Fix test failures:
- 01257_dictionary_mismatch_types: use currentDatabase() || '.table1_dict'
  for dictGet/dictHas calls so the dictionary is found correctly in
  ParallelReplicas mode where queries route to remote shards (127.0.0.2)
  that don't have the unqualified dict in their local context

- 02115_rewrite_local_join_right_distribute_table: update
  .oldanalyzer.reference to use normalized 'default_1' instead of
  static 'test_02115' database name (clickhouse-test normalizes the
  random test db name to 'default', so CLICKHOUSE_DATABASE_1 normalizes
  to 'default_1')

Flaky check improvements (clickhouse-test):
- Add --sequential-test-runs: controls run count for no-parallel and
  no-flaky-check tests (defaults to half of --test-runs)
- Add --no-flaky-check-sequential: when set in flaky check mode, run
  no-flaky-check tests sequentially (like no-parallel) with
  --sequential-test-runs runs instead of skipping them entirely
- is_sequential_test now returns True for no-flaky-check tests when
  --no-flaky-check-sequential is active
- apply_test_runs now uses sequential_runs for sequential tests so
  no-parallel tests also run fewer times than parallel tests
…flag

- 01257_dictionary_mismatch_types: revert to static db name, add
  no-flaky-check tag. The dictGet calls with currentDatabase() || '...'
  are complex and the test is no-parallel anyway.

- clickhouse-test: remove --no-flaky-check-sequential flag. When
  --flaky-check is passed, no-flaky-check tests now automatically run
  sequentially (like no-parallel) with --sequential-test-runs iterations.
  This is the intended default behavior in flaky check mode.
@clickhouse-gh

clickhouse-gh Bot commented Apr 3, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% (739,676/879,675) 84.10% (739,382/879,676) +0.00% (-294)
Functions 90.90% (798,428/878,616) 90.90% (798,288/878,510) +0.00% (-140)
Branches 76.60% (239,804/312,974) 76.60% (239,651/312,976) +0.00% (-153)

Changed lines: 100.00% (5/5) · Uncovered code

Full report · Diff report

@fm4v fm4v changed the title ci/find_tests: use git diff in CI instead of gh pr diff for coverage-based test selection Fix tests that create databases with static names causing flaky check conflicts; improve flaky check coverage Apr 4, 2026
fm4v added 2 commits April 4, 2026 09:17
04035_json_extract_null_handling, 04036_system_commands_coverage, and
04040_join_used_flags were swept up in a bulk git add and are unrelated
to the static database name fix work.
…n clickhouse-test

- functional_tests.py: pass --sequential-test-runs 30 when running in
  flaky check mode so no-parallel and no-flaky-check tests run 30 times
  (instead of being skipped or using the full 100-run count)

- clickhouse-test: remove the halving default for sequential_runs;
  value now comes directly from --sequential-test-runs (falls back to
  test_runs if not set, so behavior is unchanged when the flag is absent)
Comment thread tests/clickhouse-test
help="Number of runs for sequential (no-parallel) and no-flaky-check tests. "
"Defaults to half of --test-runs.",
)
parser.add_argument(

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.

--sequential-test-runs currently defaults to test_runs (sequential_runs = ... else test_runs), but the CLI help says "Defaults to half of --test-runs".

This mismatch is user-visible and makes flaky/local behavior hard to reason about. Please align one side with the other: either restore max(test_runs // 2, 1) as the fallback, or update the help/PR description to state that the fallback is --test-runs.

…nstant_arg

The test already resets max_threads to 0, but other random settings
(optimize_aggregation_in_order=1, max_threads=2, etc.) still cause
it to exceed the 180s flaky check time limit on test.hits.
Comment thread tests/clickhouse-test
elif self.is_sequential_test(test):
base = sequential_runs
else:
base = test_runs

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.

get_runs currently gives long precedence over sequential-only constraints (no-parallel / no-flaky-check). In flaky-check mode this under-runs many tests: e.g. a test tagged both long and no-flaky-check gets long_test_runs (typically 5) instead of --sequential-test-runs (30 in this job).

That weakens flaky coverage exactly for tests that cannot run in parallel.

Please make sequential precedence explicit in flaky-check mode, e.g. evaluate is_sequential_test before is_long_test (or use max(long_test_runs, sequential_runs) for sequential tests).

fm4v added 7 commits April 4, 2026 14:42
The test explicitly sets max_bytes_before_external_sort, max_bytes_ratio_before_external_sort,
and other sort/group-by spill settings to force external sort spilling.
Random settings can inject conflicting values (e.g. max_bytes_before_external_sort=0,
max_bytes_ratio_before_external_sort=0 with prefer_external_sort_block_bytes=1)
that prevent the sort from spilling to disk, so the ProfileEvents for
ExternalProcessingCompressedBytesTotal are 0 and the check fails.
In flaky check mode, apply random settings to ALL tests regardless of
no-random-settings or no-random-merge-tree-settings tags. This maximizes
the chance of catching flakiness caused by different settings combinations.
Tests that rely on a deterministic execution plan should use no-flaky-check
instead of no-random-settings if they are not compatible with the flaky check.
Instead of [t1×N, t2×N, t3×N] (all copies of one test before moving on),
build the run list round-robin: [t1,t2,t3, t1,t2,t3, ...] so each test
runs once per slot before any test gets a second run.

This ensures parallel workers receive a mix of tests rather than N
consecutive copies of the same test, which is especially important
for the flaky check where each test runs 100 times.
…ries

Coverage data lives in the public ClickHouse CIDB and is accessible from
any CI environment, including private-repo CI containers that cannot reach
internal CIDB endpoints (e.g. cidb.clickhouse-staging.com).

Switch the four coverage-query CIDB instances to use _PUBLIC_CIDB_URL =
https://play.clickhouse.com directly. Only get_previously_failed_tests
keeps Settings.CI_DB_READ_URL since it queries per-repo test history.
Comment thread ci/jobs/functional_tests.py Outdated
# The 45-min global_time_limit is the primary stopping condition for healthy PRs.
runner_options += " --max-failures 5"
# Run no-parallel and no-flaky-check tests sequentially with fewer iterations.
runner_options += " --sequential-test-runs 30"

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.

--sequential-test-runs 30 is a hardcoded policy constant here, but this job already computes rerun_count/worker count dynamically for flaky-check. Pinning sequential runs to a fixed number can quietly drift from intended flaky coverage as defaults evolve (for example, if --test-runs or timeout policy changes).

Could you derive this from existing flaky-check parameters (or expose it as a CI setting) instead of embedding a magic constant?

…ed ClickHouse/ClickHouse

In private-repo CI the PR number belongs to the private repo, so fetching
the diff from ClickHouse/ClickHouse with that PR number returns the wrong
diff or a 404. Use self.info.repo_name to get the actual repo.
Comment thread tests/clickhouse-test
result = []
for slot in range(max_runs):
result.extend(test for test in all_tests if slot < runs_per_test[test])
return result

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.

apply_test_runs now builds a round-robin run list, but right after that the constructor still does self.all_tests.sort(self.tests_in_suite_key_func) (line 3371). For --order=asc/desc, that sort groups equal test names together again, so the interleaving from this new block is lost and repeated runs can still execute back-to-back. Could we preserve the generated round-robin order (for example, sort before expansion, or skip the post-expansion sort when using this schedule)?

fm4v added 3 commits April 5, 2026 01:56
…ub API

In CI containers, fetch the diff via 'git diff {merge_base}...HEAD' using
the merge_base_commit_sha stored in JOB_KV_DATA by store_data.py. This
works for both public and private repos without requiring a GitHub token,
unlike the patch-diff.githubusercontent.com URL which is public-only.
…te repos)

CI containers have no .git directory, so 'git diff {merge_base}...HEAD'
always fails with 'Not a git repository'.

Use the GitHub REST API instead:
  GET /repos/{repo}/pulls/{pr_number}
  Accept: application/vnd.github.v3.diff

This works for both public repos (no auth needed) and private repos
(GITHUB_TOKEN env var, automatically injected by GitHub Actions).
… functional_tests: 50 runs, derive sequential runs

clickhouse-test:
- Sort the unique test list BEFORE expanding to repeated runs. The previous
  code sorted after expansion, which re-grouped equal names together under
  --order=asc/desc and destroyed the round-robin interleaving.

ci/jobs/functional_tests.py:
- Reduce flaky check test runs from 100 to 50. The 45-min time limit is
  the primary stopping condition; 50 runs provides sufficient coverage.
- Derive --sequential-test-runs from rerun_count // 2 instead of hardcoding
  30, so the ratio stays correct as the policy evolves.
# repos; private repos require GITHUB_TOKEN (available in Actions env).
token = os.environ.get("GITHUB_TOKEN", "")
auth = f'-H "Authorization: Bearer {token}"' if token else ""
self._diff_text = Shell.get_output(

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.

When diff includes a deleted file, +++ /dev/null does not match line.startswith("+++ b/"), so current_file is not reset and can remain from the previous file. Then the next @@ ... @@ hunk may be attributed to the wrong file.

Concrete trace:

  1. Parse file A: +++ b/src/A.cpp sets current_file = src/A.cpp.
  2. Parse deleted file B: +++ /dev/null leaves current_file unchanged.
  3. Parse hunk @@ -10,3 +0,0 @@ from deleted file B, it is appended under src/A.cpp.

That can pollute hunk ranges used for CIDB line-range selection and pick irrelevant tests.

Please reset current_file when seeing +++ /dev/null (or any non-+++ b/ file marker), and skip hunk collection for deleted files.

@fm4v
fm4v added this pull request to the merge queue Apr 6, 2026
Merged via the queue into master with commit 11ce418 Apr 6, 2026
158 of 159 checks passed
@fm4v
fm4v deleted the fix-find-tests-gh-auth branch April 6, 2026 11:37
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Apr 6, 2026
Mip182 pushed a commit to Mip182/ClickHouse that referenced this pull request May 9, 2026
…h-auth

Fix tests that create databases with static names causing flaky check conflicts; improve flaky check coverage
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

2 participants