Skip to content

CI: validate that the two LLVM coverage measurements are comparable - #112832

Closed
groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-llvm-coverage-completeness
Closed

groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-llvm-coverage-completeness

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

The LLVM Coverage gate fails a PR when line coverage drops more than 0.3 pp below the baseline.
Both percentages are merged from per-shard .profdata artifacts that are deliberately
optional=True, and nothing checked that either side had all of them. Five routes drop a shard
while every check-run stays green, from a producer merge that crashes to an aggregate merge that
discards a corrupt input under -failure-mode=warn.

Both directions are wrong. A short PR side fails an unrelated PR for a regression it did not cause
(example).
A short baseline has a low total, so a real regression passes; that case produces a PASS, emits no
failure row, and is invisible in any failure count.

Rather than raise the tolerance, which would paper over the measurement, the invariant is that a
verdict comes only from two complete measurements of the same artifact manifest. Each merge becomes all-or-nothing via
--failure-mode=any; each producer publishes no profile unless it ran what it planned; each shard
names its profile after its own coverage artifact, so completeness is exact set equality. That
fact travels beside the measurement in a sidecar riding on the existing
llvm_coverage.info artifact, so no new artifact name and no workflow file change is needed.
Otherwise the job reports SKIPPED with the reason, which counts as OK, and withholds every
comparative output, including the CI DB row that later baselines read. No master commit has a
sidecar yet, so a missing one means "unknown" and the fallback selector pass reproduces today's
behaviour until master republishes.

One residual is not covered: two runs can both be complete over the same 21 artifacts yet exercise
different code, for example when a commit changes which integration suites are selected. The
fingerprint detects artifact-list drift only, and is not a claim that the measured code matched.

Why tests/clickhouse-test gains a marker, and validation

All tests have finished. cannot carry the "this run executed what it planned" fact, because a
worker that dies abnormally still reaches it: the counter tested there is the number of tests
selected. Suppressing that marker would be the tidier layer, but such a run already exits non-zero
and is already reported as a failure, so suppression would only reclassify it from FAIL to ERROR
across every functional-test job. The new line is additive and leaves success_finish and its three
consumers untouched. If you would rather have the suppression, that is a deliberate CI semantics
change and I would send it separately.

92 new pytest cases plus one on the existing gate test, all pure and deterministic. Each of 51
mutations, one per behaviour introduced here, reddens its intended case. ci/tests/ run per arm
against a baseline exported from this branch's merge base: 607 collected here against 514 there,
0 new failures and 0 tests deleted by set difference, and the same pre-existing host-flaky rows in
both arms. Workflow config generation succeeds, which confirms no new artifact name was introduced.
The llvm-profdata behaviour relied on here was measured: -failure-mode=any on a corrupt input exits
1 and writes no file, while the clean path is byte-identical to -failure-mode=warn; a zero-length
input is accepted silently at both modes, which is why it is filtered explicitly.

The other three routes are an unbounded *.profdata glob, a run that stopped early yet still
publishes a valid but under-covered profile, and that zero-length .profraw. When a measurement is
incomplete the full report is still published, labelled partial measurement: N of M shards, as the
best artifact for identifying the missing shard.

groeneai and others added 6 commits July 31, 2026 02:56
The LLVM Coverage diff gate compares a baseline line-coverage percentage
against the current one and fails the PR on a drop above 0.3 pp. Both
percentages are merged from per-shard .profdata artifacts declared
optional=True, and neither side was ever validated as a complete
measurement. Five independent routes drop a shard while every check-run
stays success: a producer merge that crashes and uploads nothing, an
aggregate merge that discards a corrupt input under -failure-mode=warn, an
unbounded *.profdata glob that never compares what arrived against what was
expected, a run that stopped early yet still publishes a structurally valid
but under-covered profile, and a zero-length .profraw, which llvm-profdata
ignores silently at every --failure-mode.

The defect is symmetric and the second direction is worse. A short PR side
fails an unrelated PR for a regression it did not cause. A short baseline has
a low total, so a real regression passes; that case produces a PASS, emits no
failure row, and is therefore invisible in any failure count.

Enforce one invariant: a verdict, and every number derived from it, is
produced only from two complete measurements of the same artifact manifest.
Each fact is produced by the component that owns it. All four merge sites
become all-or-nothing via --failure-mode=any, which lets the three producer
two-string corrupt-profile parsers go away. The functional and integration
producers create no profile when the run did not execute what it planned;
the functional fact comes from a new authoritative marker inside
tests/clickhouse-test, because "All tests have finished." is also printed by
a run that lost a worker (the counter tested there is the number of tests
SELECTED), and the integration fact is recorded at the phase scheduler and
snapshotted before the coverage block resets has_error. Zero-length raw
inputs are rejected. Each shard names its profile after its own coverage
artifact, so completeness is exact set equality rather than a difference,
which would accept a foreign profile, and the aggregate merge receives an
explicit expected-intersect-present file list instead of a glob.

A llvm_coverage.meta.json sidecar rides on the existing llvm_coverage.info
artifact's path list, so no new artifact name is introduced and no workflow
file changes. The selector prefers a complete, manifest-matching ancestor and
keeps today's first-match walk as a fallback. The consumer judges only when
both sides are complete over the same manifest and otherwise reports SKIPPED
with the reason, which counts as OK, withholding every comparative output
including the CI DB row on the master path that later baselines read. The
full HTML report is still published, labelled as a partial measurement,
since it is the best artifact for identifying the missing shard.

No master commit published before this carries a sidecar, so a missing
sidecar means "unknown" and the fallback selector pass reproduces today's
behaviour until master republishes; nothing starts failing at merge time.

Not covered, and disclosed in the description: two runs can both be complete
over the same artifact manifest while exercising different code, for example
when a commit changes which integration suites are selected without changing
the manifest. The fingerprint detects artifact-list drift only.

The praktika change is one additive line giving a locally-run job its own
JOB_CONFIG, mirroring _setup_env; without it a locally-run coverage shard
cannot derive its profile name. It is deliberately not registered in the
coverage digests, because CI never executes generate_local_run_environment.
… unit-test jobs working

Two guards introduced by the previous commit did not reach the path they exist to
serve. Both were found independently by review and by the automated gate.

The differential coverage script was invoked unconditionally. Its own precondition
exits 1 when llvm_coverage.info is absent, which is exactly the state a failed
aggregate merge deliberately leaves behind: the merge writes `failed` to its marker,
publishes no .info and exits 0 so the job can report SKIPPED. A non-zero command
makes the sub-result FAIL, and the script dies before genhtml, so the output
directory is missing and the SKIPPED override nested under that directory's
existence is never evaluated. The job therefore reddened on precisely the run that
four separate places in this change promise it cannot. The absent-.info condition
is now evaluated before the invocation, and the invocation is skipped in that case;
the result keeps the same name so the report links are unaffected. The existing
override stays, because it still serves the other incomparable causes, where the
script does succeed.

The unit-test profile naming block sat at unconditional top level, between the
gtest run and the result write. The six sanitizer Unit tests parameter sets declare
no coverage artifact, so the assertion on `provides` fired there and the job died
without writing its result, discarding the gtest outcome rather than mis-reporting
it. The block moves back inside the existing `.profraw` guard, where the profile
filename was a literal before this change: a non-instrumented binary emits no
.profraw, so there is nothing to name. The assertions are unchanged; they are
correct for the one job that does declare an artifact.

The two cells that covered these lines only checked that a substring appeared in
the job source, which is how both defects survived. They are replaced by
behavioural cells that execute the real statements in their real order, and the one
that matters asserts the composite job result is green rather than only the
sub-result's status. Three mutations, one per behaviour, each reddening its
intended cell.

Co-Authored-By: Claude Opus 5 <[email protected]>
…eport an empty measurement as skipped

Four defects in the completeness protocol, all in the ci/ Python.

The baseline sidecar and the selected-base marker were read above the differential
script, which is their only writer: the wget in generate_diff_coverage_report.sh
fetches base_llvm_coverage.meta.json and the echo near its end writes
selected_base_commit.txt. Both reads therefore returned nothing on every run, so
comparable() took its absent-baseline branch and the gate abstained even when both
sides were complete and the artifact fingerprints matched. It could not self-heal,
because a download cannot be observed by a read that already happened, and it was
invisible: the reason string is the same one correct behaviour emits during the
first days after this lands, so the CI log of the broken state was identical to the
log of the working one. The reads now sit in the branch that runs the script, after
it. On the path where no coverage data was published the marker is not read at all,
since nothing wrote one.

With no shard profile arriving at all, the file list rendered as the empty string
and the merge script's unbounded-glob guard cannot distinguish that from the
variable being omitted, which is the case it exists to catch. It exited 1 before
writing its status marker, so the job went red on exactly the input the protocol
promises to report as a green skip. The job now recognises the empty set itself and
builds the skipped sub-result directly. The script keeps its guard and is unchanged;
no sentinel value is passed to it and no marker is fabricated for it.

A PR side already known to be short a shard still ran the script, so the log printed
a baseline percentage, a current percentage and a delta between two identical
notices saying the comparison had been skipped. Every published comparative surface
was already withheld, so nothing incorrect was exported, but a reader could take an
abstention for a verdict, which is the confusion this gate exists to remove, and
genhtml ran on a measurement already known incomparable. The four causes that depend
only on this run's own sidecar now short-circuit before the script. They moved into
completeness.current_side_reason, which comparable() also calls, so the short-circuit
reason cannot drift from the verdict. Baseline-side causes are unchanged and still
reach the later override: the script is what fetches the baseline, so they cannot be
known any earlier, and a test pins that the script still runs for them.

The harness for the diff gate could not observe any of this. Its stub created none
of the files the real script creates, so the baseline side was unobservable under
both orderings, and its synthetic sidecar omitted the schema version, so a verdict
was unreachable even had a baseline existed. Both of its cells passed against the
broken ordering. The stub now reproduces the real outputs using the production
sidecar functions, the synthetic sidecar is a real one built over real profile
files, and the healthy-path cell asserts the runtime verdict rather than a
sub-result status that a later statement overrides anyway.

While writing the test for the third defect I asserted that no delta line is printed
and found the assertion could never fail, because the harness executed a region
ending six statements before those prints. The region now covers them, a check keeps
them inside it, and the healthy path demonstrates they are reachable, which is what
makes the absence meaningful.
Fix round 3 of the LLVM coverage completeness protocol. The short-circuit added
in the previous round correctly stops the differential script from running on a
measurement already known incomparable, but two downstream blocks were never
taught about the state that creates, so on exactly the paths this change exists
to serve the job log contradicted itself.

The differential script is the sole writer of changes.diff and
current.changed.info. When the current side is known incomparable the script
never runs, so both files are absent, so the uncovered-code block's own
incomparable branch was unreachable and control fell through to the arm that
reports "No C/C++ source files changed" - a statement about the PR's contents
that was never established, on a run whose C++ files may well have changed. The
diff-report line printed the same false sentence. Both now test comparability
first, so the reason that was actually established is the one reported, while a
genuinely comparable run that found nothing coverable still reports exactly as
before.

A baseline-side cause is only knowable after the script has run, so that path
legitimately reaches the block that parses both lcov summaries. It printed
baseline, current and delta before the abstention override was applied, putting
three numbers between two identical skip notices - the reading confusion this
gate exists to remove. The summary parsing and those three prints are now gated
on comparability; a comparable run still prints all three, and the override
stays where it is, since it is the only thing that turns the sub-result into
SKIPPED on that path.

The coverage marker predicate in tests/clickhouse-test had no live test: the
existing cell asserted that both operand substrings appear near the marker,
which still passes when the conjunction is swapped for a disjunction - and that
swap admits both states the marker exists to exclude, a killed worker and a
zero-test run, each of which then lets a short profile be merged. The cell now
executes the real predicate over both signs of both inputs. The predicate itself
is unchanged.

Nine mutations, each reddening exactly its predicted cells; the operator-swap
mutations are verified per row. The gate module's verdict-block extraction moved
from a line range to AST nodes, because the drop assignment and the verdict
chain now sit at different nesting depths; that also makes it carry all three
arms, so its pass path is executed rather than merely not-failed.
Three residues of the same defect: _diff_ran was being used as a proxy for
"this run produced a verdict", but it is False for three materially different
reasons and only one of them - nothing coverable changed on a comparable run -
licenses an OK or the "no C/C++ source files changed" sentence.

The abstention override was nested inside `if _diff_ran:`. When the
differential script ran, selected an incomplete baseline and then took its own
no-coverable-files exit, no report directory was created, so the override never
executed and the diff sub-result kept the OK it was constructed with: a green
verdict for a run that did not judge. It is now an independent statement placed
after the whole construct, guarded on comparability alone, where the
degraded/not-degraded arm cannot clobber it either.

The coverage-comment and CI-DB-row branch selected its message on _diff_ran, so
a current-side cause - where the script is deliberately never invoked - printed
a claim about the PR's contents immediately after the real incompleteness
reason. It now tests comparability first, as the two sibling sites already do.

The full-report link was appended unconditionally. The merge phase can now
legitimately produce no report (it exits 0 without generating HTML when
merged.profdata is absent, where the merge base exited 1 and reddened the job),
so the intended green SKIPPED result advertised a URL that 404s, on master runs
too. The link is now gated on the same entry point collect_html_report_files
requires, so the link and the artifact cannot disagree.

Tests: nine new cases, each mutation-verified. The harness slice is extended
through the comment branch, without which four of them would assert on
statements that never execute; a self-assert pins that reach, and shortening the
slice makes all four fail loudly rather than pass vacuously.

The sibling gate test selected the verdict node by requiring one `if` that was
both `not _measurement_comparable` and contained `set_failed()` - a conjunction
that only held while the abstention and the verdict were arms of one chain, i.e.
it encoded the pre-fix structure as an invariant. Each statement is now selected
on one property and the comparability guard is taken from the job's own node, so
the emitted snippet cannot describe a nesting the job no longer has.
…omparable

The abstention that reports "we could not compare the two coverage
measurements" was hoisted out of the `if _diff_ran:` chain in the previous
round so that a baseline-side cause could still reach it. Hoisting it exposed a
second problem the nested form had masked: unlike the two sibling abstentions,
which construct a fresh Result via `Result.create_from`, this one MUTATES the
Result that `Result.from_commands_run` produced for
generate_diff_coverage_report.sh. That Result is already FAIL when the script
exited non-zero, and SKIPPED is inside `Result.is_ok()`, so an unguarded
`set_status` turned a real tooling failure green.

The two states genuinely co-occur on an ordinary post-merge run. The script
writes base_llvm_coverage.meta.json and selected_base_commit.txt before several
of its own later failure paths - `exit 1` on an empty GitHub compare, and under
`set -euo pipefail` any failure of the two `gh api` calls, of either
`lcov --extract`, or of `genhtml`. In each of those the report directory is
absent, and the baseline side is incomparable for every baseline published
before this change because those commits carry no sidecar. A failed report must
stay RED: merge_llvm_coverage.sh states that contract verbatim.

Guarding on `is_ok()` rather than `not is_failure()` also excludes ERROR, which
is the conservative direction; only a result that is not already a failure may
be downgraded, so a run that merely could not be compared still reports SKIPPED
and keeps the job green.

The new pytest case drives the mixed state through the real job source and
asserts the composite is not ok. Its harness parameter forces the script's
status to failure while still writing the baseline outputs the script writes
before failing, because writing them first is what makes the state real. The
sibling gate module's AST selector now matches a test that contains the
comparability negation rather than equals it, and its Result stub delegates to
the real `is_ok`, so neither can drift from production.
@groeneai

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

Pre-publication review by an independent model, run once per revision of this branch:
6 rounds, 15 findings. Every finding was verified against the code before I adjudicated it,
and each round's fixes were re-reviewed in the next.

# Sev Finding Verdict Evidence / action
1 ❌ The intended green SKIPPED verdict is unreachable when the aggregate merge fails, because the differential script's own precondition exits 1 on a missing llvm_coverage.info and reddens the sub-result first AGREE, fixed The current-side verdict is now computed before that script runs, so the abstention is reached instead of the failure
2 ❌ Deriving the profile name in unit_tests_job.py asserts in the six non-coverage Unit tests (*) jobs, which declare no coverage artifact AGREE, fixed The whole naming block moved inside the .profraw guard; the six ParamSets were resolved by AST to confirm they declare none
3 ❌ The baseline sidecar and the selected-base marker were read ABOVE the only thing that writes them AGREE, fixed Both reads moved below the script; a test now drives the real statements in real order, so a re-inversion is observable
4 ❌ An empty merge input set reached a guard that cannot distinguish it from an omitted variable, so a zero-shard run reddened AGREE, fixed That case now reports SKIPPED without invoking the script, and the marker read is skipped rather than fabricated
5 ❌ An abstention nested inside if _diff_ran: cannot be reached when the report directory is absent, so a run that selected an incomplete baseline and then found nothing coverable kept a green OK sub-result AGREE, fixed The abstention became an independent statement after the whole construct
6 ❌ Hoisting it exposed the opposite defect: it MUTATES a result that may already carry the script's own FAIL, and SKIPPED is inside is_ok(), so a real tooling failure went green AGREE, fixed Guarded on is_ok() as well. I raised this in my own review before reading the gate output and the gate raised it independently, citing my finding id. At that point the result can only be SKIPPED, OK or FAIL, so the guard admits exactly the two intended downgrades; is_failure() would have admitted ERROR
7 ❌ A failed llvm-profdata merge can leave its -o target behind, so the promised all-or-nothing measurement is not delivered DISAGREE Measured on the tool the pipeline uses, four arms: corrupt-only and mixed valid-plus-corrupt both give exit 1 with NO output file under -failure-mode=any (while =warn gives exit 0 and a short file, which is the defect being fixed), and with a pre-existing target the failing merge leaves it BYTE-IDENTICAL rather than truncating it. So a surviving file can only ever be a stale one, and every stale-file route is unlinked before the merge in all four sites. The probe backing this finding had to write the output from a shim in order to observe it
8 ⚠️ The two comparison sides can be complete over different code even when both are complete over the same artifact list AGREE, disclosed Not fixable at this layer: closing it needs a canonical shard specification shared by producers and consumer. Stated in the description as an uncovered residual, and the fingerprint is deliberately not described as a claim about the measured code
9 ⚠️ A baseline-side abstention still parsed both summaries and printed a delta, putting three numbers between two abstention notices AGREE, fixed Parsing and the three prints are now inside the comparability guard; a comparable run still prints all three, asserted on exact values from distinct sides so a swapped argument is visible
10 ⚠️ An incomparable run printed No C/C++ source files changed, a cause that was never established AGREE, fixed All three message sites test comparability first. I enumerated every reader of the report-directory flag rather than shaving one site at a time, because this finding had already recurred
11 ⚠️ The green no-profile path published a report link that 404s AGREE, fixed The link is gated on its own entry point, on both the pull-request and the master path
12 ⚠️ The marker-predicate test checked that two operand substrings appear near each other, which passes when the and becomes an or AGREE, fixed It now compiles and executes the real predicate over all four input combinations and asserts the matrix as one equality
13 ⚠️ The producer tests are source-text reads, so their guards could become no-ops while the assertions stay green DISAGREE Refuted by the mutation ledger, which is behavioural: each semantic neutering this names was applied and reddened its intended cell. Two of the cited cells assert statement ORDER rather than substrings, which is the property that matters here, and the prescribed remedy would assert a post-condition against a pre-condition the tool never produces (see #7)
14 ⚠️ Countable claims in the description went stale as the diff changed AGREE, fixed Re-derived by script rather than carried forward: 92 new cases plus one net on the existing gate module, 51 mutations from a ledger that now reconciles with its own rows, 607 collected against 514 at the merge base. The host-flaky row count varies run to run, so that claim is now qualitative rather than a number that would be wrong either way
15 💡 Two comments cite a line two lines off, and the pre-merge unlink is justified by a truncation the tool does not perform AGREE, noted The unlink is still correct for the reason those comments give second: the completion gate can skip the merge entirely, so nothing would open the target and a stale profile would be published as this shard's contribution

Severity: blocker, major, nit. DISAGREE verdicts carry recorded evidence and are terminal
per finding. Findings on hunks unchanged by a later round are dropped.

Session id: cron:clickhouse-review-slot-51:20260731-221200

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, at two levels. The tool premises are measured directly: llvm-profdata -failure-mode=warn on a good + corrupt pair exits 0 and writes a SHORT profile, -failure-mode=any exits 1 and writes nothing, the clean path is byte-identical between the two modes, and a zero-length .profraw is accepted silently at both. The gate-level defect is reproduced by the new pytest rows, which fail on the pre-fix code and pass on the fixed code. Nothing here is randomized.
b Root cause explained? Yes. The coverage total is merged from per-shard .profdata artifacts declared optional=True, and neither side of the comparison was ever validated as complete. Five routes make a side short while every check-run stays success, so the gate compares two different-sized measurements: short PR side gives a fake FAIL, short baseline hides a real regression behind a PASS.
c Fix matches root cause? Yes. It does not raise the 0.3 pp tolerance (that guards the symptom of a measurement bug and cannot fix it) and does not make the profdata artifacts non-optional (that reverts a deliberate decision which has its own regression test, ci/tests/test_optional_artifact.py). Each fact is produced where it is known and validated once, before any consumer of the numbers.
d Test intent preserved / new tests added? Yes. 92 new cases plus one on the existing gate test; no assertion weakened. Six of them are the r1 round: the two cells the reviewer flagged as source-substring reads are now behavioural, driving the real job source in real statement order, and the one that matters asserts the COMPOSITE job result is green rather than just the sub-result's status. The over-tolerance and 57 pp rows still FAIL, so the gate is not disabled, and a deliberate row asserts that a completed run WITH failing tests still publishes its profile, so an over-broad gate cannot silently delete coverage on the common path. The r2 round added seven more and REPLACED one that was vacuous: the healthy-path cell now asserts the runtime verdict (comparable is True, an empty reason and the selected base commit) instead of a pre-override sub-result status, and its harness reproduces the real baseline artifacts with the production sidecar functions so the ordering it exists to pin is observable at all. The r3 round added three more and rewrote one: the three new cells observe print_res and the captured log rather than source text, and the marker cell now EXECUTES the real predicate over all four (total_tests_run, killed) combinations instead of checking that two operand substrings appear near it, because replaying two such substring checks against a window whose and is swapped for or passes. One pre-existing source-text cell pinned the very conjunction r3 removes, so it was updated to pin the new unconjoined guard and to assert the old form is gone; mutation A proves it is still load-bearing. The r4 round added nine more and strengthened three plus one sibling-module self-assert: the new cells cover the one matrix state nobody had driven (the differential script ran, selected an incomplete baseline, then found nothing coverable - which kept a green sub-result), the coverage-comment branch that had been below the harness's reach, and the full-report link. The r5 round added one more: the state where the differential script itself FAILED while the sides are also incomparable, which the r4 hoist had allowed the abstention to overwrite with a green SKIPPED. Cell count 92 in the new module plus one net new on the gate module (13 against 12 at the merge base); 0 cells deleted across the whole diff.
e Both directions demonstrated? Yes. 51 mutations, one per behaviour introduced here, each reddening its predicted row; each mutation is the pre-fix behaviour of one item. Two that survived the first pass were weak assertions of mine, not weak fixes, and were rewritten to execute the shell scripts against synthetic tool shims. One r1 mutation initially reddened two rows instead of one because I had written it as an added call rather than a moved one; re-expressed faithfully it reddens exactly its intended row. In r2 the four mutations each reddened exactly their intended set, and one assertion of my own turned out to be vacuous because the harness executed a region that stopped six statements short of the lines it asserted on; I extended the region and made the healthy path demonstrate those lines are reachable rather than shipping the assertion. The r3 round ran nine mutations, 9/9 reddening exactly their predicted cells, each md5-verified restored. Three of them (F, G, H) are verified per-ROW: and->or moves the killed-worker AND zero-tests rows, dropping either operand moves only its own row, and the five pre-existing transcript cells stay GREEN under all three because they pin the results parser rather than the predicate, which is what documents that the new cell is not redundant with them. The r4 round ran seven, 7/7 reddening exactly their predicted cells, each applied alone with all three touched files md5-verified restored afterwards. Two are worth naming: shortening the harness slice AND deleting its new self-assert makes all four new comment-branch cells fail LOUDLY on positive assertions about output an unexecuted branch never produced, which is what proves they are not vacuous; and testing the report DIRECTORY instead of its index.html entry point reddens the no-report cell, which is what proves the entry-point choice is load-bearing rather than cosmetic. The r5 round ran three, 3/3 reddening exactly their predicted cells, each applied alone with both touched files md5-verified restored afterwards. Dropping the new and diff_res.is_ok() term restores the previous round's shape and reddens the new cell on its diff_res.status assertion; dropping the comparability term instead reddens the two must-stay-OK cells, which is what proves that term is still load-bearing after the change; and neutering the harness parameter that forces the script's status to failure reddens the new cell, which is what proves it is not vacuous. Each of the first two also reddens the sibling gate module's own self-assert, a second and independent detector of the same regression reached from source structure rather than from behaviour.
f Fix is general across code paths? Yes. All four merge sites, all three producers, and both branch paths (PR and master) are covered; git grep -nE "\*\.profdata|LLVM_ARTIFACTS_LIST|failure-mode" -- ci/ finds no other site. Two asymmetries are deliberate and stated: the aggregate site cannot be handled like a producer (a failed producer merge means "no profile", which is the design), and the unit-test producer needs no completion gate because a failed run exits non-zero and the runner already skips the artifact upload. The r1 round closed the two places where a guard existed but did not reach the path it serves: the absent-.info verdict is now computed BEFORE the differential script runs (its own precondition exits 1 on that input, which turned the intended SKIPPED into FAIL), and the unit-test naming block sits inside the .profraw guard so the six non-coverage Unit tests (*) ParamSets, which declare no artifact, are unaffected.. The r2 round closed three more of the same shape: two reads sat above the only writer of the files they read, so they could observe nothing on any run; an empty merge input set reached a guard that cannot distinguish it from an omitted variable and exited non-zero; and the four current-side incomparability causes, already knowable before the differential script runs, are now short-circuited there while the baseline-side causes stay with the later override because that script is what fetches the baseline. The r3 round closed two more of the same shape, both places where a downstream block was never taught about the state the r2 short-circuit creates: the uncovered-code branch tested _diff_inputs_exist before comparability, but on a current-side cause the differential script never runs and it is the sole writer of both diff inputs, so the dedicated incomparable branch was unreachable and the job reported No C/C++ source files changed on runs whose C++ files may well have changed; and the diff-report line printed the same false sentence. Both are now ordered comparability-first, and mutation B2 shows the two halves are independently load-bearing, while a reverse-direction cell keeps the fix from being widened into always abstaining. The r4 round re-enumerated all eight real readers of _diff_ran and closed the two that were not already conjoined with comparability or dominated by a comparable branch: the one deciding whether the abstention is reachable at all (it was nested inside if _diff_ran:, so a run whose script ran, selected an incomplete baseline and then found nothing coverable kept the OK sub-result it was constructed with) and the one selecting which message the coverage-comment branch prints. No seventh unguarded reader exists. It also gated the full-report link on its own artifact, covering BOTH the PR and the master path since that block sits outside if not is_master_branch:.
g Fix generalizes across inputs? Yes: complete, short, extra and empty present-sets; absent, corrupt, newer-schema and torn sidecars; artifact-manifest growth; zero-input producers; both merge outcomes. Type-wrapper matrix is N/A, there is no src/ change.
h Backward compatible? Yes, and load-bearing. No master commit published before this has a sidecar, so a missing sidecar means "unknown" and yields SKIPPED, never a failure; the selector's fallback pass reproduces today's selection until master republishes. The schema version makes a future field addition degrade to "unknown" rather than throw. No setting, no SettingsChangesHistory.cpp, no serialization format, no CI DB schema change.
i Invariants and contracts preserved? Yes. success_finish and its three consumers are byte-identical (the new field is additive beside it); the new tests/clickhouse-test line does not touch the existing marker text, exit_code or sys.exit semantics; the integration completion snapshot is taken before the block that resets has_error, and the present-profile snapshot before the merge writes into the directory being listed, both asserted by tests; optional=True on the .info is paired with a consumer-side contract check, so weakening that guarantee cannot make the job silently compare nothing. r1 added two more, each asserted rather than argued: a run that published no coverage data yields a green COMPOSITE job result (SKIPPED counts as OK, so the sub-result status alone was not sufficient to check), and the unit-test job never raises between from_gtest_run and complete_job(), which would discard the gtest outcome rather than mis-report it.. r2 added three: a variable read after the if/else is now bound on both paths; the merge sub-result is appended to the results list exactly once on both paths, and its status marker is read only when the script that writes it actually ran, so no marker is ever fabricated; and the reason a caller short-circuits on is produced by the same function the verdict uses, so the two surfaces cannot drift. r3 added three: the two lcov summaries are parsed and the delta printed only for a comparable measurement, so a baseline-side abstention no longer prints three numbers between two identical skip notices, while a comparable run still prints all three (asserted on exact values from distinct stubbed sides, so a swapped argument is visible); the SKIPPED override stays inside if _diff_ran: and is still the only thing that turns the OK sub-result into SKIPPED there; and every new cell asserts the real COMPOSITE Result.is_ok(), so an abstention still cannot redden the job. r4 added four: the abstention's body is byte-identical to the block that was hoisted, so there is still exactly ONE producer of the skip string; it now runs strictly AFTER the verdict arm, so a FAIL can never be overwritten by it; the current-side path's construction-time SKIPPED is merely re-set to the same value, checked idempotent; and a published report URL now addresses an artifact that exists, with the URL string asserted verbatim so a healthy run's link cannot silently move. r5 added one, and it is the strongest of the set: the abstention MUTATES a result rather than constructing one, unlike its two siblings, so it is now guarded on is_ok() and a failed differential script keeps the job RED - merge_llvm_coverage.sh states that contract verbatim. The guard admits exactly the two intended downgrades: at that point the result can only be SKIPPED, OK or FAIL, and is_ok() is {OK, SKIPPED, XFAIL}, so FAIL is excluded while is_failure() would have admitted ERROR.

Session id: cron:clickhouse-review-slot-51:20260731-221200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alexbakharew @maxknv, could you review this? The coverage gate compared a baseline total against a PR total without checking that either side had all 21 shard profiles, so a short PR side failed unrelated PRs and a short baseline hid real regressions behind a pass; each side now publishes and validates its own completeness before any verdict, and reports SKIPPED with a reason when it cannot.

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

clickhouse-gh Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [df79405]


AI Review

Summary

This PR hardens the LLVM Coverage gate by carrying coverage-completeness metadata end to end and refusing to compare incomplete measurements. The overall direction is correct and the test coverage is substantial, but there are still two contract gaps around baseline selection and emitted metadata that can make the gate skip when a usable baseline exists, or record the wrong baseline commit for the comparison that actually ran.

Findings

⚠️ Majors

  • [ci/jobs/scripts/generate_diff_coverage_report.sh:68-72] The prefer_complete selector stops on the first ancestor whose sidecar says complete and whose manifest matches, but comparable() rejects additional states after that: a newer schema_version and a torn info_digest/.info pair. In either case the job now selects an unusable baseline, then downgrades the whole check to SKIPPED instead of continuing to the next older usable ancestor. Minimum fix: keep walking unless the candidate also satisfies the same schema/digest checks that the Python-side comparability gate enforces after download.
  • [ci/jobs/llvm_coverage_job.py:597] The job now reads selected_base_commit.txt because the compared baseline is often not the nearest master ancestor, but the emitted coverage_comment.json still records base_commit_sha. Whenever the selector skips the nearest ancestor and compares against an older complete one, the coverage_ci.coverage_data row points to the wrong baseline revision. Minimum fix: serialize _selected_base_commit for PR rows so downstream analysis matches the report that was actually generated.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: make baseline selection skip unusable candidates instead of stopping at the first manifest match, and emit the actual selected baseline commit in the coverage metadata.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Aug 1, 2026
fi
echo "Found coverage file at ${COVERAGE_URL}"
wget --quiet "${COVERAGE_URL}" -O base_llvm_coverage.info
FIRST_BASE_COMMIT="${TEST_COMMIT}"

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.

Before breaking on this candidate, the selector still needs to reject the cases that comparable() later treats as unusable: a newer schema_version and a torn info_digest/.info pair. Right now the pass-1 predicate only checks complete + manifest_fp, so the nearest ancestor can win selection here and then force the whole job to SKIPPED instead of falling through to the next older usable baseline. Please keep walking unless the candidate also passes the same schema/digest checks after download.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Both findings reproduced against the code and are fixed in 33b26ce.

Selection predicate weaker than the usability predicate. Correct, and the
consequence is the one this PR exists to prevent: a candidate that passes the
weaker test and fails comparable won selection and then abstained the whole job
instead of falling through to the next usable ancestor. Rather than duplicating the
schema_version and info_digest checks in the selector, pass 1 now calls
comparable itself, so the two cannot drift apart again. The digest check needs the
candidate's .info bytes, so the download moves above the decision and a rejected
candidate's files are removed before the walk continues. Pass 2 is untouched and
still selects exactly as before.

Verified the fallthrough actually reaches the next older candidate: with a newer
schema_version on the nearer ancestor the selector picks the farther one, same for
a torn info_digest/.info pair, and when pass 1 rejects every candidate pass 2
still selects the nearest. In all three outcomes a non-empty
base_llvm_coverage.info and the marker are on disk for the job to read.

Metadata attributes the delta to the wrong baseline. Correct, and it was the
more corrosive of the two because the row is stored with nothing revealing the
substitution. coverage_comment.json now serializes _selected_base_commit,
falling back to base_commit_sha when no marker exists so the row never loses its
baseline key. That is the only consumer keyed on it: the hook reads this field
straight through into coverage_ci.coverage_data, and the master-side payload
writes "" by construction. Existing stored rows are not backfilled -- the
substitution was not recorded at the time, so which revision each old row actually
measured is not recoverable.

Six test rows, each verified to fail without its fix (restoring the previous
selector reddens the two walk-past rows; restoring the old payload line reddens both
metadata rows). The selector harness now imports the real completeness module
through WORKSPACE_PATH, so the predicate under test is the production function
rather than a copy -- breaking that import reddens the pass-1 rows, which is what
shows they are not vacuous.

ci/tests: 97 passed in the completeness suite, 605 passed overall. The 7 failures
in the full run reproduce identically at the pre-change commit and need a live
server on localhost:9000; they are unrelated to this change.

f"{TEMP_DIR}/base_llvm_coverage.meta.json"
)
_selected_base_file = Path(TEMP_DIR) / "selected_base_commit.txt"
_selected_base_commit = (

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.

We now capture the actually selected baseline here because it can differ from base_commit_sha, but the later coverage_comment.json payload still serializes base_commit_sha. Whenever generate_diff_coverage_report.sh skips the nearest ancestor and picks an older complete one, coverage_ci.coverage_data will attribute the delta to the wrong master revision. Please plumb _selected_base_commit through to the emitted metadata so the stored row matches the report that was actually generated.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 33b26ce. coverage_comment.json now serializes _selected_base_commit, falling back to base_commit_sha only when no marker exists. Details and the verification of both findings are in #112832 (comment).

…he one it used

Two independent defects in the completeness protocol, both reported by the
automated reviewer on the PR.

The baseline selector's first pass tested only `complete` + `manifest_fp`, while
`comparable` additionally rejects a newer `schema_version` and a torn
`info_digest`/`.info` pair. A candidate that passes the weaker test and fails the
stronger one therefore won selection and then forced the whole job to SKIPPED,
instead of walking on to the next usable ancestor. A gate that disables itself on
an avoidable input is the failure mode this protocol exists to prevent, so the
selector now applies `comparable` itself rather than an approximation of it. That
needs the candidate's `.info` bytes for the digest check, so the download moves
above the decision; a rejected candidate's files are removed before the walk
continues. Pass 2 is unchanged and still selects exactly as before, which is what
keeps the change backward compatible while master has not yet republished.

The emitted metadata attributed the delta to the wrong revision. The job captures
the ancestor that was actually selected, but `coverage_comment.json` kept
serializing `base_commit_sha`, the NEAREST master ancestor. Whenever the selector
walks past it, every consumer of `coverage_ci.coverage_data` reads a delta against
a revision that was never measured, with nothing in the payload revealing the
substitution. It now stores the selected commit, falling back to the nearest one
when no marker exists so the row never loses its baseline key.

Six test rows, each verified to fail without its fix: two selector rows for the
two causes `comparable` rejects after download, one reverse-direction row proving
pass 1 still selects a usable candidate, and the payload rows. The selector
harness now imports the real completeness module through `WORKSPACE_PATH`, so the
predicate under test is the production function.
@alexbakharew

Copy link
Copy Markdown
Contributor

Closing as over-engineered for the problem it solves. The invariant it establishes (a coverage verdict only from two complete measurements) is right, and the analysis in this PR was what surfaced the failure routes - but the completeness sidecar, the manifest fingerprint, and the two-pass baseline selector can be replaced by a simpler rule: the LLVM Coverage job checks the expected shard-profile set itself and, on any shortfall, reports SKIPPED and publishes nothing (no llvm_coverage.info, no CI DB row). "An .info exists for a master commit" then means "that measurement was complete", which the existing baseline selection already keys on - no metadata needed.

Superseded by #115623, which implements that design (~460 added lines vs ~3200 here), keeps the per-artifact profile naming and --failure-mode=any from this PR, and additionally fixes the root cause of the recurring shard 4/8 profile corruption (LLVM continuous mode, %c + -mllvm -runtime-counter-relocation). Accepted residuals of the simpler design vs this PR: a session-timeout-truncated shard can still publish a valid short profile, and verdicts are unreliable for ~30 master commits when the coverage artifact manifest itself changes - both rare and bounded.

pull Bot pushed a commit to Haofei/ClickHouse that referenced this pull request Aug 27, 2026
…ofiles kill-safe

The `LLVM Coverage` gate compares two totals merged from 21 per-shard
`.profdata` artifacts that are `optional=True`, and nothing checked that
either side had all of them. A missing shard on the PR side fails an innocent
PR ("Coverage degraded" by 0.5 pp on a 102-line PR); a missing shard on a
master run writes a low baseline into the CI DB, so later real regressions
pass invisibly. Observed twice in 60 days, both times the same shard:
`Integration tests (amd_llvm_coverage, 4/8)` merged only 20 of 21 profiles
while every check was green.

Examples:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110186&sha=0b33f54bc8089ea3560397c589e93dc6aec92d47&name_0=PR&name_1=LLVM%20Coverage
(ClickHouse#110186)
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=105844&sha=66107bb44ab45a490e839225eb096e46204e5e86&name_0=PR&name_1=LLVM%20Coverage
(ClickHouse#105844)

The invariant: a verdict comes only from two complete measurements.

- Every coverage producer (FT, IT, unit) names its profile after its own
  artifact (`<artifact>.profdata`), so the filename carries the shard
  identity. Producer merges use `--failure-mode=any` and skip zero-length
  `.profraw` inputs: a shard with invalid data is absent, never silently
  short. Artifacts stay `optional=True`, so a missing profile never reddens
  a green test job.
- The `LLVM Coverage` job checks the expected set against what arrived and
  merges an explicit file list (no `*.profdata` glob). On a missing or
  invalid shard it reports `SKIPPED` with the shard name and withholds every
  comparative output: no verdict, no GitHub comment, no `llvm_coverage.info`,
  no CI DB row. Baseline completeness then needs no metadata: the diff script
  already selects the first master ancestor that has an `.info`, and after
  this change such an `.info` exists only for complete runs.
- Under coverage the IT sequential phase runs regardless of how many parallel
  tests failed (`MAX_FAILS_BEFORE_DROP`), so a green shard cannot silently
  publish a profile short by the whole sequential phase.
- Root cause of the recurring shard 4/8 loss: a `SIGKILL` during the
  exit-time profile write leaves a half-written `.profraw` whose header makes
  `llvm-profdata` abort with "LLVM ERROR: out of memory"
  (llvm/llvm-project#50970). Coverage builds now
  compile with `-mllvm -runtime-counter-relocation` and run with `%c`
  (continuous mode): counters are memory-mapped into the file, which is valid
  at every instant, so kills lose nothing and corrupt nothing.

Related: ClickHouse#112832

Co-Authored-By: Claude Fable 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 groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work manual approve Manual approve required to run CI pr-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants